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
refactor: add generic asset build transforms and fix WeChat audio playback
esengine6147f31c042d
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.jsindex 6a0c9cf0c..7cc1b3b8b 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}function s(){return"wechat"===e?.name}async function n(e,s){return t().fetch(e,s)}async function i(e){return t().readFile(e)}async function o(e){return t().readTextFile(e)}async function r(e){return t().fileExists(e)}async function a(e,s){return t().instantiateWasm(e,s)}function l(e,s){return t().createCanvas(e,s)}function c(){return t().now()}function u(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}class d{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,t.volume??1)),this.muted_=t.muted??!1,this.gainNode_.gain.value=this.muted_?0:this.volume_}get name(){return this.name_}get node(){return this.gainNode_}get volume(){return this.volume_}set volume(e){this.volume_=Math.max(0,Math.min(1,e)),this.muted_||this.gainNode_.gain.setTargetAtTime(this.volume_,this.gainNode_.context.currentTime,.015)}get muted(){return this.muted_}set muted(e){this.muted_=e,this.gainNode_.gain.setTargetAtTime(e?0:this.volume_,this.gainNode_.context.currentTime,.015)}connect(e){e instanceof d?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class h{constructor(e,t,s){this.panWarned_=!1,this.id=e,this.ctx_=t,this.contexts_=s}stop(){this.ctx_.stop(),this.ctx_.destroy(),this.contexts_.delete(this.id)}pause(){this.ctx_.pause()}resume(){this.ctx_.play()}setVolume(e){this.ctx_.volume=e}setPan(e){this.panWarned_||(console.warn("[Audio] WeChat InnerAudioContext does not support stereo panning"),this.panWarned_=!0)}setLoop(e){this.ctx_.loop=e}setPlaybackRate(e){this.ctx_.playbackRate=e}get isPlaying(){return!this.ctx_.paused}get currentTime(){return this.ctx_.currentTime}get duration(){return this.ctx_.duration}}class p{constructor(){this.name="WeChat",this.contexts_=new Map,this.urlCache_=new Map,this.nextId_=0}get mixer(){return null}get isReady(){return!0}async initialize(e){}async ensureResumed(){}async loadBuffer(e){const t=++this.nextId_;return this.urlCache_.set(t,e),{id:t,duration:0}}unloadBuffer(e){this.urlCache_.delete(e.id)}play(e,t){const s=this.urlCache_.get(e.id);if(!s)throw new Error(`Buffer ${e.id} not found`);const n=wx.createInnerAudioContext();n.src=s,n.loop=t.loop??!1,n.volume=t.volume??1,n.playbackRate=t.playbackRate??1,n.startTime=t.startOffset??0,n.obeyMuteSwitch=!1;const i=++this.nextId_;this.contexts_.set(i,n);const o=new h(i,n,this.contexts_);return n.onEnded(()=>{o.onEnd?.(),n.loop||(n.destroy(),this.contexts_.delete(i))}),n.autoplay=!0,o}suspend(){for(const e of this.contexts_.values())e.pause()}resume(){for(const e of this.contexts_.values())e.paused&&e.play()}dispose(){for(const e of this.contexts_.values())e.destroy();this.contexts_.clear(),this.urlCache_.clear()}}function f(e,t){return new Promise((s,n)=>{const i=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===i?"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 m(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 g=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],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},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0}],y={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",bmfont:"application/json",fnt:"text/plain"},_=new Map,x=new Set;for(const e of g)for(const t of e.extensions)_.set(t,e),x.add(t);function w(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function v(e){return _.get(w(e))}function b(e){return x.has(e.toLowerCase())}function S(){const e=[];for(const t of g)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function P(e){const t=v(e);return t?.wechatPackInclude??!1}function M(e){const t=v(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const s=e.lastIndexOf(".");return s>=0?e.substring(0,s)+".json":e}let T=null;function E(){return T||(T=wx.getFileSystemManager()),T}function C(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(P(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 A(e){const t=E();try{return t.accessSync(e),!0}catch{return!1}}function R(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 I(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 i=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(i.data.buffer)}}async function F(e){return I(await R(e))}let k=!1;const B=new class{constructor(){this.name="wechat",this.inputCleanup_=null}async fetch(e,t){return f(e,t)}async readFile(e){return function(e){return E().readFileSync(e)}(M(e))}async readTextFile(e){return function(e,t="utf-8"){return E().readFileSync(e,t)}(M(e))}async fileExists(e){return A(M(e))}async loadImagePixels(e){return F(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return m(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){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const s=t=>e.onKeyDown(t.code),n=t=>e.onKeyUp(t.code),i="function"==typeof wx.onKeyDown;i&&(wx.onKeyDown(s),wx.onKeyUp(n));const o=t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX,s.clientY)},r=t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX,s.clientY)},a=t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)};wx.onTouchStart(o),wx.onTouchMove(r),wx.onTouchEnd(a),this.inputCleanup_=()=>{i&&(wx.offKeyDown(s),wx.offKeyUp(n)),wx.offTouchStart(o),wx.offTouchMove(r),wx.offTouchEnd(a)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new p}},D=1920,U=1080,L=1/60,W={x:0,y:-9.81},z=1/60,$={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};const O={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function H(e,t){if(void 0!==t.maxDeltaTime&&($.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&($.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&($.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&($.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&($.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");$.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&($.canvasScaleMode=O[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&($.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight)}const X=4294967295,j=4294967295;function V(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(V);const t={};for(const s in e)t[s]=V(e[s]);return t}let N=0;function Y(e,t){const s=++N,n=function(e){for(const t in e){const s=e[t];if(null!==s&&"object"==typeof s)return!0}return!1}(t);return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>n?e?{...V(t),...e}:V(t):e?{...t,...e}:{...t}}}function G(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function q(e,t){const s=Z.get(e)??G().get(e);if(s)return s;const n=Y(e,t);return G().set(e,n),Z.set(e,n),J(e,t,!1),n}function K(e){return G().get(e)}function J(e,t,s){const n=globalThis;n.__esengine_registerComponent&&n.__esengine_registerComponent(e,t,s)}function Q(e){return!0===e._builtin}const Z=new Map;function ee(e,t){Z.set(e,t)}function te(e){return Z.get(e)??K(e)}function se(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return Z.set(e,s),s}const ne={Perspective:0,Orthographic:1},ie={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},oe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},re=se("Transform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}}),ae=re,le=re,ce=se("Sprite",{texture:X,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),ue=se("Camera",{projectionType:ne.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:ie.ColorAndDepth}),de=se("Canvas",{designResolution:{x:D,y:U},pixelsPerUnit:100,scaleMode:oe.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),he=se("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),pe=se("Parent",{entity:0}),fe=se("Children",{entities:[]}),me=se("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:j,enabled:!0}),ge=se("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),ye=q("Name",{value:""}),_e=q("SceneOwner",{scene:"",persistent:!1});const xe=se("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),we=se("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ve=se("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),be=se("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Se={Static:0,Kinematic:1,Dynamic:2};let Pe=0;function Me(e,t){const s=++Pe;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function Te(e){return{_type:"res",_resource:e}}function Ee(e){return{_type:"res_mut",_resource:e}}class Ce{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class Ae{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new Ce(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Re=Me({delta:0,elapsed:0,frameCount:0},"Time");function Ie(e,t,s){const n=[];for(const[e,i]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const s=Fe(t[e]),o=Fe(i);"null"!==s&&"undefined"!==s&&(s!==o&&null!=i&&n.push({field:e,expected:s,actual:o,value:i}))}return n}function Fe(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ke(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}let Be=null;function De(e){Be=e}function Ue(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Be&&Be(e,t)}function Le(e){let t=!1;for(const s of Object.keys(e)){const n=e[s];if(null!=n&&"object"==typeof n&&!Array.isArray(n)){if("r"in n&&"g"in n&&"b"in n&&"a"in n&&!("x"in n)){t=!0;break}}}if(!t)return e;const s={};for(const t of Object.keys(e)){const n=e[t];if(null==n||"object"!=typeof n||Array.isArray(n))s[t]=n;else{const e=n;s[t]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:n}}return s}let We=1;const ze=new WeakMap;function $e(e){let t=ze.get(e);return void 0===t&&(t=We++,ze.set(e,t)),t}const Oe=[];function He(e,t=[],s=[]){Oe.length=0;for(const t of e)Oe.push($e(t));Oe.sort((e,t)=>e-t);let n=Oe.join(",");if(t.length>0){Oe.length=0;for(const e of t)Oe.push($e(e));Oe.sort((e,t)=>e-t),n+="|+"+Oe.join(",")}if(s.length>0){Oe.length=0;for(const e of s)Oe.push($e(e));Oe.sort((e,t)=>e-t),n+="|-"+Oe.join(",")}return n}class Xe{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw Ue(e,"spawn"),e}else e=++this.nextEntityId_;let t=0;if(this.module_&&this.cppRegistry_)try{t=this.module_.registry_getGeneration(this.cppRegistry_,e)}catch{}else t=++this.nextGeneration_;this.entities_.set(e,t),this.worldVersion_++;for(const t of this.spawnCallbacks_)try{t(e)}catch{}return e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch{}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){Ue(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t){this.tsStorage_.get(s)?.delete(e),this.componentAddedTicks_.get(s)?.delete(e),this.componentChangedTicks_.get(s)?.delete(e);let t=this.componentRemovedBuffer_.get(s);t||(t=[],this.componentRemovedBuffer_.set(s,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){Ue(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Ue(t,`removeParent(entity=${e})`)}}insert(e,t,s){return Q(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}set(e,t,s){if(Q(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,Le(s))}catch(s){Ue(s,`set(${t._name}, entity=${e})`)}this.recordChangedTick_(t,e)}else this.getStorage(t).set(e,s),this.recordChangedTick_(t,e)}get(e,t){return Q(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return Q(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(Q(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return Ue(s,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");Q(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_,n=s[`add${e}`],i=s[`get${e}`],o=s[`has${e}`],r=s[`remove${e}`];if("function"!=typeof n||"function"!=typeof i||"function"!=typeof o||"function"!=typeof r)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:n.bind(s),get:i.bind(s),has:o.bind(s),remove:r.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(ke(t._name,e))}const i={...t._default,...n};let o=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(t._cppName);o=!s.has(e),s.add(e,Le(i))}catch(s){Ue(s,`insertBuiltin(${t._name}, entity=${e})`)}return o&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let s=!1;for(const n of Object.keys(t)){const i=t[n];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){const t=e[n];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){s=!0;break}}}if(!s)return e;const n={};for(const s of Object.keys(e)){const i=e[s],o=t[s];if(null==i||"object"!=typeof i||Array.isArray(i)||null==o||"object"!=typeof o||Array.isArray(o))n[s]=i;else{const e=i,t=o;n[s]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:i}}return n}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(s){return Ue(s,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(s){return Ue(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Ue(s,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++}}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 i=Ie(t._name,t._default,e);if(i.length>0)throw new Error(ke(t._name,i));n=e}const i=t.create(n),o=this.getStorage(t),r=!o.has(e);o.set(e,i);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}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.recordRemovedTick_(t,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}getComponentTypes(e){const t=new Set;for(const[s,n]of this.builtinMethodCache_)try{n.has(e)&&t.add(s)}catch{}if(this.cppRegistry_)for(const[s,n]of Z)if(Q(n)&&!t.has(s))try{this.getBuiltinMethods(n._cppName).has(e)&&t.add(s)}catch{}const s=this.entityComponents_.get(e);if(s){const e=G();for(const n of s)for(const[s,i]of e)if(i._id===n){t.add(s);break}}return Array.from(t)}getEntitiesWithComponents(e,t=[],s=[],n){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();const i=n??He(e,t,s),o=this.queryCache_.get(i);if(o&&o.version===this.worldVersion_)return o.result;let r=null,a=1/0;for(const t of e)if(!Q(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<a&&(a=s,r=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=r?r.keys():this.entities_.keys();for(const n of c){let i=!0;for(const t of e)if(!this.has(n,t)){i=!1;break}if(i)for(const e of t)if(!this.has(n,e)){i=!1;break}if(i)for(const e of s)if(this.has(n,e)){i=!1;break}i&&l.push(n)}return this.queryCache_.set(i,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,s){const n=this.componentAddedTicks_.get(t._id);if(!n)return!1;const i=n.get(e);return void 0!==i&&i>s}isChangedSince(e,t,s){const n=this.componentChangedTicks_.get(t._id);if(!n)return!1;const i=n.get(e);return void 0!==i&&i>s}getRemovedEntitiesSince(e,t){const s=this.componentRemovedBuffer_.get(e._id);if(!s)return[];const n=[];for(const e of s)e.tick>t&&n.push(e.entity);return n}cleanRemovedBuffer(e){for(const[t,s]of this.componentRemovedBuffer_){let n=0;for(let t=0;t<s.length;t++)s[t].tick>=e&&(s[n++]=s[t]);s.length=n,0===n&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let s=this.componentAddedTicks_.get(e._id);s||(s=new Map,this.componentAddedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordChangedTick_(e,t){let s=this.componentChangedTicks_.get(e._id);s||(s=new Map,this.componentChangedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordRemovedTick_(e,t){let s=this.componentRemovedBuffer_.get(e._id);s||(s=[],this.componentRemovedBuffer_.set(e._id,s)),s.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function je(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Ve(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Ne(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Ye(e){return je(e)||Ve(e)||Ne(e)?e._component:e}function Ge(e,t=[],s=[]){const n=[],i=[],o=[];return e.forEach((e,t)=>{je(e)&&n.push(t),Ve(e)?i.push({index:t,component:e._component}):Ne(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s,_addedFilters:i,_changedFilters:o,with:(...n)=>Ge(e,[...t,...n],s),without:(...n)=>Ge(e,t,[...s,...n])}}class qe{constructor(e,t,s=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=s,this.actualComponents_=t._components.map(Ye),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=He(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:s}=this.descriptor_;if(0===t.length&&0===s.length)return!0;const n=this.lastRunTick_;for(const s of t)if(!this.world_.isAddedSince(e,s.component,n))return!1;for(const t of s)if(!this.world_.isChangedSince(e,t.component,n))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),n=t.length,i=e.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const u of s)if(!o||this.passesChangeFilters_(u)){if(null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}r[0]=u;for(let e=0;e<n;e++)r[e+1]=this.world_.get(u,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];c=u}yield r}}finally{if(this.world_.endIteration(),null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class Ke{constructor(e,t,s){this.world_=e,this.component_=t,this.lastRunTick_=s}*[Symbol.iterator](){yield*this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}isEmpty(){return 0===this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_).length}toArray(){return this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}}class Je{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=Q(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Qe{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Je(this,null);return this.spawned_.push(e),e}entity(e){return new Je(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"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)}}}class Ze{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(e){this.writeBuffer_.push(e)}getReadBuffer(){return this.readBuffer_}swap(){const e=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=e,this.writeBuffer_.length=0}}class et{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Ze)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Ze,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}class tt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class st{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var nt;function it(){return{_type:"get_world"}}exports.Schedule=void 0,(nt=exports.Schedule||(exports.Schedule={}))[nt.Startup=0]="Startup",nt[nt.First=1]="First",nt[nt.PreUpdate=2]="PreUpdate",nt[nt.Update=3]="Update",nt[nt.PostUpdate=4]="PostUpdate",nt[nt.Last=5]="Last",nt[nt.FixedPreUpdate=10]="FixedPreUpdate",nt[nt.FixedUpdate=11]="FixedUpdate",nt[nt.FixedPostUpdate=12]="FixedPostUpdate";let ot=0;function rt(e,t,s){const n=++ot;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function at(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}class lt{constructor(e,t,s){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=s??null}setTimingEnabled(e){this.timings_=e?new Map:null}getTimings(){return this.timings_}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);const s=this.timings_?performance.now():0;try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Qe&&t[e].flush()}finally{this.timings_&&this.timings_.set(e._name,performance.now()-s),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new qe(this.world_,e,this.currentLastRunTick_);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Qe(this.world_,this.resources_);case"event_writer":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new tt(s)}case"event_reader":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new st(s)}case"removed":{const t=e;return new Ke(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class ct{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 ut=Me(new ct,"Input");class dt{constructor(e){this.target_=e??null}build(e){const s=new ct;e.insertResource(ut,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,rt([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ht=new dt,pt=Me({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var ft;function mt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(ft=exports.BlendMode||(exports.BlendMode={}))[ft.Normal=0]="Normal",ft[ft.Additive=1]="Additive",ft[ft.Multiply=2]="Multiply",ft[ft.Screen=3]="Screen",ft[ft.PremultipliedAlpha=4]="PremultipliedAlpha";let gt=null,yt=null,_t=1;const xt=new Map;function wt(e){gt=e,yt=e.getResourceManager(),Rt()}function vt(){0!==Mt&>&&(gt._free(Mt),Mt=0),xt.clear(),_t=1,Pt=!1,Et.clear(),Ct=null,yt=null,gt=null}function bt(){if(!yt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return yt}const St={createShader:(e,t)=>bt().createShader(e,t),releaseShader(e){e>0&&bt().releaseShader(e)},create(e){const t=_t++,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 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,gt?.invalidateMaterialCache(e))},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,gt?.invalidateMaterialCache(e))},getBlendMode(e){const t=xt.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=xt.get(e);s&&(s.depthTest=t,gt?.invalidateMaterialCache(e))},getShader(e){const t=xt.get(e);return t?.shader??0},release(e){xt.delete(e),gt?.invalidateMaterialCache(e)},isValid:e=>xt.has(e),releaseAll(){xt.clear(),gt?.clearMaterialCache()},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=xt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=_t++,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 Pt=!1,Mt=0;const Tt=16384,Et=new Map;let Ct=null;function At(e){const t=(0===Mt&>&&(Mt=gt._malloc(Tt)),Mt);if(0===t||!gt)return{ptr:0,count:0};let s=0,n=0;const i=gt.HEAPU8,o=gt.HEAPU32,r=gt.HEAPF32;for(const[a,l]of e){if(mt(l))continue;let e=Et.get(a);e||(Ct||(Ct=new TextEncoder),e=Ct.encode(a),Et.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(s+(4+u+4+16)>Tt){console.warn(`[ESEngine] Material uniform buffer full (${s}/${Tt} bytes), skipping remaining uniforms`);break}o[t+s>>2]=c,s+=4,i.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++)r[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function Rt(){if(!gt||Pt)return;gt.materialDataProvider=(e,t,s,n,i)=>{const o=xt.get(e);if(!o)return gt.HEAPU32[t>>2]=0,gt.HEAPU32[s>>2]=0,gt.HEAPU32[n>>2]=0,void(gt.HEAPU32[i>>2]=0);gt.HEAPU32[t>>2]=o.shader,gt.HEAPU32[s>>2]=o.blendMode;const{ptr:r,count:a}=At(o.uniforms);gt.HEAPU32[n>>2]=r,gt.HEAPU32[i>>2]=a},Pt=!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,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const i=this.pending_.get(e);if(i&&!i.aborted)return i.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),i=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,i),this.pending_.delete(e),i})(),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 kt{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&&(St.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())St.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await r(t))throw new Error(`Material file not found: ${t}`);const s=await o(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:St.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}}function Bt(e){const t=new Set;for(const s of e.frames)s.texture&&t.add(s.texture);return Array.from(t)}function Dt(e,t,s){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>({texture:s.get(e.texture)??0}))}}const Ut=new Map;function Lt(e){Ut.set(e.name,e)}const Wt=q("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function zt(e,t){const s=e.getEntitiesWithComponents([Wt]);for(const n of s){const s=e.get(n,Wt);if(!s.enabled||!s.playing||!s.clip)continue;const i=Ut.get(s.clip);if(!i||0===i.frames.length)continue;const o=1/(i.fps*s.speed),r=0===s.frameTimer&&0===s.currentFrame;s.frameTimer+=t;let a=r;if(s.frameTimer>=o&&(s.frameTimer-=o,s.currentFrame++,s.currentFrame>=i.frames.length&&(s.loop&&i.loop?s.currentFrame=0:(s.currentFrame=i.frames.length-1,s.playing=!1)),a=!0),a&&e.has(n,ce)){const t=i.frames[s.currentFrame],o=e.get(n,ce);o.texture=t.texture,e.insert(n,ce,o)}a&&e.insert(n,Wt,s)}}class $t{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null,this.bgmVolume_=1,this.disposed_=!1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}static async preload(e){if(this.bufferCache_.has(e))return;const t=await this.backend_.loadBuffer(e);this.bufferCache_.set(e,t)}static async preloadAll(e){await Promise.all(e.map(e=>this.preload(e)))}static playSFX(e,t){const s={bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0},n=this.bufferCache_.get(e);if(!n){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const n=this.bufferCache_.get(e);n&&t.resolve(this.backend_.play(n,s))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(n,s)}static playBGM(e,t){const s=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const s=t?.volume??1,n=this.bgmVolume_;this.bgmVolume_=s,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,n):this.bgmHandle_&&this.bgmHandle_.stop();const i=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:i?0:s,loop:!0}),i&&this.fadeIn(this.bgmHandle_,i,s)},n=this.bufferCache_.get(e);n?s(n):this.preload(e).then(()=>{if(this.disposed_)return;const t=this.bufferCache_.get(e);t&&s(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else this.bgmHandle_.stop(),this.bgmHandle_=null}static setMasterVolume(e){this.mixer_&&(this.mixer_.master.volume=e)}static setMusicVolume(e){this.mixer_&&(this.mixer_.music.volume=e)}static setSFXVolume(e){this.mixer_&&(this.mixer_.sfx.volume=e)}static setUIVolume(e){this.mixer_&&(this.mixer_.ui.volume=e)}static muteBus(e,t){const s=this.mixer_?.getBus(e);s&&(s.muted=t)}static getBufferHandle(e){return this.bufferCache_.get(e)}static dispose(){this.disposed_=!0,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}static fadeIn(e,t,s){e.setVolume(0);const n=performance.now(),i=()=>{const o=(performance.now()-n)/1e3,r=Math.min(o/t,1);e.setVolume(r*s),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,s){const n=performance.now(),i=()=>{const o=(performance.now()-n)/1e3,r=Math.min(o/t,1);e.setVolume(s*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}static createDeferredHandle(){let e=null;return{id:-1,stop(){e?.stop()},pause(){e?.pause()},resume(){e?.resume()},setVolume(t){e?.setVolume(t)},setPan(t){e?.setPan(t)},setLoop(t){e?.setLoop(t)},setPlaybackRate(t){e?.setPlaybackRate(t)},get isPlaying(){return e?.isPlaying??!1},get currentTime(){return e?.currentTime??0},get duration(){return e?.duration??0},resolve(t){e=t}}}}$t.mixer_=null,$t.bufferCache_=new Map,$t.bgmHandle_=null,$t.bgmVolume_=1,$t.fadeAnimId_=0,$t.disposed_=!1;const Ot=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}],["AudioSource",{fields:[{field:"clip",type:"audio"}]}]]);function Ht(e){const t=Ot.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s}function Xt(e){return Ot.get(e)?.fields??[]}function jt(e){return Ot.get(e)?.spine??null}const Vt=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Nt(e){return Vt.get(e)}function Yt(e,t){const s=Vt.get(e.type);if(!s)return;const n=e.data;for(const i of s){const s=n[i];if("number"==typeof s&&0!==s){const o=t.get(s);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${s} which does not exist`),n[i]=void 0!==o?o:0}}}function Gt(e,t){const s=new Map;for(const n of t.entities){if(!1===n.visible)continue;const t=e.spawn();s.set(n.id,t),e.insert(t,ye,{value:n.name})}for(const n of t.entities){if(!1===n.visible)continue;const t=s.get(n.id);for(const i of n.components)Yt(i,s),Qt(e,t,i,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),i=s.get(n.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return s}function qt(e,t){return Gt(e,t)}async function Kt(e,t,s){const n=s?.assetServer,i=s?.assetBaseUrl??n?.baseUrl,o=new Map;n&&await async function(e,t,s,n,i){const o=new Map;for(const e of Jt.keys())o.set(e,new Set);const r=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ot.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...Jt.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,s,n);l.set(e,r)}),u=r.map(async e=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)});if(await Promise.all([...c,...u]),i){for(const e of n.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ot.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const n=s[e.field];if("string"!=typeof n||!n)continue;const i=t.get(n);void 0!==i&&(s[e.field]=i)}}}(t,n,i,o,s?.collectAssets);const r=Gt(e,t);if(n&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&n.setTextureMetadataByPath(t,s.sliceBorder)}return r}const Jt=new Map([["texture",{async load(e,t,s,n){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),n.set(e,o)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(o),i}}],["material",{async load(e,t,s){const n=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,s);n.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),n.set(e,0)}});return await Promise.all(i),n}}],["font",{async load(e,t,s){const n=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,s);n.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),n.set(e,0)}});return await Promise.all(i),n}}],["anim-clip",{async load(e,t,s,n){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=Bt(i),r=new Map,a=o.map(async e=>{try{const i=s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),n.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);Lt(Dt(e,i,r))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(i),new Map}}],["audio",{async load(e,t,s){const n=[...e].map(e=>s?`${s}/${e}`:`/${e}`);return await $t.preloadAll(n).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}]]);function Qt(e,t,s,n){if("LocalTransform"!==s.type&&"WorldTransform"!==s.type||(s.type="Transform"),"UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===s.type){const e=s.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=te(s.type);if(i)e.insert(t,i,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function Zt(e,t){const s=e.getEntitiesWithComponents([ue]);for(const n of s){const s=e.get(n,ue);s&&(s.aspectRatio=t,e.insert(n,ue,s))}}class es{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.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=l($.textCanvasSize,$.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new kt(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),i=this.textureCache_.get(n);if(!i)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),St.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const i=this.resolveUrl(t,s),o=await this.fetchText(i);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=r?`${r}/${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"===v(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),i=l.find(e=>e.name===s);if(i){const s=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,i.info.width,i.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}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=v(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 i=s?`${s}/${n}`:n;return this.loadFntFile(i)}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],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${n}`:n,r=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,r.handle,r.width,r.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,async()=>{const e=await this.fetchJson(s);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const s of e.entities){for(const e of s.components){if(!e.data)continue;for(const s of Ht(e.type)){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}const s=jt(e.type);if(s)for(const n of[s.skeletonField,s.atlasField]){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}}if(s.nestedPrefab?.prefabPath){const e=t(s.nestedPrefab.prefabPath);e&&(s.nestedPrefab.prefabPath=e)}}}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const 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 Kt(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 i=n.metadata?.atlas;i&&s.push(this.loadSpine(n.path,i).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return this.loadImageFromSrc(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){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=e})}createTextureFromImage(e,t){const{width:s,height:n}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,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,i){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const r=this.module_.GL,a=r.getNewId(r.textures);r.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 i=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(o);const r=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=r.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.getEmbedded(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:i}=this.parseEsShader(t);if(!n||!i)throw new Error(`Invalid shader format: ${e}`);return St.createShader(n,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await r(t))throw new Error(`Shader file not found: ${e}`);const n=await o(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 St.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://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(M(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(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.getEmbedded(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return o(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(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.getEmbedded(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return i(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(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 i="";for(const e of n){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const 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 ts=Me(null,"Assets");class ss{build(e){const t=e.wasmModule;t?e.insertResource(ts,new es(t)):console.warn("AssetPlugin: No WASM module available")}}const ns=new ss;async function is(e,t,s){const{entities:n,rootId:i}=await rs(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}))},r=await Kt(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=r.get(i);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:r}}const os=10;async function rs(e,t,s,n,i,o=0){if(o>os)throw new Error(`Prefab nesting depth exceeded ${os}. Check for deep or circular nesting in: ${e.name}`);const r=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,a++)}const l=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(i?.has(n.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${n.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await rs(e,n.nestedPrefab.overrides,s,a,i,o+1);r.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?r.get(n.parent)??null:null),l.push(...t.entities);continue}const c=r.get(n.prefabEntityId),u=n.prefabEntityId===e.rootEntityId,d={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?null:null!==n.parent?r.get(n.parent)??null:null,children:n.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};as(d.components,r),ls(d,t),l.push(d)}const c=r.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function as(e,t){for(const s of e){const e=Nt(s.type);if(e)for(const n of e){const e=s.data[n];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(s.data[n]=i)}}}}function ls(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 cs{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,i=await this.assetServer_.loadPrefab(n,t?.baseUrl);return is(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const us=Me(null,"Prefabs");class ds{constructor(){this.name="PrefabsPlugin",this.dependencies=[ts]}build(e){const t=e.getResource(ts);e.insertResource(us,new cs(e.world,t))}}const hs=new ds;let ps=null,fs=0,ms=0,gs=0;const ys=new Float32Array(256);function _s(e){ps=e,fs=ps._malloc(64),ms=ps._malloc(64),gs=ps._malloc(1024)}function xs(){ps&&(fs&&(ps._free(fs),fs=0),ms&&(ps._free(ms),ms=0),gs&&(ps._free(gs),gs=0)),ps=null}function ws(){if(!ps)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return ps}const vs={r:1,g:1,b:1,a:1},bs={begin(e){const t=ws();try{t.HEAPF32.set(e,fs/4),t.draw_begin(fs)}catch(e){Ue(e,"Draw.begin")}},end(){try{ws().draw_end()}catch(e){Ue(e,"Draw.end")}},line(e,t,s,n=1){try{ws().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ue(e,"Draw.line")}},rect(e,t,s,n=!0){try{ws().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ue(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{ws().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ue(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,i=32){try{ws().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){Ue(e,"Draw.circle")}},circleOutline(e,t,s,n=1,i=32){try{ws().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){Ue(e,"Draw.circleOutline")}},texture(e,t,s,n=vs){try{ws().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Ue(e,"Draw.texture")}},textureRotated(e,t,s,n,i=vs){try{ws().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,i.r,i.g,i.b,i.a)}catch(e){Ue(e,"Draw.textureRotated")}},setLayer(e){ws().draw_setLayer(e)},setDepth(e){ws().draw_setDepth(e)},getDrawCallCount:()=>ps?ps.draw_getDrawCallCount():0,getPrimitiveCount:()=>ps?ps.draw_getPrimitiveCount():0,setBlendMode(e){ws().draw_setBlendMode(e)},setDepthTest(e){ws().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=ws();n.HEAPF32.set(s,ms/4),n.draw_mesh(e,t,ms)}catch(s){Ue(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=ws(),i=St.get(t);if(!i)return;if(bs.setBlendMode(i.blendMode),bs.setDepthTest(i.depthTest),0===i.uniforms.size)return void bs.drawMesh(e,i.shader,s);let o;if(n.HEAPF32.set(s,ms/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,s]of i.uniforms){const n=Ms(t);if(!(n<0)){if(mt(s))ys[o++]=10,ys[o++]=n,ys[o++]=s.slot??e++,ys[o++]=s.textureId;else if("number"==typeof s)ys[o++]=1,ys[o++]=n,ys[o++]=s;else if(Array.isArray(s)){ys[o++]=s.length,ys[o++]=n;for(let e=0;e<s.length;e++)ys[o++]=s[e]}else"w"in s?(ys[o++]=4,ys[o++]=n,ys[o++]=s.x,ys[o++]=s.y,ys[o++]=s.z,ys[o++]=s.w):"z"in s?(ys[o++]=3,ys[o++]=n,ys[o++]=s.x,ys[o++]=s.y,ys[o++]=s.z):(ys[o++]=2,ys[o++]=n,ys[o++]=s.x,ys[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<o)&&(i.cachedBuffer_=new Float32Array(o)),i.cachedBuffer_.set(ys.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void n.draw_mesh(e,i.shader,ms);n.HEAPF32.set(i.cachedBuffer_.subarray(0,o),gs/4),n.draw_meshWithUniforms(e,i.shader,ms,gs,o)}catch(s){Ue(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Ss={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17},Ps=new Set;function Ms(e){const t=Ss[e];return void 0!==t?t:(Ps.has(e)||(Ps.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Ss).join(", ")}`)),-1)}const Ts=new Map;function Es(e,t,s){Ts.set(e,{fn:t,scene:s??""})}function Cs(e){Ts.delete(e)}function As(){Ts.clear()}var Rs;exports.DataType=void 0,(Rs=exports.DataType||(exports.DataType={}))[Rs.Float=1]="Float",Rs[Rs.Float2=2]="Float2",Rs[Rs.Float3=3]="Float3",Rs[Rs.Float4=4]="Float4",Rs[Rs.Int=5]="Int",Rs[Rs.Int2=6]="Int2",Rs[Rs.Int3=7]="Int3",Rs[Rs.Int4=8]="Int4";let Is=null,Fs=0,ks=0,Bs=0;function Ds(e){Is=e,Fs=Is._malloc(262144),ks=Is._malloc(65536),Bs=Is._malloc(256)}function Us(){Is&&(Fs&&Is._free(Fs),ks&&Is._free(ks),Bs&&Is._free(Bs),Fs=0,ks=0,Bs=0),Is=null}function Ls(){if(!Is)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Is}const Ws={create(e){const t=Ls(),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,Fs/4);const i=e.layout.length,o=new Int32Array(i);for(let t=0;t<i;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Bs,i).set(o),t.geometry_init(s,Fs,n,Bs,i,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,ks,n).set(e.indices),t.geometry_setIndices16(s,ks,n)}else{new Uint32Array(t.HEAPU8.buffer,ks,n).set(e.indices),t.geometry_setIndices32(s,ks,n)}}return s},updateVertices(e,t,s=0){const n=Ls(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);n.HEAPF32.set(t,Fs/4),n.geometry_updateVertices(e,Fs,i,s)},release(e){e>0&&Ls().geometry_release(e)},isValid:e=>!(!Is||e<=0)&&Is.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Ws.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 i=n/t*Math.PI*2,o=Math.cos(i)*e,r=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;s.push(o,r,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Ws.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,i=-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),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(n-t),a=(r.y-s)/(i-s);o.push(r.x,r.y,e,a)}const r=[];for(let t=1;t<e.length-1;t++)r.push(0,t,t+1);return Ws.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(r)})}};let zs=null;function $s(e){zs=e}function Os(){zs&&Xs.isInitialized()&&Xs.shutdown(),zs=null}function Hs(){if(!zs)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return zs}const Xs={init(e,t){try{return Hs().postprocess_init(e,t)}catch(s){return Ue(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Hs().postprocess_shutdown()}catch(e){Ue(e,"PostProcess.shutdown")}},resize(e,t){try{Hs().postprocess_resize(e,t)}catch(s){Ue(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Hs().postprocess_addPass(e,t)}catch(t){return Ue(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Hs().postprocess_removePass(e)}catch(t){Ue(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Hs().postprocess_setPassEnabled(e,t)}catch(t){Ue(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Hs().postprocess_isPassEnabled(e)}catch(t){return Ue(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{Hs().postprocess_setUniformFloat(e,t,s)}catch(s){Ue(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{Hs().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){Ue(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Hs().postprocess_begin()}catch(e){Ue(e,"PostProcess.begin")}},end(){try{Hs().postprocess_end()}catch(e){Ue(e,"PostProcess.end")}},getPassCount(){try{return Hs().postprocess_getPassCount()}catch(e){return Ue(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!zs)return!1;try{return zs.postprocess_isInitialized()}catch(e){return Ue(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Hs().postprocess_setBypass(e)}catch(e){Ue(e,"PostProcess.setBypass")}},isBypassed(){if(!zs)return!0;try{return zs.postprocess_isBypassed()}catch(e){return Ue(e,"PostProcess.isBypassed"),!0}},createBlur:()=>St.createShader(js,"#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:()=>St.createShader(js,"#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:()=>St.createShader(js,"#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:()=>St.createShader(js,"#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")},js="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var Vs;exports.RenderStage=void 0,(Vs=exports.RenderStage||(exports.RenderStage={}))[Vs.Background=0]="Background",Vs[Vs.Opaque=1]="Opaque",Vs[Vs.Transparent=2]="Transparent",Vs[Vs.Overlay=3]="Overlay";let Ns=null,Ys=0;function Gs(e){Ns=e,Ys=Ns._malloc(64)}function qs(){Ns&&Ys&&(Ns._free(Ys),Ys=0),Ns=null}const Ks={init(e,t){Ns?.renderer_init(e,t)},resize(e,t){Ns?.renderer_resize(e,t)},begin(e,t){if(Ns&&Ys)try{Ns.HEAPF32.set(e,Ys/4),Ns.renderer_begin(Ys,t??0)}catch(e){Ue(e,"Renderer.begin")}},flush(){try{Ns?.renderer_flush()}catch(e){Ue(e,"Renderer.flush")}},end(){try{Ns?.renderer_end()}catch(e){Ue(e,"Renderer.end")}},submitSprites(e){if(Ns)try{Ns.renderer_submitSprites(e._cpp)}catch(e){Ue(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Ns)try{Ns.renderer_submitBitmapText(e._cpp)}catch(e){Ue(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Ns)try{Ns.renderer_submitSpine?.(e._cpp)}catch(e){Ue(e,"Renderer.submitSpine")}},setStage(e){Ns?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Ns?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Ns?.renderer_releaseTarget(e)},getTargetTexture:e=>Ns?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Ns?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Ns?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Ns?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,i){Ns?.renderer_setScissor(e,t,s,n,i)},clearBuffers(e){Ns?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Ns?Ns.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Ns?{drawCalls:Ns.renderer_getDrawCalls(),triangles:Ns.renderer_getTriangles(),sprites:Ns.renderer_getSprites(),text:Ns.renderer_getText(),spine:Ns.renderer_getSpine?.()??0,meshes:Ns.renderer_getMeshes(),culled:Ns.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Js=null;function Qs(e){Js=e}function Zs(){Js=null}const en={enable(){Js?.gl_enableErrorCheck(!0)},disable(){Js?.gl_enableErrorCheck(!1)},check:e=>Js?.gl_checkErrors(e)??0,diagnose(){Js?.renderer_diagnose()}};class tn{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:i,elapsed:o}=e;n===this.lastWidth_&&i===this.lastHeight_||(Ks.resize(n,i),Xs.isInitialized()&&Xs.getPassCount()>0&&Xs.resize(n,i),this.lastWidth_=n,this.lastHeight_=i),Ks.setViewport(0,0,n,i),Ks.clearBuffers(3),Ks.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,i),Ks.submitSprites(t),Ks.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ks.submitSpine(t),Ks.flush(),this.executeDrawCallbacks(s,o),Ks.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:i,elapsed:o}=e;Ks.setViewport(n.x,n.y,n.w,n.h),Ks.setScissor(n.x,n.y,n.w,n.h,!0),Ks.clearBuffers(i),Ks.setScissor(0,0,0,0,!1),Ks.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Ks.submitSprites(t),Ks.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ks.submitSpine(t),Ks.flush(),this.executeDrawCallbacks(s,o),Ks.end()}executeDrawCallbacks(e,t){const s=Ts;if(s.size>0){bs.begin(e);const n=[];for(const[e,i]of s.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}bs.end();for(const e of n)Cs(e)}}}const sn="__scene_transition_overlay__";class nn{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class on{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,_e,{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),Es(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Xs.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Xs.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,_e)){const s=this.app_.world.get(e,_e);s.persistent=t,this.app_.world.insert(e,_e,s)}}}class rn{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??$.sceneTransitionDuration,i=t.color??{...$.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:i,targetScene:e,options:t,resolve:s},Es(sn,()=>{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;bs.setLayer(9999),bs.setDepth(9999),bs.rect({x:0,y:0},{x:2e4,y:2e4},{r:i.r,g:i.g,b:i.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()=>{try{s&&s!==e&&await this.unload(s,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,Cs(sn),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Cs(sn),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new nn(t);this.scenes_.set(e,s);const n=new on(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(ts)?this.app_.getResource(ts):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(s,e,t,i),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new nn(t);this.scenes_.set(e,s);const n=new on(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(ts)?this.app_.getResource(ts):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(s,e,t,i),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const i=t?.keepPersistent??!0;for(const e of s.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,_e)){if(this.app_.world.get(e,_e).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())Cs(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Xs.removePass(e)}catch{}s.postProcessPasses.length=0,this.releaseSceneAssets_(s),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)}async loadSceneData_(e,t,s,n){if(n){const s={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:s};this.app_.hasResource(ts)&&(i.assetServer=this.app_.getResource(ts));const o=await Kt(this.app_.world,n,i);e.loadedAssets=s;for(const s of o.values())e.entities.add(s),this.app_.world.insert(s,_e,{scene:t,persistent:!1})}if(s.systems)for(const{schedule:e,system:n}of s.systems){const s=ln(this.app_,t,n);this.app_.addSystemToSchedule(e,s)}const i=this.contexts_.get(t);s.setup&&await s.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const s=this.app_.hasResource(ts)?this.app_.getResource(ts):null;if(s){for(const e of t.textureUrls)s.releaseTexture(e);for(const e of t.fontPaths)s.releaseFont(e);for(const e of t.spineKeys)s.releaseSpine(e)}for(const e of t.materialHandles)St.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n={};let i=!1;if(s.has(e,ce)){const t=s.get(e,ce);n.sprite=t.color.a,t.color.a=0,s.insert(e,ce,t),i=!0}if(s.has(e,ge)){const t=s.get(e,ge);n.spine=t.color.a,t.color.a=0,s.insert(e,ge,t),i=!0}if(s.has(e,me)){const t=s.get(e,me);n.bitmapText=t.color.a,t.color.a=0,s.insert(e,me,t),i=!0}i&&t.savedAlphas.set(e,n)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n=t.savedAlphas.get(e);if(n){if(void 0!==n.sprite&&s.has(e,ce)){const t=s.get(e,ce);t.color.a=n.sprite,s.insert(e,ce,t)}if(void 0!==n.spine&&s.has(e,ge)){const t=s.get(e,ge);t.color.a=n.spine,s.insert(e,ge,t)}if(void 0!==n.bitmapText&&s.has(e,me)){const t=s.get(e,me);t.color.a=n.bitmapText,s.insert(e,me,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{Xs.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 an=Me(null,"SceneManager");function ln(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(an).getSceneStatus(t)&&s._fn(...n)}}}const cn=rt([Ee(an),Te(Re)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),un={name:"SceneManager",build(e){const t=new rn(e);e.insertResource(an,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(an),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(exports.Schedule.Startup,s),e.addSystemToSchedule(exports.Schedule.Last,cn)}};class dn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new et,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=c(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(exports.Schedule.Last);else{this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new Xe,this.resources_=new Ae;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new dn}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}removeSystem(e){let t=!1;for(const[s,n]of this.systems_){const i=n.filter(t=>t.system._id!==e);i.length!==n.length&&(this.systems_.set(s,i),this.sortedSystemsCache_.delete(s),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return De(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}enableStats(){return this.statsEnabled_=!0,this.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}getEntityCount(){return this.world_.entityCount()}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(an).register(e),this}setInitialScene(e){return this.getResource(an).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new lt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(Re)||this.resources_.insert(Re,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(exports.Schedule.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(exports.Schedule.Last);else{this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new lt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(Re,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(exports.Schedule.Startup),this.lastTime_=c(),this.mainLoop())}quit(){this.running_=!1,As();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[Zs,qs,Os,Us,vt,xs];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let 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 i=t.get(n);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,i=new Set,o=r=>{if(n.has(r))return;if(i.has(r)){const t=e[r].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(r);const a=e[r];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}i.delete(r),n.add(r),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));const n=this.phaseTimings_?performance.now():0;for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}this.phaseTimings_&&this.phaseTimings_.set(exports.Schedule[e],performance.now()-n)}updateTime(e){const t=this.resources_.get(Re);t.delta=e,t.elapsed+=e,t.frameCount++}}function hn(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const pn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function fn(e,t,s,n,i){const o=e*t/s,r=e;switch(n){case oe.FixedWidth:return o;case oe.FixedHeight:return r;case oe.Expand:return Math.max(o,r);case oe.Shrink:return Math.min(o,r);case oe.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const mn=[];function gn(e){if(e<mn.length)return mn[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return mn.push(t),t}function yn(e,t,s,n,i,o){if(0===s||0===n)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,_e);return!t||""===t.scene||o.has(t.scene)}):r;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 i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*s/(i.viewportH*n);let a,u=0,d=0;if(i.projectionType===ne.Orthographic){if(d=i.orthoSize,l){d=fn(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=d*r,a=xn(-u,u,-d,d,-i.farPlane,i.farPlane)}else a=vn(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const h=Sn(o.position.x,o.position.y,o.position.z),p=gn(c.length);p.entity=e,p.viewProjection.set(Mn(a,h)),p.viewportRect.x=i.viewportX,p.viewportRect.y=i.viewportY,p.viewportRect.w=i.viewportW,p.viewportRect.h=i.viewportH,p.clearFlags=i.clearFlags,p.priority=i.priority,p.halfW=u,p.halfH=d,p.cameraX=o.position.x,p.cameraY=o.position.y,c.push(p)}return c.sort((e,t)=>e.priority-t.priority),c}const _n=new Float32Array(16);function xn(e,t,s,n,i,o){const r=_n;r.fill(0);const a=t-e,l=n-s,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(n+s)/l,r[14]=-(o+i)/c,r[15]=1,r}const wn=new Float32Array(16);function vn(e,t,s,n){const i=wn;i.fill(0);const o=1/Math.tan(e/2),r=s-n;return i[0]=o/t,i[5]=o,i[10]=(n+s)/r,i[11]=-1,i[14]=2*n*s/r,i}const bn=new Float32Array(16);function Sn(e,t,s){const n=bn;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=-e,n[13]=-t,n[14]=-s,n[15]=1,n}const Pn=new Float32Array(16);function Mn(e,t){const s=Pn;for(let n=0;n<4;n++)for(let i=0;i<4;i++)s[4*i+n]=e[0+n]*t[4*i+0]+e[4+n]*t[4*i+1]+e[8+n]*t[4*i+2]+e[12+n]*t[4*i+3];return s}const Tn={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function En(e,t,s,n,i,o,r={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,u=o.left+t.x*a,d=o.bottom+e.y*l,h=o.bottom+t.y*l;let p,f,m,g;e.x===t.x?(p=c+s.x-i.x*r.x,m=p+i.x):(p=c+s.x,m=u+n.x),e.y===t.y?(f=d+s.y-i.y*r.y,g=f+i.y):(f=d+s.y,g=h+n.y);const y=Math.max(0,m-p),_=Math.max(0,g-f);return{originX:p+r.x*y,originY:f+r.y*_,width:y,height:_,rect:{left:p,bottom:f,right:m,top:g}}}const Cn=se("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});let An=null,Rn=null;function In(e,t){e.has(t,ce)||e.insert(t,ce,{texture:X,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0})}function Fn(e,t){switch(e){case Tn.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Tn.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Tn.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function kn(e,t,s,n){if(!e.has(t,Cn))return;const i=e.get(t,Cn),o=Fn(s,n);i.anchorMin=o.anchorMin,i.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(i.size={...i.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,Cn,i)}function Bn(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Dn(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Un(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),i=[];for(const t of n){if(!t){i.push("");continue}let n="";for(let o=0;o<t.length;o++){const r=t[o],a=n+r;if(e.measureText(a).width>s&&n){if(Dn(r.charCodeAt(0))&&n.length>0&&Dn(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!Dn(n.charCodeAt(t))){e=t;break}e>=0?(i.push(n.substring(0,e+1)),n=n.substring(e+1)+r):(i.push(n),n=r)}else i.push(n),n=r}else n=a}n&&i.push(n)}return i.length>0?i:[""]}function Ln(e){let t=1;for(;t<e;)t*=2;return t}function Wn(e,t){let s=0,n=t;for(;e.has(n,pe);){const t=e.get(n,pe).entity;if(!e.valid(t))break;s++,n=t}return s}function zn(e,t){if(An&&Rn){const e=An.getUIRectComputedWidth(Rn,t);if(e>0)return e}return e.size.x}function $n(e,t){if(An&&Rn){const e=An.getUIRectComputedHeight(Rn,t);if(e>0)return e}return e.size.y}function On(e,t,s){let n=t;for(;e.has(n,pe);){const t=e.get(n,pe).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function Hn(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function Xn(e,t,s,n,i){if(!e.has(t,Cn))return;const o=e.get(t,Cn),r=En(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s,o.pivot),a=r.rect.right-r.rect.left,l=r.rect.top-r.rect.bottom;if(e.has(t,ce)){const s=e.get(t,ce);s.size.x===a&&s.size.y===l||(s.size.x=a,s.size.y=l,e.insert(t,ce,s))}if(e.has(t,re)){const s=e.get(t,re);s.position.x=r.originX-n,s.position.y=r.originY-i,e.insert(t,re,s)}}function jn(e){const t=Object.keys(e),s=t.map(t=>e[t]);return{take(e){const n={};for(let i=0;i<t.length;i++)n[t[i]]=s[i](e);return n},changed(e,n){for(let i=0;i<t.length;i++)if(e[t[i]]!==s[i](n))return!0;return!1},update(e,n){for(let i=0;i<t.length;i++)e[t[i]]=s[i](n)}}}const Vn=.1,Nn=30,Yn={r:.3,g:.5,b:.8,a:1},Gn={Left:0,Center:1,Right:2},qn={Top:0,Middle:1,Bottom:2},Kn={Visible:0,Clip:1,Ellipsis:2},Jn=q("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Gn.Left,verticalAlign:qn.Top,wordWrap:!0,overflow:Kn.Visible,lineHeight:1.2});class Qn{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=l($.textCanvasSize,$.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,Ln(this.frameMaxW_)),e.height=Math.max(e.height,Ln(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Ln(this.frameMaxW_),e.height=Ln(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,o=i?t.size.x:0,r=i?t.size.y:0,a=e.wordWrap&&i;let l=Un(s,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=i?Math.ceil(o):d+2*u,f=i?Math.ceil(r):h+2*u;if(i&&e.overflow===Kn.Ellipsis&&h>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}this.frameMaxW_=Math.max(this.frameMaxW_,p),this.frameMaxH_=Math.max(this.frameMaxH_,f),(n.width<p||n.height<f)&&(n.width=Math.max(n.width,Ln(p)),n.height=Math.max(n.height,Ln(f)));const m=Math.round(255*e.color.r),g=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(${m}, ${g}, ${y}, ${_})`,i&&e.overflow===Kn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const x=l.length*c;let w;if(i){switch(e.verticalAlign){case qn.Top:w=u;break;case qn.Middle:w=u+(f-2*u-x)/2;break;case qn.Bottom:w=f-x-u;break;default:w=u}w<0&&(w=0)}else w=u;let v=w;for(const t of l){let n;switch(e.align){case Gn.Left:n=u;break;case Gn.Center:n=p/2;break;case Gn.Right:n=p-u;break;default:n=u}s.fillText(t,n,v),v+=c}i&&e.overflow===Kn.Clip&&s.restore();const b=s.getImageData(0,0,p,f),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(p,f,M,S.length,1,!0);return this.module._free(M),{textureHandle:T,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const i=this.renderText(t,s);return this.cache.set(e,i),i}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}measureWidth(e){let t=0;for(const s of e)t=Math.max(t,this.ctx.measureText(s).width);return t}mapAlign(e){switch(e){case Gn.Left:return"left";case Gn.Center:return"center";case Gn.Right:return"right"}}}const Zn=jn({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?zn(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?$n(e.uiRect,e.entity):0});class ei{build(e){ee("Text",Jn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Qn(t),n=e.world,i=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Jn));for(const e of i.keys())if(!n.valid(e)||!n.has(e,Jn)){if(n.valid(e)&&n.has(e,ce)){const t=n.get(e,ce);n.insert(e,ce,{texture:X,color:{r:t.color.r,g:t.color.g,b:t.color.b,a:t.color.a},size:{x:t.size.x,y:t.size.y},uvOffset:{x:t.uvOffset.x,y:t.uvOffset.y},uvScale:{x:t.uvScale.x,y:t.uvScale.y},layer:t.layer,flipX:t.flipX,flipY:t.flipY,material:t.material,enabled:t.enabled})}i.delete(e)}const e=n.getEntitiesWithComponents([Jn]);for(const t of e){const e=n.get(t,Jn),o=n.has(t,Cn)?n.get(t,Cn):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!Zn.changed(a,r)){if(n.has(t,ce)&&n.get(t,ce).texture!==X)continue}In(n,t);const l=o?{size:{x:zn(o,t),y:$n(o,t)}}:null,c=s.renderForEntity(t,e,l),u=n.get(t,ce);n.insert(t,ce,{texture:c.textureHandle,color:{r:u.color.r,g:u.color.g,b:u.color.b,a:u.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:u.layer,flipX:u.flipX,flipY:u.flipY,material:u.material,enabled:u.enabled}),i.set(t,Zn.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const ti=new ei,si=0,ni=1,ii=se("UIMask",{enabled:!0,mode:si});function oi(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),i=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,i-s),h:Math.max(0,o-n)}}function ri(e,t){const s=t??new Float32Array(16),n=e[0],i=e[1],o=e[2],r=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],m=e[12],g=e[13],y=e[14],_=e[15],x=n*l-i*a,w=n*c-o*a,v=n*u-r*a,b=i*c-o*l,S=i*u-r*l,P=o*u-r*c,M=d*g-h*m,T=d*y-p*m,E=d*_-f*m,C=h*y-p*g,A=h*_-f*g,R=p*_-f*y;let I=x*R-w*A+v*C+b*E-S*T+P*M;return 0===I||(I=1/I,s[0]=(l*R-c*A+u*C)*I,s[1]=(o*A-i*R-r*C)*I,s[2]=(g*P-y*S+_*b)*I,s[3]=(p*S-h*P-f*b)*I,s[4]=(c*E-a*R-u*T)*I,s[5]=(n*R-o*E+r*T)*I,s[6]=(y*v-m*P-_*w)*I,s[7]=(d*P-p*v+f*w)*I,s[8]=(a*A-l*E+u*M)*I,s[9]=(i*E-n*A-r*M)*I,s[10]=(m*S-g*v+_*x)*I,s[11]=(h*v-d*S-f*x)*I,s[12]=(l*T-a*C-c*M)*I,s[13]=(n*C-i*T+o*M)*I,s[14]=(g*w-m*b-y*x)*I,s[15]=(d*b-h*w+p*x)*I),s}function ai(e,t,s,n,i,o,r){const a=(e-n)/o*2-1,l=(t-i)/r*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 li(e,t){return 2*Math.atan2(e,t)}function ci(e,t,s,n,i,o,r){const a=s[0]*e+s[4]*t+s[12],l=s[1]*e+s[5]*t+s[13],c=s[3]*e+s[7]*t+s[15];return[n+(.5*(a/c)+.5)*o,i+(.5*(l/c)+.5)*r]}function ui(e,t,s,n,i,o,r){if(!e.has(t,Cn)||!e.has(t,re))return null;const a=e.get(t,Cn),l=e.get(t,re),c=zn(a,t)*l.worldScale.x,u=$n(a,t)*l.worldScale.y,d=l.worldPosition.x,h=l.worldPosition.y,p=a.pivot.x,f=a.pivot.y,m=-c*p,g=c*(1-p),y=-u*f,_=u*(1-f),x=li(l.worldRotation.z,l.worldRotation.w),w=Math.cos(x),v=Math.sin(x),b=[[d+m*w-y*v,h+m*v+y*w],[d+g*w-y*v,h+g*v+y*w],[d+g*w-_*v,h+g*v+_*w],[d+m*w-_*v,h+m*v+_*w]];let S=1/0,P=1/0,M=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=ci(e,t,s,n,i,o,r);S=Math.min(S,a),P=Math.min(P,l),M=Math.max(M,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(P),w:Math.round(M-S),h:Math.round(T-P)}}function di(e,t){return(s,n,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([ii]);if(0===l.length)return;const c=[],u=[],d=new Set,h=new Set;for(const e of l){const s=t.get(e,ii);s.enabled&&(d.add(e),s.mode===ni?(u.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,i,o,r,a,l,c){const u=[];for(const e of n){let s=!0;On(t,e,e=>{if(i.has(e)){if(t.get(e,ii).mode===si)return s=!1,!0}return!1}),s&&u.push(e)}function d(n,u){const h=e.getChildEntities(s,n);for(const s of h){let n=u;if(i.has(s)){if(t.get(s,ii).mode===si){const e=ui(t,s,o,r,a,l,c);e&&(n=oi(u,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=ui(t,e,o,r,a,l,c);s&&d(e,s)}}(e,t,s,c,d,n,i,o,r,a),u.length>0&&function(e,t,s,n,i){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0;On(t,e,e=>!!i.has(e)&&(s=!1,!0)),s&&o.push(e)}let r=1,a=!1;function l(){return r>255?(a||console.warn("Stencil mask overflow"),a=!0,null):r++}function c(t,n){if(a)return;e.renderer_setEntityStencilMask(t,n);const o=e.getChildEntities(s,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),u(t,n)}function u(t,n){if(a)return;const o=e.getChildEntities(s,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),u(t,n)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,s,u,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class hi{build(e){if(ee("UIMask",ii),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(di(e.wasmModule,e.world))}}const pi=new hi,fi=se("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),mi=se("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),gi={Normal:0,Hovered:1,Pressed:2,Disabled:3},yi=q("Button",{state:gi.Normal,transition:null});class _i{constructor(){this.events_=[]}emit(e,t,s){const n=s??e;this.events_.push({entity:e,type:t,target:n,currentTarget:e})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const xi=Me(new _i,"UIEvents");class wi{build(e){ee("UIRect",Cn);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){An=e,Rn=t}(s,n);e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([Te(pt)],e=>{e.valid&&(s.uiLayout_update(n,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),s.uiFlexLayout_update(n),s.transform_update(n))},{name:"UILayoutSystem"})),e.addSystemToSchedule(exports.Schedule.PostUpdate,rt([Te(pt)],e=>{e.valid&&(s.uiLayout_update(n,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),s.uiFlexLayout_update(n))},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(exports.Schedule.PostUpdate,rt([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const vi=new wi;let bi=!1,Si=!1;function Pi(){return bi}function Mi(){return Si}const Ti=function(){const e=new Float32Array(16),t=new Float32Array(16);let s=!0;return{update(e){for(let n=0;n<16;n++)if(t[n]!==e[n]){t.set(e),s=!0;break}},getInverse:t=>(s&&(ri(t,e),s=!1),e)}}();function Ei(e,t,s,n){t.emit(s,n,s),On(e,s,i=>{if(!e.has(i,fi))return!1;const o=e.get(i,fi);return o.enabled&&t.emit(i,n,s),o.blockRaycast})}class Ci{build(e){ee("Interactable",fi),ee("Button",yi);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),i=new _i;e.insertResource(xi,i);let o=null,r=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([Te(ut),Te(pt)],(e,a)=>{if(i.drain(),Pi()&&!Mi())return;const l=t.getEntitiesWithComponents([mi]);for(const e of l){const s=t.get(e,mi);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,mi,s))}if(!a.valid)return;const c=u(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;Ti.update(a.viewProjection);const p=ai(d,h,Ti.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=p.x,a.worldMouseY=p.y;const f=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),g=e.isMouseButtonReleased(0);s.uiHitTest_update(n,p.x,p.y,f,m,g);const y=s.uiHitTest_getHitEntity(),_=4294967295===y?null:y;if(null===o||t.valid(o)||(o=null),o!==_){if(null!==o&&t.valid(o)&&t.has(o,mi)){const e=t.get(o,mi);e.hovered=!1,t.insert(o,mi,e),i.emit(o,"hover_exit")}if(null!==_){Hn(t,_,mi);const e=t.get(_,mi);e.hovered=!0,t.insert(_,mi,e),i.emit(_,"hover_enter")}o=_}if(m&&null!==_){const e=t.get(_,mi);e.pressed=!0,e.justPressed=!0,t.insert(_,mi,e),r=_,Ei(t,i,_,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,mi)){const e=t.get(r,mi);e.pressed=!1,e.justReleased=!0,t.insert(r,mi,e),Ei(t,i,r,"release"),r===o&&Ei(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(exports.Schedule.Update,rt([],()=>{const e=t.getEntitiesWithComponents([yi]);for(const s of e){if(Hn(t,s,fi,{enabled:!0}),!t.has(s,mi))continue;const e=t.get(s,mi),n=t.get(s,yi),i=t.get(s,fi),o=!a.has(s),r=n.state;if(i.enabled?e.pressed?n.state=gi.Pressed:e.hovered?n.state=gi.Hovered:n.state=gi.Normal:n.state=gi.Disabled,o&&a.add(s),(o||r!==n.state)&&n.transition&&t.has(s,ce)){const o=t.get(s,ce);o.color=Bn(n.transition,i.enabled,e.pressed,e.hovered),t.insert(s,ce,o)}}},{name:"ButtonSystem"}))}}const Ai=new Ci,Ri=q("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}),Ii=q("Focusable",{tabIndex:0,isFocused:!1});class Fi{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const ki=Me(new Fi,"FocusManager");class Bi{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(ee("TextInput",Ri),Pi()&&!Mi())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,i=l($.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=0,a=0,c=!1,u=!0,d=0,h=0;const p=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(!p)return;const f=p;function m(){const t=e.getResource(ki);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,Ri)?n:null}const g=()=>{c||null===m()||v()},y=()=>{c=!0},_=()=>{c=!1,v()},x=t=>{const n=m();if(null===n)return;if("Escape"===t.key)return void b();const i=s.get(n,Ri);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(xi).emit(n,"submit"),void b()}let o=i.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?o=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=i.value.length),o!==i.cursorPos&&(i.cursorPos=o,f.selectionStart=o,f.selectionEnd=o,i.dirty=!0,S())},w=()=>{const t=m();if(null!==t){const n=s.get(t,Ri);n.focused=!1,n.dirty=!0;e.getResource(ki).blur()}};function v(){const t=m();if(null===t)return;const n=s.get(t,Ri);if(n.readOnly)return;let i=f.value;if(n.maxLength>0&&i.length>n.maxLength&&(i=i.substring(0,n.maxLength),f.value=i),i!==n.value){n.value=i;e.getResource(xi).emit(t,"change")}n.cursorPos=f.selectionStart??i.length,n.dirty=!0,S()}function b(){const t=m();if(null!==t){const e=s.get(t,Ri);e.focused=!1,e.dirty=!0}e.getResource(ki).blur(),f.blur()}function S(){u=!0,d=0}f.addEventListener("input",g),f.addEventListener("compositionstart",y),f.addEventListener("compositionend",_),f.addEventListener("keydown",x),f.addEventListener("blur",w),this.cleanupListeners_=()=>{f.removeEventListener("input",g),f.removeEventListener("compositionstart",y),f.removeEventListener("compositionend",_),f.removeEventListener("keydown",x),f.removeEventListener("blur",w),f.remove();const e=t.getResourceManager();for(const t of n.values())e.releaseTexture(t);n.clear(),0!==r&&(t._free(r),r=0,a=0)};let P=null;function M(e,l,c,d){(i.width<c||i.height<d)&&(i.width=Ln(Math.max(i.width,c)),i.height=Ln(Math.max(i.height,d))),o.clearRect(0,0,i.width,i.height);const h=l.backgroundColor;o.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,o.fillRect(0,0,c,d),o.save(),o.beginPath(),o.rect(l.padding,0,c-2*l.padding,d),o.clip(),o.font=`${l.fontSize}px ${l.fontFamily}`,o.textBaseline="top",o.textAlign="left";const p=0===l.value.length,f=p?l.placeholder:l.password?"●".repeat(l.value.length):l.value,m=p?l.placeholderColor:l.color;o.fillStyle=`rgba(${Math.round(255*m.r)}, ${Math.round(255*m.g)}, ${Math.round(255*m.b)}, ${m.a})`;const g=Math.ceil(1.2*l.fontSize),y=l.padding;if(l.multiline){const e=Un(o,f,c-2*y);let t=y;for(const s of e)o.fillText(s,y,t),t+=g}else{const e=(d-l.fontSize)/2;o.fillText(f,y,e)}if(l.focused&&u){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,s,n;if(l.multiline){const e=Un(o,l.value,c-2*y);let i=0,r=0,a=0;for(let t=0;t<e.length;t++){const s=e[t].length;if(i+s>=l.cursorPos){r=t,a=l.cursorPos-i;break}i+=s,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,r=t+1,a=0}const u=r<e.length?e[r].substring(0,a):"";t=y+o.measureText(u).width,s=y+r*g,n=g}else t=y+o.measureText(e).width,s=(d-l.fontSize)/2,n=l.fontSize;o.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,o.fillRect(t,s,2,n)}o.restore();const _=o.getImageData(0,0,c,d),x=new Uint8Array(_.data.buffer),w=t.getResourceManager();x.length>a&&(0!==r&&t._free(r),r=t._malloc(x.length),a=x.length),t.HEAPU8.set(x,r);const v=n.get(e);void 0!==v&&w.releaseTexture(v);const b=w.createTexture(c,d,r,x.length,1,!0);n.set(e,b);const S=s.get(e,ce);S.texture=b,S.size.x=c,S.size.y=d,S.uvOffset.x=0,S.uvOffset.y=0,S.uvScale.x=1,S.uvScale.y=1,S.color={r:1,g:1,b:1,a:1},s.insert(e,ce,S)}e.addSystemToSchedule(exports.Schedule.Update,rt([Te(ki)],e=>{const t=s.getEntitiesWithComponents([Ri]);for(const e of t)Hn(s,e,Ii,{tabIndex:0,isFocused:!1}),Hn(s,e,fi,{enabled:!0,blockRaycast:!0});const n=m();if(n!==P){if(null!==P&&s.valid(P)&&s.has(P,Ri)){const e=s.get(P,Ri);e.focused=!1,e.dirty=!0,f.blur()}null!==n&&function(e){const t=s.get(e,Ri);t.readOnly||(t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),S())}(n),P=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===h?0:(e-h)/1e3;h=e,i=Math.min(i,.1);const o=m();if(null!==o&&(d+=i,d>=.5)){d-=.5,u=!u;s.get(o,Ri).dirty=!0}const r=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Ri)||(r.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Ri,Cn]);for(const e of a){const t=s.get(e,Ri);if(!t.dirty)continue;const n=s.get(e,Cn),i=Math.ceil(n.size.x),o=Math.ceil(n.size.y);i<=0||o<=0||(In(s,e),M(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Di=new Bi,Ui={Simple:0,Sliced:1,Tiled:2,Filled:3},Li={Horizontal:0,Vertical:1},Wi={Left:0,Right:1,Bottom:2,Top:3},zi=q("Image",{texture:X,color:{r:1,g:1,b:1,a:1},imageType:Ui.Simple,fillMethod:Li.Horizontal,fillOrigin:Wi.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),$i=jn({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,layer:e=>e.image.layer,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?zn(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?$n(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class Oi{build(e){ee("Image",zi);const t=e.world,s=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,zi)||s.delete(e);const e=t.getEntitiesWithComponents([zi]);for(const n of e){const e=t.get(n,zi),i=t.has(n,Cn)?t.get(n,Cn):null,o={image:e,uiRect:i,entity:n},r=s.get(n);if(r&&!$i.changed(r,o))continue;In(t,n);const a=t.get(n,ce);if(e.enabled){if(a.texture=e.texture,a.color.r=e.color.r,a.color.g=e.color.g,a.color.b=e.color.b,a.color.a=e.color.a,a.layer=e.layer,a.material=e.material,i&&(a.size.x=zn(i,n),a.size.y=$n(i,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Ui.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===Li.Horizontal?e.fillOrigin===Wi.Left?(a.uvScale.x=t,a.size.x=s*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=s*t):e.fillOrigin===Wi.Bottom?(a.uvScale.y=t,a.size.y=n*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=n*t)}else e.imageType===Ui.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale.x=a.size.x/e.tileSize.x,a.uvScale.y=a.size.y/e.tileSize.y);t.insert(n,ce,a),s.set(n,$i.take(o))}else a.color.a=0,t.insert(n,ce,a),s.set(n,$i.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const Hi=new Oi,Xi=q("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),ji=q("ToggleGroup",{allowSwitchOff:!1});class Vi{build(e){ee("Toggle",Xi),ee("ToggleGroup",ji);const t=e.world,s=new Set;e.addSystemToSchedule(exports.Schedule.Update,rt([Te(xi)],e=>{const n=t.getEntitiesWithComponents([Xi]);if(!Pi()||Mi()){const i=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,Xi);n.isOn&&0!==n.group&&t.valid(n.group)&&(i.has(n.group)?(n.isOn=!1,t.insert(e,Xi,n)):i.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,Xi);if(0!==s.group&&t.valid(s.group)){let t=o.get(s.group);t||(t=[],o.set(s.group,t)),t.push(e)}}for(const s of n){if(Hn(t,s,fi,{enabled:!0}),!t.has(s,mi))continue;const n=t.get(s,mi),i=t.get(s,Xi),r=t.get(s,fi);if(n.justPressed&&r.enabled){const n=i.group,r=0!==n&&t.valid(n)&&t.has(n,ji);if(i.isOn&&r){if(!t.get(n,ji).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(s,Xi,i),i.isOn&&r){const i=o.get(n);if(i)for(const n of i){if(n===s)continue;const i=t.get(n,Xi);i.isOn&&(i.isOn=!1,t.insert(n,Xi,i),e.emit(n,"change"))}}e.emit(s,"change")}if(i.transition&&t.has(s,ce)){const e=t.get(s,ce);e.color=Bn(i.transition,r.enabled,n.pressed,n.hovered),t.insert(s,ce,e)}}}for(const e of n){const s=t.get(e,Xi);if(s.graphicEntity&&t.valid(s.graphicEntity)&&t.has(s.graphicEntity,ce)){const e=t.get(s.graphicEntity,ce);e.enabled=s.isOn,t.insert(s.graphicEntity,ce,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const Ni=new Vi,Yi=Tn,Gi=q("ProgressBar",{value:0,fillEntity:0,direction:Tn.LeftToRight});function qi(e,t,s,n){if(!e.has(t,Cn))return;const i=e.get(t,Cn),o=s/2,r=n/2,a={left:-o,bottom:-r,right:o,top:r},l=En(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,ce)){const s=e.get(t,ce);s.size.x===l.width&&s.size.y===l.height||(s.size.x=l.width,s.size.y=l.height,e.insert(t,ce,s))}if(e.has(t,re)){const s=e.get(t,re),n=s.position;n.x===l.originX&&n.y===l.originY||(s.position={x:l.originX,y:l.originY,z:n.z},e.insert(t,re,s))}}class Ki{build(e){ee("ProgressBar",Gi);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([],()=>{const e=t.getEntitiesWithComponents([Gi,Cn]);for(const s of e){const e=t.get(s,Gi);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,Cn),i=Math.max(0,Math.min(1,e.value));kn(t,e.fillEntity,e.direction,i);const o=zn(n,s),r=$n(n,s);qi(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Ji=new Ki,Qi=q("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Zi=q("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});class eo{build(e){ee("Draggable",Qi),ee("DragState",Zi);const t=e.world,s=e.getResource(xi);let n=null,i={x:0,y:0},o=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([Te(ut),Te(pt)],(e,r)=>{if(Pi()&&!Mi())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Qi,mi]);let s=null,o=-1/0,r=-1;for(const n of e){if(!t.get(n,Qi).enabled)continue;if(t.get(n,mi).hovered){let e=0;t.has(n,ce)&&(e=t.get(n,ce).layer);const i=Wn(t,n);(e>o||e===o&&i>=r)&&(o=e,r=i,s=n)}}if(null!==s){n=s,i={x:a.x,y:a.y},t.has(s,Zi)||t.insert(s,Zi);const e=t.get(s,Zi),o=t.get(s,re);e.startWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.currentWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==n&&!e.isMouseButtonDown(0)){if(t.valid(n)&&t.has(n,Zi)){t.get(n,Zi).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),u=t.get(n,Qi);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=n,n=null;t.get(o,Zi).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Zi))return void(o=null);const n=t.get(o,Zi),i=t.get(o,Qi),r=a.x-n.pointerStartWorld.x,l=a.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+r,u=n.startWorldPos.y+l;const d=function(e,t,s,n){let i=e.lockX?t.startWorldPos.x:s,o=e.lockY?t.startWorldPos.y:n;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:i,y:o}}(i,n,c,u);c=d.x,u=d.y;const h=n.currentWorldPos.x,p=n.currentWorldPos.y;if(n.deltaWorld={x:c-h,y:u-p},n.currentWorldPos={x:c,y:u},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:u-n.startWorldPos.y},t.has(o,re)){const e=function(e,t,s,n){if(!e.has(t,pe))return{x:s,y:n};const i=e.get(t,pe).entity;if(!e.valid(i)||!e.has(i,re))return{x:s,y:n};const o=e.get(i,re),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=li(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(s*u-n*c)/r,y:(s*c+n*u)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,re);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,re,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}}const to=new eo,so=q("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function no(e,t,s,n){return n<=0?1:e<t?Math.max(0,1-(t-e)/n):e>s?Math.max(0,1-(e-s)/n):1}function io(e,t,s,n,i){const o=2/(n=Math.max(1e-4,n)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(s+o*l)*i,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(s-o*c)*a}}class oo{build(e){ee("ScrollView",so);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(exports.Schedule.PostUpdate,rt([Te(ut),Te(pt),Te(Re)],(e,i,o)=>{const r=Pi()&&!Mi(),a=Math.min(o.delta,.05);for(const[e]of s)t.valid(e)||s.delete(e);i.valid&&(n.x=i.worldMouseX,n.y=i.worldMouseY);const l=t.getEntitiesWithComponents([so,Cn]);for(const o of l){Hn(t,o,ii,{enabled:!0,mode:si});const l=t.get(o,so),c=t.get(o,Cn);let u=s.get(o);u||(u={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},s.set(o,u));const d=zn(c,o),h=$n(c,o);let p=l.contentWidth,f=l.contentHeight;if((0===p||0===f)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,fe)){const e=t.get(l.contentEntity,fe).entities;let s=0,n=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,re))continue;const e=t.get(r,re);let a=0,l=0,c=.5,u=.5;if(t.has(r,Cn)){const e=t.get(r,Cn);a=zn(e,r)||e.size.x,l=$n(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,ce)){const e=t.get(r,ce);a=e.size.x,l=e.size.y}const d=e.position.x-a*c,h=e.position.x+a*(1-c),p=e.position.y-l*u,f=e.position.y+l*(1-u);d<s&&(s=d),h>n&&(n=h),p<i&&(i=p),f>o&&(o=f)}0===p&&(p=n-s),0===f&&(f=o-i)}const m=Math.max(0,p-d),g=Math.max(0,f-h);if(!r&&i.valid){Hn(t,o,fi,{enabled:!0,blockRaycast:!0});const s=t.has(o,mi)?t.get(o,mi):null;if(s?.justPressed&&(u.isDragging=!0,u.lastWorldX=n.x,u.lastWorldY=n.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=n.x-u.lastWorldX,t=n.y-u.lastWorldY,s=Math.min(1,10*a);if(l.horizontalEnabled){const t=no(l.scrollX,0,m,d);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const n=a>0?-e*t/a:0;u.velocityX+=(n-u.velocityX)*s}}if(l.verticalEnabled){const e=no(l.scrollY,0,g,h);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const n=a>0?t*e/a:0;u.velocityY+=(n-u.velocityY)*s}}u.lastWorldX=n.x,u.lastWorldY=n.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*d,t=5*h;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(s?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=no(l.scrollY,0,g,h);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=no(l.scrollX,0,m,d);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>g;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=io(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<Vn&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Vn?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:g,t=io(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<Vn&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Vn?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,m)),l.scrollY=Math.max(0,Math.min(l.scrollY,g)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*d,t=.5*h;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,g+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,re)){const e=t.get(l.contentEntity,re),s=e.position.x,n=e.position.y;(isNaN(u.lastAppliedX)||Math.abs(s-u.lastAppliedX)>.01)&&(u.contentBaseX=s),(isNaN(u.lastAppliedY)||Math.abs(n-u.lastAppliedY)>.01)&&(u.contentBaseY=n),e.position.x=u.contentBaseX-l.scrollX,e.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=e.position.x,u.lastAppliedY=e.position.y,t.insert(l.contentEntity,re,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const ro=new oo,ao=Tn,lo=q("Slider",{value:0,minValue:0,maxValue:1,direction:Tn.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function co(e,t,s,n,i,o){const r=zn(n,i)*s.worldScale.x,a=$n(n,i)*s.worldScale.y,l=li(s.worldRotation.z,s.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),d=e-s.worldPosition.x,h=t-s.worldPosition.y,p=d*u-h*c,f=d*c+h*u,m=-n.pivot.x*r,g=-n.pivot.y*a;switch(o){case Tn.LeftToRight:return r>0?(p-m)/r:0;case Tn.RightToLeft:return r>0?1-(p-m)/r:0;case Tn.BottomToTop:return a>0?(f-g)/a:0;case Tn.TopToBottom:return a>0?1-(f-g)/a:0}}function uo(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case Tn.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case Tn.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case Tn.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case Tn.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class ho{build(e){ee("Slider",lo);const t=e.world;let s=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([Te(ut),Te(pt),Te(xi)],(e,n,i)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([lo,Cn]);for(const r of o){const o=t.get(r,lo),a=t.get(r,Cn);if(!Pi()||Mi()){if(t.has(r,re)){Hn(t,r,fi,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Hn(t,o.handleEntity,fi,{enabled:!0,blockRaycast:!1});const l=t.get(r,re),c=t.has(r,mi)?t.get(r,mi):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,mi)&&(u=t.get(o.handleEntity,mi).justPressed),u&&(s=r),s===r&&e.isMouseButtonDown(0)){let e=co(n.worldMouseX,n.worldMouseY,l,a,r,o.direction);e=Math.max(0,Math.min(1,e));let s=o.minValue+e*(o.maxValue-o.minValue);o.wholeNumbers&&(s=Math.round(s));const c=o.value;o.value=Math.max(o.minValue,Math.min(o.maxValue,s)),t.insert(r,lo,o),o.value!==c&&i.emit(r,"change")}s===r&&e.isMouseButtonReleased(0)&&(s=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,u=zn(a,r),d=$n(a,r),h={left:-u/2,bottom:-d/2,right:u/2,top:d/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(kn(t,o.fillEntity,o.direction,c),Xn(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Cn)){const e=t.get(o.handleEntity,Cn);uo(e,o.direction,c),t.insert(o.handleEntity,Cn,e),Xn(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const po=new ho;class fo{build(e){ee("Focusable",Ii);const t=e.world,s=new Fi;e.insertResource(ki,s),e.addSystemToSchedule(exports.Schedule.Update,rt([Te(ut),Te(xi)],(e,n)=>{if(Pi()&&!Mi())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const i=t.getEntitiesWithComponents([Ii]);for(const e of i){if(!t.has(e,mi))continue;t.get(e,mi).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const n=function(){const e=[];for(const s of i){if(!t.valid(s))continue;if(t.has(s,fi)){if(!t.get(s,fi).enabled)continue}const n=t.get(s,Ii);e.push({entity:s,tabIndex:n.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===n.length)return;const r=null!==s.focusedEntity?n.findIndex(e=>e===s.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?n.length-1:0:a?(r-1+n.length)%n.length:(r+1)%n.length,o(n[l])}function o(e){const i=s.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Ii)){t.get(i,Ii).isFocused=!1,n.emit(i,"blur",i)}s.focus(e);t.get(e,Ii).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const mo=new fo,go=q("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function yo(){return s()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:s,screenWidth:n,screenHeight:i}=t;return{top:s.top,bottom:i-s.bottom,left:s.left,right:n-s.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}class _o{build(e){ee("SafeArea",go);const t=e.world;let n=yo(),i=!0,o=0,r=0;if(s()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=yo(),i=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=yo(),i=!0});e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([Te(pt)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===r||(o=e.screenH,r=a,i=!0),!i)return;i=!1;const l=u(),c=s()?a/e.screenH:l*a/e.screenH,d=t.getEntitiesWithComponents([go,Cn]);for(const e of d){const s=t.get(e,go),i=t.get(e,Cn),o=s.applyTop?n.top*c:0,r=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let u=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},u=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,Cn,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const xo=new _o,wo=q("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let vo=null;class bo{build(e){ee("ListView",wo);const t=e.world,s=new Map;vo=s,e.addSystemToSchedule(exports.Schedule.PostUpdate,rt([Te(ut)],e=>{const n=Pi()&&!Mi();for(const[e,n]of s)if(!t.valid(e)){for(const e of n.itemEntities.values())t.valid(e)&&t.despawn(e);s.delete(e)}const i=t.getEntitiesWithComponents([wo,Cn]);for(const o of i){Hn(t,o,fi,{enabled:!0,blockRaycast:!0}),Hn(t,o,ii,{enabled:!0,mode:si});let i=s.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},s.set(o,i));const r=t.get(o,wo),a=t.get(o,Cn),l=$n(a,o),c=zn(a,o);if(!n){const s=t.has(o,mi)?t.get(o,mi):null;if(s?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const u=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,u));const d=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),h=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,s]of i.itemEntities)(e<d||e>=h)&&(t.valid(s)&&t.despawn(s),i.itemEntities.delete(e));for(let e=d;e<h;e++){let s=i.itemEntities.get(e);if(s&&t.valid(s)||(s=t.spawn(),t.insert(s,ye,{value:`ListItem_${e}`}),t.insert(s,Cn,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(s,o),i.itemEntities.set(e,s),i.renderer&&i.renderer(e,s)),t.has(s,re)){const n=t.get(s,re);n.position.y=-(e*r.itemHeight-r.scrollY),t.insert(s,re,n)}}i.visibleStart=d,i.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const So=new bo,Po=q("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class Mo{build(e){ee("Dropdown",Po);const t=e.world,s=new Map;function n(e){if(0===e||!t.valid(e))return;if(!t.has(e,re))return;const s=t.get(e,re);0===s.scale.x&&0===s.scale.y&&0===s.scale.z&&t.insert(e,re,{position:{x:s.position.x,y:s.position.y,z:s.position.z},rotation:{x:s.rotation.x,y:s.rotation.y,z:s.rotation.z,w:s.rotation.w},scale:{x:1,y:1,z:1}})}function i(e){if(t.has(e,ce)){const s=t.get(e,ce);1===s.color.r&&1===s.color.g&&1===s.color.b&&1===s.color.a&&t.insert(e,ce,{texture:s.texture,color:{r:.9,g:.9,b:.9,a:1},size:{x:s.size.x,y:s.size.y},uvOffset:{x:s.uvOffset.x,y:s.uvOffset.y},uvScale:{x:s.uvScale.x,y:s.uvScale.y},layer:s.layer,flipX:s.flipX,flipY:s.flipY,material:s.material,enabled:s.enabled})}}function o(e,s,n){s.isOpen=!0,n.highlightIndex=s.selectedIndex;const i=s.listEntity;if(0===i||!t.valid(i))return;u(i,!0),c(n);const o=t.get(e,ce),r=o.size.x,a=o.size.y;n.ddWidth=r;const l=s.options.length*Nn;t.insert(i,Cn,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:l},pivot:{x:.5,y:.5}}),t.insert(i,re,{position:{x:0,y:-(a+l)/2,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(i,ce,{texture:X,color:{r:1,g:1,b:1,a:1},size:{x:r,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<s.options.length;e++){const o=t.spawn(),a=l/2-(e+.5)*Nn;t.insert(o,ye,{value:`Option_${e}`}),t.insert(o,Cn,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Nn},offsetMax:{x:0,y:0},size:{x:r,y:Nn},pivot:{x:.5,y:.5}}),t.insert(o,re,{position:{x:0,y:a,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(o,ce,{texture:X,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:Nn},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,fi,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),n.optionEntities.push(o);const c=t.spawn();t.insert(c,re,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(c,Jn,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Gn.Left,verticalAlign:qn.Middle,wordWrap:!1,overflow:Kn.Clip,lineHeight:1.2}),t.insert(c,Cn,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:Nn},pivot:{x:.5,y:.5}}),t.setParent(c,o),n.textEntities.push(c)}d(n)}function r(e,t,s){t.isOpen=!1,c(s),u(t.listEntity,!1)}function a(e,t,s,n,i){t.selectedIndex=n,r(0,t,s),i.emit(e,"change")}function l(e){const s=e.labelEntity;if(0===s||!t.valid(s))return;if(!t.has(s,Jn))return;const n=t.get(s,Jn);let i={r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},o=n.content,r=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},r=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,r=!0)}r&&t.insert(s,Jn,{content:o,fontSize:n.fontSize,fontFamily:n.fontFamily,color:i,align:n.align,verticalAlign:n.verticalAlign,wordWrap:n.wordWrap,overflow:n.overflow,lineHeight:n.lineHeight})}function c(e){for(const s of e.textEntities)t.valid(s)&&t.despawn(s);for(const s of e.optionEntities)t.valid(s)&&t.despawn(s);e.optionEntities=[],e.textEntities=[]}function u(e,s){if(0!==e&&t.valid(e)&&(t.has(e,fi)&&t.insert(e,fi,{enabled:s,blockRaycast:!0,raycastTarget:!0}),t.has(e,ce))){const n=t.get(e,ce);t.insert(e,ce,{texture:n.texture,color:{r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:s})}}function d(e){for(let s=0;s<e.optionEntities.length;s++){const n=e.optionEntities[s];if(!t.valid(n)||!t.has(n,ce))continue;const i=s===e.highlightIndex?{...Yn}:{r:.95,g:.95,b:.95,a:1};t.insert(n,ce,{texture:X,color:i,size:{x:e.ddWidth,y:Nn},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function h(e){for(const s of e.optionEntities){if(!t.valid(s)||!t.has(s,mi))continue;if(t.get(s,mi).hovered)return!0}return!1}e.addSystemToSchedule(exports.Schedule.Update,rt([Te(ut),Te(xi)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const p=Pi()&&!Mi(),f=t.getEntitiesWithComponents([Po]);for(const m of f){const f=t.get(m,Po);let g=s.get(m);if(g||(g={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},s.set(m,g)),n(f.listEntity),i(m),f.isOpen||u(f.listEntity,!1),l(f),p)continue;Hn(t,m,fi,{enabled:!0,blockRaycast:!0});const y=t.has(m,mi)?t.get(m,mi):null;if(y?.justPressed&&(f.isOpen?r(m,f,g):o(m,f,g)),f.isOpen){for(let e=0;e<g.optionEntities.length;e++){const s=g.optionEntities[e];if(!t.valid(s)||!t.has(s,mi))continue;if(t.get(s,mi).justPressed){a(m,f,g,e,c);break}}let s=-1;for(let e=0;e<g.optionEntities.length;e++){const n=g.optionEntities[e];if(!t.valid(n)||!t.has(n,mi))continue;if(t.get(n,mi).hovered){s=e;break}}s>=0&&s!==g.highlightIndex&&(g.highlightIndex=s,d(g)),e.isKeyPressed("ArrowDown")?(g.highlightIndex>=f.options.length-1?g.highlightIndex=0:g.highlightIndex++,d(g)):e.isKeyPressed("ArrowUp")?(g.highlightIndex<=0?g.highlightIndex=f.options.length-1:g.highlightIndex--,d(g)):e.isKeyPressed("Enter")&&g.highlightIndex>=0?a(m,f,g,g.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,f,g),e.isMouseButtonPressed(0)&&(y?.hovered||h(g)||r(m,f,g))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}}const To=new Mo,Eo=0,Co=0,Ao=2,Ro=q("LayoutGroup",{direction:Eo,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Co,reverseOrder:!1});class Io{build(e){ee("LayoutGroup",Ro);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([],()=>{const e=t.getEntitiesWithComponents([Ro,Cn,fe]);for(const s of e){const e=t.get(s,Ro),n=t.get(s,Cn),i=t.get(s,fe);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,Cn)&&t.has(e,re)&&o.push({entity:e,rect:t.get(e,Cn)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=zn(n,s),a=$n(n,s),l=n.pivot.x,c=n.pivot.y,u=e.padding,d=e.direction===Eo;let h=0;for(let s=0;s<o.length;s++){const n=o[s],i=zn(n.rect,n.entity),p=$n(n.rect,n.entity),f=n.rect.pivot.x,m=n.rect.pivot.y;let g,y;d?(g=-l*r+u.left+h+f*i,y=e.childAlignment===Co?(1-c)*a-u.top-(1-m)*p:e.childAlignment===Ao?-c*a+u.bottom+m*p:(.5-c)*a+.5*(u.bottom-u.top)+(m-.5)*p,h+=i,s<o.length-1&&(h+=e.spacing)):(g=e.childAlignment===Co?-l*r+u.left+f*i:e.childAlignment===Ao?(1-l)*r-u.right-(1-f)*i:(.5-l)*r+.5*(u.left-u.right)+(f-.5)*i,y=(1-c)*a-u.top-h-(1-m)*p,h+=p,s<o.length-1&&(h+=e.spacing));const _=t.get(n.entity,re);_.position.x=g,_.position.y=y,t.insert(n.entity,re,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}}const Fo=new Io;class ko{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(exports.Schedule.PostUpdate,rt([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const Bo=new ko;async function Do(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 Uo=Me({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Lo=Me(null,"PhysicsAPI");function Wo(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function zo(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class $o{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(Uo,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Do(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const i=function(e){const t=e.world.getEntitiesWithComponents([de]);for(const s of t){const t=e.world.get(s,de);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/i,r=e.world;r.onDespawn(e=>{t.has(e)&&(n._physics_destroyBody(e),t.delete(e),s.delete(e))}),e.addSystemToSchedule(exports.Schedule.PostUpdate,rt([Te(Re)],a=>{const l=r.getEntitiesWithComponents([xe,re]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,xe),l=r.get(i,re);if(t.has(i)){const e=s.get(i);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(i,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const r=Wo(l.worldRotation);n._physics_createBody(i,a.bodyType,l.worldPosition.x*o,l.worldPosition.y*o,r,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Oo(e,n,i),t.add(i),s.set(i,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===Se.Kinematic){const e=Wo(l.worldRotation);n._physics_setBodyTransform(i,l.worldPosition.x*o,l.worldPosition.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 i=t._physics_getDynamicBodyTransforms(),o=i>>2;for(let i=0;i<n;i++){const n=o+4*i,r=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(r))continue;const u=e.world.get(r,re);if(!u)continue;let d=a,h=l,p=c;if(e.world.has(r,pe)){const t=e.world.get(r,pe);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,re)){const s=e.world.get(t.entity,re),n=Wo(s.worldRotation),i=a-s.worldPosition.x,o=l-s.worldPosition.y,r=Math.cos(-n),u=Math.sin(-n);d=(i*r-o*u)/(0!==s.worldScale.x?s.worldScale.x:1),h=(i*u+o*r)/(0!==s.worldScale.y?s.worldScale.y:1),p=c-n}}u.position.x=d,u.position.y=h;const f=zo(p);u.rotation.w=f.w,u.rotation.x=f.x,u.rotation.y=f.y,u.rotation.z=f.z,e.world.insert(r,re,u)}}(e,n,i),function(e,t,s){t._physics_collectEvents();const n=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<i;o++){const i=e+6*o;n.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*s,contactY:t.HEAPF32[i+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 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(Uo,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,i)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Lo,Ho._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function Oo(e,t,s){const n=e.world;if(n.has(s,we)){const e=n.get(s,we);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,ve)){const e=n.get(s,ve);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,be)){const e=n.get(s,be);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 Ho{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(Ho.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}const Xo={nearest:0,linear:1},jo={repeat:0,clamp:1,mirror:2};function Vo(e,t,s=!0,n){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),n&&(n.filterMode||n.wrapMode)&&i.createTextureEx){const e=Xo[n.filterMode??"linear"]??1,a=jo[n.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,s,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,s);return e._free(o),r}function No(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 Yo(e,t,s,n){const i=e.worldScale.x*t*(s?-1:1),o=e.worldScale.y*t*(n?-1:1),r=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,u=e.worldRotation.w,d=a+a,h=l+l,p=c+c,f=a*d,m=a*h,g=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))*i,(m+b)*i,(g-v)*i,0,(m-b)*o,(1-(f+x))*o,(_+w)*o,0,(g+v)*r,(_-w)*r,(1-(f+y))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function Go(e){const{app:t,module:s,sceneData:n,provider:i,spineModule:o,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,u=await async function(e,t,s){const n={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=Xt(t.type);for(const r of o){if("texture"!==r.type)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===n[o])try{const t=i?.[o];n[o]=Vo(e,await s.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),n[o]=0}}}return n}(s,n,i);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const i=s[e];if(i&&i>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(s,n,u);let d={},h=null;if(o&&(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"])}}(o),d=await async function(e,t,s,n,i){const o={};for(const r of n.entities)for(const n of r.components){const r=jt(n.type);if(!r||!n.data)continue;const a=n.data[r.skeletonField],l=n.data[r.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),u=i.resolvePath(l);try{const n=await i.readText(l),r="binary"===v(c)?.contentType;let d,h;if(r){const e=await i.readBinary(a);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await i.readText(a),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,r);if(t._free(d),p<0)continue;o[a]=p;const f=No(n),m=u.substring(0,u.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=m+"/"+f[t];try{const o=i.loadPixelsRaw?await i.loadPixelsRaw(n):await i.loadPixels(n),r=Vo(e,o,!1),a=e.getResourceManager().getTextureGLId(r);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(s,o,h,n,i)),r){const e={gravity:a?.gravity??{...W},fixedTimestep:a?.fixedTimestep??z,subStepCount:a?.subStepCount??4};new $o("",e,()=>Promise.resolve(r)).build(t)}const p=await async function(e,t,s){const n={};for(const i of t.entities)for(const t of i.components){const i=Xt(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{let t,i;const r=v(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await s.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){n[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await s.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),u=Vo(e,c,!1),d=e.getResourceManager();n[o]=d.loadBitmapFont(t,u,c.width,c.height)}catch{n[o]=0}}return n}(s,n,i),f=await async function(e,t){const s={},n={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Xt(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){s[o]=0;continue}const i=e.vertexSource+e.fragmentSource;let r=n[i];r||(r=St.createShader(e.vertexSource,e.fragmentSource),n[i]=r),s[o]=St.createFromAsset(e,r)}catch{s[o]=0}}return s}(n,i);await async function(e,t,s){const n=new Set;for(const i of t.entities)for(const t of i.components){const i=Xt(t.type);for(const o of i){if("anim-clip"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!n.has(i)){n.add(i);try{const t=await s.readText(i),n=JSON.parse(t),o=Bt(n),r=new Map;for(const t of o)try{const n=await s.loadPixels(t);r.set(t,Vo(e,n))}catch{r.set(t,0)}Lt(Dt(i,n,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(s,n,i),await async function(e){const t=[],s=new Set;for(const n of e.entities)for(const e of n.components){const n=Xt(e.type);for(const i of n){if("audio"!==i.type)continue;const n=e.data[i.field];"string"==typeof n&&n&&!s.has(n)&&(s.add(n),t.push(n))}}t.length>0&&await $t.preloadAll(t).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)})}(n),function(e,t,s,n){const i={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=Xt(e.type);if(0===t.length)continue;const s=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof s[e.field]&&(s[e.field]=t[s[e.field]]||0)}}}(n,u,p,f);const m=qt(t.world,n);if(c&&t.hasResource(an))for(const e of m.values())t.world.insert(e,_e,{scene:c,persistent:!1});if(o&&h){const e=function(e,t,s,n){const i={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const r=jt(t.type);if(!r||!t.data)continue;const a=s[t.data[r.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=n.get(o.id);void 0!==c&&(i[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return i}(h,n,d,m);!function(e,t,s,n,i){let o=0;e.setSpineRenderer((r,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=L);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,ge)?c.get(o,ge):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(r,l*d);let h=0;if(c.has(o,re)){const e=Yo(c.get(o,re),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=n.getMeshBatchCount(r);for(let e=0;e<p;e++){const i=n.getMeshBatchVertexCount(r,e),o=n.getMeshBatchIndexCount(r,e);if(!i||!o)continue;const a=8*i*4,l=2*o,c=s._malloc(a),u=s._malloc(l),d=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(r,e,c,u,d,p);const f=s.HEAPU32[d>>2],m=s.HEAPU32[p>>2],g=new Float32Array(s.HEAPF32.buffer,c,8*i),y=new Uint16Array(s.HEAPU8.buffer,u,o),_=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(g,_>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(y),t.renderer_submitTriangles(_,i,x,o,f,m,h),t._free(_),t._free(x),s._free(c),s._free(u),s._free(d),s._free(p)}h&&t._free(h)}})}(t,s,o,h,e)}if(l){const e=t.getResource(ts);e&&e.setAddressableManifest(l)}}function qo(e,t,s){return{name:e,async setup(){await Go({...s,sceneData:t,sceneName:e})}}}async function Ko(e){const{app:t,firstScene:s,aspectRatio:n}=e;hn(t);const i={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},o=t.getResource(an);for(const t of e.scenes)o.register(qo(t.name,t.data,i));s&&(o.setInitial(s),await o.load(s)),void 0!==n&&Zt(t.world,n)}class Jo{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 i of e.entities)for(const e of i.components){if(!e.data)continue;const i=jt(e.type);if(i){const n=e.data[i.skeletonField],o=e.data[i.atlasField];n&&("binary"===v(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=Xt(e.type);for(const s of o){const i=e.data[s.field];"string"==typeof i&&i&&("font"===s.type?(n.add(i),t.add(i)):("material"===s.type||"anim-clip"===s.type)&&t.add(i))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const o=[];for(const e of n){const t=v(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(),i=await createImageBitmap(n),o=new OffscreenCanvas(i.width,i.height).getContext("2d");o.drawImage(i,0,0);const r=o.getImageData(0,0,i.width,i.height);return i.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Qo="__preview__";const Zo={create(e){const t=e.depth??!0,s="linear"===e.filter,n=(t?1:0)|(s?2:0),i=Ks.createRenderTarget(e.width,e.height,n);return{_handle:i,textureId:Ks.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:s?"linear":"nearest"}},release(e){Ks.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Ks.releaseRenderTarget(e._handle),Zo.create({width:t,height:s,depth:e._depth,filter:e._filter})),begin(e,t){Ks.begin(t,e._handle)},end(){Ks.end()},getDepthTexture:e=>Ks.getTargetDepthTexture(e._handle)};var er;exports.LogLevel=void 0,(er=exports.LogLevel||(exports.LogLevel={}))[er.Debug=0]="Debug",er[er.Info=1]="Info",er[er.Warn=2]="Warn",er[er.Error=3]="Error";class tr{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 sr{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new tr)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,s){this.log(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 i={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const nr=new sr;const ir={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},or={None:0,Restart:1,PingPong:2};class rr{constructor(e,t,s){this.module_=e,this.registry_=t,this.entity=s}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,s,n){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,s,n),this}then(e){return this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let ar=null,lr=null;function cr(e,t){ar=e,lr=t}function ur(){ar=null,lr=null}function dr(){if(!ar)throw new Error("Tween API not initialized");return ar}function hr(){if(!lr)throw new Error("Tween API not initialized");return lr}const pr={to(e,t,s,n,i,o){const r=dr(),a=hr(),l=o?.easing??ir.Linear,c=o?.delay??0,u=o?.loop??or.None,d=o?.loopCount??0,h=r._anim_createTween(a,e,t,s,n,i,l,c,u,d);return new rr(r,a,h)},cancel(e){dr()._anim_cancelTween(hr(),e.entity)},cancelAll(e){dr()._anim_cancelAllTweens(hr(),e)},update(e){dr()._anim_updateTweens(hr(),e)}};class fr{constructor(){this.name="AnimationPlugin"}build(e){cr(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(exports.Schedule.Update,rt([Te(Re)],e=>{pr.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(exports.Schedule.Update,rt([Te(Re)],e=>{zt(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){ur()}}const mr=new fr;var gr;exports.AttenuationModel=void 0,(gr=exports.AttenuationModel||(exports.AttenuationModel={}))[gr.Linear=0]="Linear",gr[gr.Inverse=1]="Inverse",gr[gr.Exponential=2]="Exponential";const yr={model:exports.AttenuationModel.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function _r(e,t=yr){const{model:s,refDistance:n,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(s){case exports.AttenuationModel.Linear:{const e=i-n;if(e<=0)return 1;a=1-(Math.min(Math.max(r,n),i)-n)/e;break}case exports.AttenuationModel.Inverse:a=n/Math.max(r,n);break;case exports.AttenuationModel.Exponential:a=Math.pow(Math.max(r,n)/n,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function xr(e,t,s,n,i){const o=e-s;return Math.max(-1,Math.min(1,o/i))}const wr=q("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:exports.AttenuationModel.Inverse,rolloff:1,priority:0,enabled:!0}),vr=q("AudioListener",{enabled:!0});class br{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const s=t().createAudioBackend(),n=this.config_;s.initialize({initialPoolSize:n.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const i=s.mixer;$t.init(s,i),i&&(void 0!==n.masterVolume&&(i.master.volume=n.masterVolume),void 0!==n.musicVolume&&(i.music.volume=n.musicVolume),void 0!==n.sfxVolume&&(i.sfx.volume=n.sfxVolume));const o=new Map;this.activeSourceHandles_=o;const r=new Set;this.playedEntities_=r;const a=new Set;let l=!1,c=!1;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([Te(Re)],t=>{if(!(!Pi()||Mi()))return void(c&&(l=!1,c=!1));c=!0;const n=e.world;let i=0,u=0,d=!1;const h=n.getEntitiesWithComponents([vr,le]);for(const e of h){if(n.get(e,vr).enabled){const t=n.get(e,le);i=t.position.x,u=t.position.y,d=!0;break}}const p=n.getEntitiesWithComponents([wr]);a.clear();for(const e of p){const t=n.get(e,wr);if(!t.enabled||!t.clip)continue;const c=e;if(a.add(c),t.playOnAwake&&!r.has(c)&&!o.has(c)&&s.isReady){const e=$t.getBufferHandle(t.clip);if(e){const n=s.play(e,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});o.set(c,n),r.add(c)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(c)){const s=o.get(c);if(!s.isPlaying){o.delete(c);continue}d||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=n.tryGet?.(e,le),a=r?.position.x??0,h=r?.position.y??0,p=a-i,f=h-u,m=_r(Math.sqrt(p*p+f*f),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=xr(a,0,i,0,t.maxDistance);s.setVolume(t.volume*m),s.setPan(g)}}for(const[e,t]of o)a.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),$t.dispose()}}const Sr=new br;function Pr(e,t){return e.toFixed(t)}function Mr(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}class Tr{constructor(e,t="bottom-left"){this.visible_=!0,this.disposed_=!1,this.el_=document.createElement("div"),this.el_.style.cssText="\nposition: fixed;\nz-index: 99999;\npointer-events: none;\nbackground: rgba(30, 30, 30, 0.85);\nborder: 1px solid rgba(60, 60, 60, 0.8);\nborder-radius: 4px;\npadding: 6px 10px;\nfont: 11px monospace;\ncolor: #cccccc;\nline-height: 1.6;\nmin-width: 200px;\nwhite-space: pre;\n"+function(e){switch(e){case"top-left":return"top: 12px; left: 12px;";case"top-right":return"top: 12px; right: 12px;";case"bottom-left":return"bottom: 12px; left: 12px;";case"bottom-right":return"bottom: 12px; right: 12px;"}}(t),e.appendChild(this.el_)}update(e){if(!this.visible_||this.disposed_)return;const t=[];if(t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div><div>FPS: <span style="color:#d19a66">${Pr(e.fps,1)}</span> Frame: <span style="color:#d19a66">${Pr(e.frameTimeMs,1)}ms</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div><div>DC: <span style="color:#d19a66">${e.drawCalls}</span> Tri: <span style="color:#d19a66">${e.triangles}</span></div><div>Sprites: <span style="color:#d19a66">${e.sprites}</span> Culled: <span style="color:#d19a66">${e.culled}</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div><div>Entities: <span style="color:#d19a66">${e.entityCount}</span></div>`),e.systemTimings.size>0){const s=[...e.systemTimings.entries()].sort((e,t)=>t[1]-e[1]).slice(0,5);let n='<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';for(const[e,t]of s){n+=`<div>${Mr(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${Pr(t,1)}ms</span></div>`}t.push(n)}this.el_.innerHTML=t.join("")}show(){this.visible_=!0,this.el_.style.display=""}hide(){this.visible_=!1,this.el_.style.display="none"}dispose(){this.disposed_=!0,this.el_.parentElement?.removeChild(this.el_)}}function Er(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const Cr=Me(Er(),"Stats");const Ar="StatsCollect";class Rr{constructor(){this.deltas_=[],this.cursor_=0,this.count_=0,this.sum_=0}pushFrame(e){!Number.isFinite(e)||e<0||(this.count_<60?(this.deltas_.push(e),this.sum_+=e,this.count_++):(this.sum_-=this.deltas_[this.cursor_],this.deltas_[this.cursor_]=e,this.sum_+=e,this.cursor_=(this.cursor_+1)%60))}getFps(){return 0===this.count_||this.sum_<=0?0:this.count_/this.sum_}getFrameTimeMs(){return 0===this.count_||this.sum_<=0?0:this.sum_/this.count_*1e3}reset(){this.deltas_.length=0,this.cursor_=0,this.count_=0,this.sum_=0}}class Ir{constructor(e){this.name="Stats",this.collector_=new Rr,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(Cr,Er());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new Tr(e,this.options_.position)}const t=this.collector_,s=this.overlay_,n=rt([Te(Re),{_type:"get_world"}],(n,i)=>{t.pushFrame(n.delta);const o=e.getResource(Cr);o.fps=t.getFps(),o.frameTimeMs=t.getFrameTimeMs(),o.entityCount=i.entityCount();const r=e.getSystemTimings();if(r){const e=new Map(r);e.delete(Ar),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=Ks.getStats();o.drawCalls=l.drawCalls,o.triangles=l.triangles,o.sprites=l.sprites,o.text=l.text,o.spine=l.spine,o.meshes=l.meshes,o.culled=l.culled,s?.update(o)},{name:Ar});e.addSystemToSchedule(exports.Schedule.Last,n)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const Fr=new Ir;class kr{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,s)=>{const n=new Image;n.onload=()=>{const e=document.createElement("canvas");e.width=n.width,e.height=n.height;const s=e.getContext("2d");s.drawImage(n,0,0);const i=s.getImageData(0,0,n.width,n.height);t({width:n.width,height:n.height,pixels:new Uint8Array(i.data.buffer)})},n.onerror=s,n.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return function(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}(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}async function Br(e,t){try{const s=function(e){const t=atob(e),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s}(t);return await e({instantiateWasm:(e,t)=>(WebAssembly.instantiate(s.buffer,e).then(e=>{t(e.instance,e.module)}),{})})}catch(e){return null}}const Dr=[ti,pi,vi,Hi,Ji,Ai,to,ro,po,Ni,Di,mo,xo,So,To,Fo,Bo],Ur=[...Dr,mr,Sr];function Lr(e,t){return function(e,t){const s=dn.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),_s(e),wt(e),Ds(e),$s(e),Gs(e),Qs(e);const i=new tn;s.setPipeline(i);let o=c();const r=t?.getViewportSize??(()=>{const e=u();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=yn(e,n,t,i));const r=s.getResource(pt);if(o.length>0){const e=o[0],s=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(s.x*t),r.vpY=Math.round((1-s.y-s.h)*i),r.vpW=Math.round(s.w*t),r.vpH=Math.round(s.h*i),r.screenW=t,r.screenH=i,r.worldLeft=e.cameraX-e.halfW,r.worldRight=e.cameraX+e.halfW,r.worldBottom=e.cameraY-e.halfH,r.worldTop=e.cameraY+e.halfH,r.valid=!0}else r.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,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=r();a(e,t)}},d={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const u=e.registry_getCanvasEntity(n);if(u>=0){const e=n.getCanvas(u).backgroundColor;Ks.setClearColor(e.x,e.y,e.z,e.w)}const d=(c()-o)/1e3;let h;if(Ks.resize(t,l),Xs.isInitialized()&&Xs.getPassCount()>0&&!Xs.isBypassed()&&Xs.resize(t,l),s.hasResource(an)){const e=s.getResource(an).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const p=yn(e,n,t,l,s.world,h);if(a(t,l,p),0===p.length)i.render({registry:{_cpp:n},viewProjection:pn,width:t,height:l,elapsed:d});else{for(const e of p){const s=e.viewportRect,o=Math.round(s.x*t),r=Math.round((1-s.y-s.h)*l),a=Math.round(s.w*t),c=Math.round(s.h*l);i.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:d})}Ks.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(exports.Schedule.First,l),s.addSystemToSchedule(exports.Schedule.Last,d),s.addPlugin(ns),s.addPlugin(hs),s.addPlugin(ht),s.addPlugin(un),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Ur,...t})}class Wr{constructor(e){this.resolvePath_=e}async loadPixels(e){return async function(e){return t().loadImagePixels(e)}(this.resolvePath_(e))}async readText(e){return o(this.resolvePath_(e))}async readBinary(e){const t=await i(this.resolvePath_(e));return new Uint8Array(t)}resolvePath(e){return this.resolvePath_(e)}}function zr(e){return(t,s)=>(a(e,t).then(e=>{s(e.instance,e.module)}),{})}async function $r(e,t){try{return await e({instantiateWasm:zr(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}k||(k=!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},i=await f(s,n);return{ok:i.ok,status:i.status,statusText:i.statusText,headers:new Headers(i.headers),json:()=>i.json(),text:()=>i.text(),arrayBuffer:()=>i.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 m(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 i=e.charCodeAt(t);i<128?s[n++]=i:i<2048?(s[n++]=192|i>>6,s[n++]=128|63&i):i>=55296&&i<=56319?(i=e.charCodeAt(++t)-56320+(i-55296<<10)+65536,s[n++]=240|i>>18,s[n++]=128|i>>12&63,s[n++]=128|i>>6&63,s[n++]=128|63&i):(s[n++]=224|i>>12,s[n++]=128|i>>6&63,s[n++]=128|63&i)}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 i=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(i>>10),56320+(1023&i)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=B,exports.Added=function(e){return{_filterType:"added",_component:e}},exports.AnimationPlugin=fr,exports.App=dn,exports.AssetPlugin=ss,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=es,exports.Assets=ts,exports.AsyncCache=Ft,exports.Audio=$t,exports.AudioBus=d,exports.AudioListener=vr,exports.AudioMixer=class{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new d(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new d(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new d(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new d(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new d(e,{name:"voice",volume:t.voiceVolume??1}),this.master.addChild(this.voice),this.buses_.set("master",this.master),this.buses_.set("music",this.music),this.buses_.set("sfx",this.sfx),this.buses_.set("ui",this.ui),this.buses_.set("voice",this.voice)}getBus(e){return this.buses_.get(e)}createBus(e){const t=new d(this.context_,e),s=e.parent?this.buses_.get(e.parent):this.master;return s&&s.addChild(t),this.buses_.set(e.name,t),t}},exports.AudioPlugin=br,exports.AudioPool=class{constructor(e,t=16){this.pool_=[],this.activeCount_=0,this.context_=e;for(let e=0;e<t;e++)this.pool_.push(this.createNode())}createNode(){const e=this.context_.createGain(),t=this.context_.createStereoPanner();return e.connect(t),{gain:e,panner:t,source:null,inUse:!1,startTime:0}}acquire(){let e=this.pool_.find(e=>!e.inUse);return e||(e=this.createNode(),this.pool_.push(e)),e.inUse=!0,e.startTime=this.context_.currentTime,e.gain.gain.value=1,e.panner.pan.value=0,this.activeCount_++,e}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}},exports.AudioSource=wr,exports.BitmapText=me,exports.BodyType=Se,exports.BoxCollider=we,exports.Button=yi,exports.ButtonState=gi,exports.Camera=ue,exports.Canvas=de,exports.CapsuleCollider=be,exports.Changed=function(e){return{_filterType:"changed",_component:e}},exports.Children=fe,exports.CircleCollider=ve,exports.ClearFlags=ie,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=Qe,exports.DEFAULT_DESIGN_HEIGHT=U,exports.DEFAULT_DESIGN_WIDTH=D,exports.DEFAULT_FALLBACK_DT=L,exports.DEFAULT_FIXED_TIMESTEP=z,exports.DEFAULT_FONT_FAMILY="Arial",exports.DEFAULT_FONT_SIZE=24,exports.DEFAULT_GRAVITY=W,exports.DEFAULT_LINE_HEIGHT=1.2,exports.DEFAULT_MAX_DELTA_TIME=.5,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_SPINE_SKIN="default",exports.DEFAULT_SPRITE_SIZE={x:100,y:100},exports.DEFAULT_TEXT_CANVAS_SIZE=512,exports.DragPlugin=eo,exports.DragState=Zi,exports.Draggable=Qi,exports.Draw=bs,exports.Dropdown=Po,exports.DropdownPlugin=Mo,exports.EasingType=ir,exports.EntityCommands=Je,exports.EventReader=function(e){return{_type:"event_reader",_event:e}},exports.EventReaderInstance=st,exports.EventRegistry=et,exports.EventWriter=function(e){return{_type:"event_writer",_event:e}},exports.EventWriterInstance=tt,exports.FillDirection=Tn,exports.FillMethod=Li,exports.FillOrigin=Wi,exports.FocusManager=ki,exports.FocusManagerState=Fi,exports.FocusPlugin=fo,exports.Focusable=Ii,exports.FrameHistory=class{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,s){const n={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:s?new Map(s):new Map};this.count_<this.capacity_?(this.buffer_.push(n),this.count_++):this.buffer_[this.cursor_]=n,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}},exports.GLDebug=en,exports.Geometry=Ws,exports.GetWorld=it,exports.INVALID_ENTITY=0,exports.INVALID_FONT=j,exports.INVALID_MATERIAL=0,exports.INVALID_TEXTURE=X,exports.Image=zi,exports.ImagePlugin=Oi,exports.ImageType=Ui,exports.Input=ut,exports.InputPlugin=dt,exports.InputState=ct,exports.Interactable=fi,exports.LayoutGroupPlugin=Io,exports.ListView=wo,exports.ListViewPlugin=bo,exports.LocalTransform=ae,exports.Logger=sr,exports.LoopMode=or,exports.Material=St,exports.MaterialLoader=kt,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ye,exports.Parent=pe,exports.Physics=Ho,exports.PhysicsEvents=Uo,exports.PhysicsPlugin=$o,exports.PostProcess=Xs,exports.PrefabServer=cs,exports.Prefabs=us,exports.PrefabsPlugin=ds,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(an);t.register({name:Qo,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Qo),this.loadPromise_=t.load(Qo).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await n(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new Jo(this.baseUrl_);await s.prefetch(t);let i=null;const o=this.app_.spineInitPromise;if(o){i=(await o).controller.raw}await Go({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:s,spineModule:i,sceneName:Qo})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([ue]);for(const n of s){if(e.get(n,ue).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([de]);for(const i of n){const n=e.get(i,de);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const i=this.app_.getResource(an).getScene(Qo),o=i?i.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,re,r);const a={isActive:!0,projectionType:ne.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:ie.ColorAndDepth};e.insert(o,ue,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(an);await e.switchTo(Qo),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}},exports.ProgressBar=Gi,exports.ProgressBarDirection=Yi,exports.ProgressBarPlugin=Ki,exports.ProjectionType=ne,exports.Query=function(...e){return Ge(e)},exports.QueryInstance=qe,exports.Removed=function(e){return{_type:"removed",_component:e}},exports.RemovedQueryInstance=Ke,exports.RenderPipeline=tn,exports.RenderTexture=Zo,exports.Renderer=Ks,exports.Res=Te,exports.ResMut=Ee,exports.RigidBody=xe,exports.RuntimeConfig=$,exports.SafeArea=go,exports.SafeAreaPlugin=_o,exports.ScaleMode=oe,exports.SceneManager=an,exports.SceneManagerState=rn,exports.SceneOwner=_e,exports.ScrollView=so,exports.ScrollViewPlugin=oo,exports.ShaderSources=It,exports.Slider=lo,exports.SliderDirection=ao,exports.SliderPlugin=ho,exports.SpineAnimation=ge,exports.Sprite=ce,exports.SpriteAnimator=Wt,exports.Stats=Cr,exports.StatsCollector=Rr,exports.StatsOverlay=Tr,exports.StatsPlugin=Ir,exports.SystemRunner=lt,exports.Text=Jn,exports.TextAlign=Gn,exports.TextInput=Ri,exports.TextInputPlugin=Bi,exports.TextOverflow=Kn,exports.TextPlugin=ei,exports.TextRenderer=Qn,exports.TextVerticalAlign=qn,exports.Time=Re,exports.Toggle=Xi,exports.TogglePlugin=Vi,exports.Transform=re,exports.Tween=pr,exports.TweenHandle=rr,exports.TweenState={Running:0,Paused:1,Completed:2,Cancelled:3},exports.TweenTarget={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12},exports.UICameraInfo=pt,exports.UIEventQueue=_i,exports.UIEvents=xi,exports.UIInteraction=mi,exports.UIInteractionPlugin=Ci,exports.UILayoutPlugin=wi,exports.UIMask=ii,exports.UIMaskPlugin=hi,exports.UIRect=Cn,exports.UIRenderOrderPlugin=ko,exports.Velocity=he,exports.WeChatAssetProvider=Wr,exports.WebAssetProvider=Jo,exports.World=Xe,exports.WorldTransform=le,exports.addStartupSystem=function(e){at().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){at().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){at().push({schedule:e,system:t})},exports.animationPlugin=mr,exports.applyBuildRuntimeConfig=H,exports.applyDirectionalFill=kn,exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=$.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=$.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=$.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=$.canvasMatchWidthOrHeight)},exports.assetPlugin=ns,exports.audioPlugin=Sr,exports.calculateAttenuation=_r,exports.calculatePanning=xr,exports.clearAnimClips=function(){Ut.clear()},exports.clearDrawCallbacks=As,exports.clearUserComponents=function(){const e=G();for(const t of e.keys())Z.delete(t);e.clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeFillAnchors=Fn,exports.computeFillSize=function(e,t,s,n){switch(e){case Tn.BottomToTop:case Tn.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}},exports.computeHandleAnchors=function(e,t){switch(e){case Tn.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case Tn.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case Tn.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1-t}};default:return{anchorMin:{x:t,y:0},anchorMax:{x:t,y:1}}}},exports.computeUIRectLayout=En,exports.createMaskProcessor=di,exports.createRuntimeSceneConfig=qo,exports.createWebApp=Lr,exports.debug=function(e,t,s){nr.debug(e,t,s)},exports.defaultFrameStats=Er,exports.defineComponent=q,exports.defineEvent=function(e){return{_id:Symbol(`Event_${e}`),_name:e}},exports.defineResource=Me,exports.defineSystem=rt,exports.defineTag=function(e){const t=Z.get(e)??G().get(e);if(t)return t;const s=Y(e,{});return G().set(e,s),Z.set(e,s),J(e,{},!0),s},exports.dragPlugin=to,exports.dropdownPlugin=To,exports.error=function(e,t,s){nr.error(e,t,s)},exports.extractAnimClipTexturePaths=Bt,exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([ye]);for(const n of s){const s=e.get(n,ye);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=hn,exports.focusPlugin=mo,exports.getAddressableType=function(e){return v(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of g)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return x},exports.getAnimClip=function(e){return Ut.get(e)},exports.getAssetMimeType=function(e){return y[e.toLowerCase()]},exports.getAssetTypeEntry=v,exports.getComponent=te,exports.getComponentAssetFieldDescriptors=Xt,exports.getComponentAssetFields=Ht,exports.getComponentDefaults=function(e){const t=te(e);return t?V(t._default):null},exports.getComponentEntityFields=Nt,exports.getComponentSpineFieldDescriptor=jt,exports.getCustomExtensions=S,exports.getEditorType=function(e){return v(e)?.editorType??"unknown"},exports.getLogger=function(){return nr},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=K,exports.getWeChatPackOptions=function(){return S().map(e=>({type:"suffix",value:e}))},exports.imagePlugin=Hi,exports.info=function(e,t,s){nr.info(e,t,s)},exports.initDrawAPI=_s,exports.initGLDebugAPI=Qs,exports.initGeometryAPI=Ds,exports.initMaterialAPI=wt,exports.initPlayableRuntime=async function(e){const{app:t,module:s,assets:n,sceneData:i,sceneName:o}=e,r=t.getResource(ts);r&&(r.registerEmbeddedAssets(n),r.setEmbeddedOnly(!0));const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await Br(ESSpineModule,e);return t||console.warn("Spine module not available"),t}(e.spineWasmBase64):null,l=e.physicsWasmBase64?await async function(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await Br(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new kr(n);await Ko({app:t,module:s,provider:c,scenes:[{name:o,data:i}],firstScene:o,spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()},exports.initPostProcessAPI=$s,exports.initRendererAPI=Gs,exports.initRuntime=Ko,exports.initTweenAPI=cr,exports.initWeChatRuntime=async function(e){const t=await o("asset-manifest.json"),s=JSON.parse(t),n=function(e){const{assetIndex:t,pathIndex:s}=e;return e=>{const n=M(e),i=t[e]||t[n]||s[n]||s[e];return i?i.path:n}}(function(e){const t={},s={};for(const n in e.groups){const i=e.groups[n];for(const e in i.assets){const n=i.assets[e];t[e]=n,s[n.path]=n}}return{assetIndex:t,pathIndex:s}}(s)),i=wx.createCanvas(),r=wx.getSystemInfoSync();i.width=r.windowWidth*r.pixelRatio,i.height=r.windowHeight*r.pixelRatio;const a=await e.engineFactory({canvas:i,instantiateWasm:zr("esengine.wasm")}),l=i.getContext("webgl2")||i.getContext("webgl");if(!l)return void console.error("[ESEngine] Failed to create WebGL context");const c=a.GL.registerContext(l,{majorVersion:0===l.getParameter(l.VERSION).indexOf("WebGL 2")?2:1,minorVersion:0,enableExtensionsByDefault:!0}),u=Lr(a,{glContextHandle:c,getViewportSize:()=>({width:i.width,height:i.height})});e.runtimeConfig&&H(u,e.runtimeConfig);let d=null;e.spineFactory&&(d=await $r(e.spineFactory,"spine.wasm"));let h=null;e.physicsFactory&&(h=await $r(e.physicsFactory,"physics.wasm"));const p=new Wr(n),f=[];for(const t of e.sceneNames){const e=await o(`scenes/${t}.json`);f.push({name:t,data:JSON.parse(e)})}await Ko({app:u,module:a,provider:p,scenes:f,firstScene:e.firstScene,spineModule:d,physicsModule:h,physicsConfig:e.physicsConfig,manifest:s,aspectRatio:i.width/i.height}),u.run()},exports.inputPlugin=ht,exports.instantiatePrefab=is,exports.intersectRects=oi,exports.invertMatrix4=ri,exports.isBuiltinComponent=Q,exports.isCustomExtension=P,exports.isEditor=Pi,exports.isKnownAssetExtension=b,exports.isPlatformInitialized=function(){return null!==e},exports.isPlayMode=Mi,exports.isRuntime=function(){return!bi},exports.isTextureRef=mt,exports.isWeChat=s,exports.isWeb=function(){return"web"===e?.name},exports.layoutGroupPlugin=Fo,exports.listViewPlugin=So,exports.loadComponent=Qt,exports.loadPhysicsModule=Do,exports.loadRuntimeScene=Go,exports.loadSceneData=qt,exports.loadSceneWithAssets=Kt,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&b(w(e)))},exports.parseAnimClipData=Dt,exports.platformFetch=n,exports.platformFileExists=r,exports.platformInstantiateWasm=a,exports.platformReadFile=i,exports.platformReadTextFile=o,exports.pointInOBB=function(e,t,s,n,i,o,r,a,l,c){const u=li(l,c),d=Math.sin(-u),h=Math.cos(-u),p=e-s,f=t-n,m=p*h-f*d+s,g=p*d+f*h+n;return m>=s-i*r&&m<=s+i*(1-r)&&g>=n-o*a&&g<=n+o*(1-a)},exports.pointInWorldRect=function(e,t,s,n,i,o,r,a){return e>=s-i*r&&e<=s+i*(1-r)&&t>=n-o*a&&t<=n+o*(1-a)},exports.prefabsPlugin=hs,exports.progressBarPlugin=Ji,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerAnimClip=Lt,exports.registerComponent=ee,exports.registerComponentAssetFields=function(e,t){Ot.set(e,t)},exports.registerComponentEntityFields=function(e,t){Vt.set(e,t)},exports.registerDrawCallback=Es,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(ts);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=Rt,exports.remapEntityFields=Yt,exports.safeAreaPlugin=xo,exports.sceneManagerPlugin=un,exports.screenToWorld=ai,exports.scrollViewPlugin=ro,exports.setEditorMode=function(e){bi=e},exports.setListViewRenderer=function(e,t){if(!vo)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=vo.get(e);s?s.renderer=t:vo.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})},exports.setLogLevel=function(e){nr.setMinLevel(e)},exports.setPlayMode=function(e){Si=e},exports.setWasmErrorHandler=De,exports.shutdownDrawAPI=xs,exports.shutdownGLDebugAPI=Zs,exports.shutdownGeometryAPI=Us,exports.shutdownMaterialAPI=vt,exports.shutdownPostProcessAPI=Os,exports.shutdownRendererAPI=qs,exports.shutdownTweenAPI=ur,exports.sliderPlugin=po,exports.spriteAnimatorSystemUpdate=zt,exports.statsPlugin=Fr,exports.syncFillSpriteSize=function(e,t,s,n,i,o){if(!e.has(t,ce))return;const r=e.get(t,ce);let a,l;switch(s){case Tn.BottomToTop:case Tn.TopToBottom:a=i,l=o*n;break;default:a=i*n,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,ce,r))},exports.textInputPlugin=Di,exports.textPlugin=ti,exports.toBuildPath=M,exports.togglePlugin=Ni,exports.transitionTo=async function(e,t,s){const n=e.getResource(an);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=Ai,exports.uiLayoutPlugin=vi,exports.uiMaskPlugin=pi,exports.uiPlugins=Dr,exports.uiRenderOrderPlugin=Bo,exports.unregisterAnimClip=function(e){Ut.delete(e)},exports.unregisterComponent=function(e){G().delete(e),Z.delete(e)},exports.unregisterDrawCallback=Cs,exports.updateCameraAspectRatio=Zt,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){nr.warn(e,t,s)},exports.wrapSceneSystem=ln,exports.wxFileExists=function(e){return new Promise(t=>{E().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})},exports.wxFileExistsSync=A,exports.wxGetImagePixels=I,exports.wxLoadImage=R,exports.wxLoadImagePixels=F,exports.wxReadFile=function(e){return new Promise((t,s)=>{E().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(C(e,t.errMsg)))}})})},exports.wxReadTextFile=function(e,t="utf-8"){return new Promise((s,n)=>{E().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(C(e,t.errMsg)))}})})},exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{E().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}function s(){return"wechat"===e?.name}async function n(e,s){return t().fetch(e,s)}async function i(e){return t().readFile(e)}async function o(e){return t().readTextFile(e)}async function r(e){return t().fileExists(e)}async function a(e,s){return t().instantiateWasm(e,s)}function l(e,s){return t().createCanvas(e,s)}function c(){return t().now()}function u(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}class d{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,t.volume??1)),this.muted_=t.muted??!1,this.gainNode_.gain.value=this.muted_?0:this.volume_}get name(){return this.name_}get node(){return this.gainNode_}get volume(){return this.volume_}set volume(e){this.volume_=Math.max(0,Math.min(1,e)),this.muted_||this.gainNode_.gain.setTargetAtTime(this.volume_,this.gainNode_.context.currentTime,.015)}get muted(){return this.muted_}set muted(e){this.muted_=e,this.gainNode_.gain.setTargetAtTime(e?0:this.volume_,this.gainNode_.context.currentTime,.015)}connect(e){e instanceof d?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class h{constructor(e,t,s){this.panWarned_=!1,this.id=e,this.ctx_=t,this.contexts_=s}stop(){this.ctx_.stop(),this.ctx_.destroy(),this.contexts_.delete(this.id)}pause(){this.ctx_.pause()}resume(){this.ctx_.play()}setVolume(e){this.ctx_.volume=e}setPan(e){this.panWarned_||(console.warn("[Audio] WeChat InnerAudioContext does not support stereo panning"),this.panWarned_=!0)}setLoop(e){this.ctx_.loop=e}setPlaybackRate(e){this.ctx_.playbackRate=e}get isPlaying(){return!this.ctx_.paused}get currentTime(){return this.ctx_.currentTime}get duration(){return this.ctx_.duration}}class p{constructor(){this.name="WeChat",this.contexts_=new Map,this.urlCache_=new Map,this.nextId_=0}get mixer(){return null}get isReady(){return!0}async initialize(e){}async ensureResumed(){}async loadBuffer(e){const t=++this.nextId_;return this.urlCache_.set(t,e),{id:t,duration:0}}unloadBuffer(e){this.urlCache_.delete(e.id)}play(e,t){const s=this.urlCache_.get(e.id);if(!s)throw new Error(`Buffer ${e.id} not found`);const n=wx.createInnerAudioContext();n.loop=t.loop??!1,n.volume=t.volume??1,n.playbackRate=t.playbackRate??1,n.startTime=t.startOffset??0,n.obeyMuteSwitch=!1;const i=++this.nextId_;this.contexts_.set(i,n);const o=new h(i,n,this.contexts_);return n.onEnded(()=>{o.onEnd?.(),n.loop||(n.destroy(),this.contexts_.delete(i))}),n.onError(e=>{console.error(`[WeChatAudio] Playback error for "${s}":`,e.errMsg)}),n.src=s,n.play(),o}suspend(){for(const e of this.contexts_.values())e.pause()}resume(){for(const e of this.contexts_.values())e.paused&&e.play()}dispose(){for(const e of this.contexts_.values())e.destroy();this.contexts_.clear(),this.urlCache_.clear()}}function f(e,t){return new Promise((s,n)=>{const i=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===i?"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 m(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 g=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],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},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0}],y={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",bmfont:"application/json",fnt:"text/plain"},_=new Map,x=new Set;for(const e of g)for(const t of e.extensions)_.set(t,e),x.add(t);function w(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function v(e){return _.get(w(e))}function b(e){return x.has(e.toLowerCase())}function S(){const e=[];for(const t of g)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function P(e){const t=v(e);return t?.wechatPackInclude??!1}function M(e){const t=v(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const s=e.lastIndexOf(".");return s>=0?e.substring(0,s)+".json":e}let T=null;function E(){return T||(T=wx.getFileSystemManager()),T}function C(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(P(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 A(e){const t=E();try{return t.accessSync(e),!0}catch{return!1}}function R(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 I(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 i=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(i.data.buffer)}}async function F(e){return I(await R(e))}let k=!1;const B=new class{constructor(){this.name="wechat",this.inputCleanup_=null}async fetch(e,t){return f(e,t)}async readFile(e){return function(e){return E().readFileSync(e)}(M(e))}async readTextFile(e){return function(e,t="utf-8"){return E().readFileSync(e,t)}(M(e))}async fileExists(e){return A(M(e))}async loadImagePixels(e){return F(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return m(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){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const s=t=>e.onKeyDown(t.code),n=t=>e.onKeyUp(t.code),i="function"==typeof wx.onKeyDown;i&&(wx.onKeyDown(s),wx.onKeyUp(n));const o=t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX,s.clientY)},r=t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX,s.clientY)},a=t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)};wx.onTouchStart(o),wx.onTouchMove(r),wx.onTouchEnd(a),this.inputCleanup_=()=>{i&&(wx.offKeyDown(s),wx.offKeyUp(n)),wx.offTouchStart(o),wx.offTouchMove(r),wx.offTouchEnd(a)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new p}},D=1920,U=1080,L=1/60,z={x:0,y:-9.81},W=1/60,$={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};const O={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function H(e,t){if(void 0!==t.maxDeltaTime&&($.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&($.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&($.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&($.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&($.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");$.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&($.canvasScaleMode=O[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&($.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight)}const N=4294967295,X=4294967295;function j(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(j);const t={};for(const s in e)t[s]=j(e[s]);return t}let V=0;function Y(e,t){const s=++V,n=function(e){for(const t in e){const s=e[t];if(null!==s&&"object"==typeof s)return!0}return!1}(t);return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>n?e?{...j(t),...e}:j(t):e?{...t,...e}:{...t}}}function G(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function q(e,t){const s=Z.get(e)??G().get(e);if(s)return s;const n=Y(e,t);return G().set(e,n),Z.set(e,n),J(e,t,!1),n}function K(e){return G().get(e)}function J(e,t,s){const n=globalThis;n.__esengine_registerComponent&&n.__esengine_registerComponent(e,t,s)}function Q(e){return!0===e._builtin}const Z=new Map;function ee(e,t){Z.set(e,t)}function te(e){return Z.get(e)??K(e)}function se(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return Z.set(e,s),s}const ne={Perspective:0,Orthographic:1},ie={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},oe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},re=se("Transform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}}),ae=re,le=re,ce=se("Sprite",{texture:N,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),ue=se("Camera",{projectionType:ne.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:ie.ColorAndDepth}),de=se("Canvas",{designResolution:{x:D,y:U},pixelsPerUnit:100,scaleMode:oe.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),he=se("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),pe=se("Parent",{entity:0}),fe=se("Children",{entities:[]}),me=se("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:X,enabled:!0}),ge=se("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),ye=q("Name",{value:""}),_e=q("SceneOwner",{scene:"",persistent:!1});const xe=se("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),we=se("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ve=se("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),be=se("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Se={Static:0,Kinematic:1,Dynamic:2};let Pe=0;function Me(e,t){const s=++Pe;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function Te(e){return{_type:"res",_resource:e}}function Ee(e){return{_type:"res_mut",_resource:e}}class Ce{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class Ae{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new Ce(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Re=Me({delta:0,elapsed:0,frameCount:0},"Time");function Ie(e,t,s){const n=[];for(const[e,i]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const s=Fe(t[e]),o=Fe(i);"null"!==s&&"undefined"!==s&&(s!==o&&null!=i&&n.push({field:e,expected:s,actual:o,value:i}))}return n}function Fe(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ke(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}let Be=null;function De(e){Be=e}function Ue(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Be&&Be(e,t)}function Le(e){let t=!1;for(const s of Object.keys(e)){const n=e[s];if(null!=n&&"object"==typeof n&&!Array.isArray(n)){if("r"in n&&"g"in n&&"b"in n&&"a"in n&&!("x"in n)){t=!0;break}}}if(!t)return e;const s={};for(const t of Object.keys(e)){const n=e[t];if(null==n||"object"!=typeof n||Array.isArray(n))s[t]=n;else{const e=n;s[t]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:n}}return s}let ze=1;const We=new WeakMap;function $e(e){let t=We.get(e);return void 0===t&&(t=ze++,We.set(e,t)),t}const Oe=[];function He(e,t=[],s=[]){Oe.length=0;for(const t of e)Oe.push($e(t));Oe.sort((e,t)=>e-t);let n=Oe.join(",");if(t.length>0){Oe.length=0;for(const e of t)Oe.push($e(e));Oe.sort((e,t)=>e-t),n+="|+"+Oe.join(",")}if(s.length>0){Oe.length=0;for(const e of s)Oe.push($e(e));Oe.sort((e,t)=>e-t),n+="|-"+Oe.join(",")}return n}class Ne{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw Ue(e,"spawn"),e}else e=++this.nextEntityId_;let t=0;if(this.module_&&this.cppRegistry_)try{t=this.module_.registry_getGeneration(this.cppRegistry_,e)}catch{}else t=++this.nextGeneration_;this.entities_.set(e,t),this.worldVersion_++;for(const t of this.spawnCallbacks_)try{t(e)}catch{}return e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch{}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){Ue(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t){this.tsStorage_.get(s)?.delete(e),this.componentAddedTicks_.get(s)?.delete(e),this.componentChangedTicks_.get(s)?.delete(e);let t=this.componentRemovedBuffer_.get(s);t||(t=[],this.componentRemovedBuffer_.set(s,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){Ue(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Ue(t,`removeParent(entity=${e})`)}}insert(e,t,s){return Q(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}set(e,t,s){if(Q(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,Le(s))}catch(s){Ue(s,`set(${t._name}, entity=${e})`)}this.recordChangedTick_(t,e)}else this.getStorage(t).set(e,s),this.recordChangedTick_(t,e)}get(e,t){return Q(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return Q(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(Q(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return Ue(s,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");Q(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_,n=s[`add${e}`],i=s[`get${e}`],o=s[`has${e}`],r=s[`remove${e}`];if("function"!=typeof n||"function"!=typeof i||"function"!=typeof o||"function"!=typeof r)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:n.bind(s),get:i.bind(s),has:o.bind(s),remove:r.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(ke(t._name,e))}const i={...t._default,...n};let o=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(t._cppName);o=!s.has(e),s.add(e,Le(i))}catch(s){Ue(s,`insertBuiltin(${t._name}, entity=${e})`)}return o&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let s=!1;for(const n of Object.keys(t)){const i=t[n];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){const t=e[n];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){s=!0;break}}}if(!s)return e;const n={};for(const s of Object.keys(e)){const i=e[s],o=t[s];if(null==i||"object"!=typeof i||Array.isArray(i)||null==o||"object"!=typeof o||Array.isArray(o))n[s]=i;else{const e=i,t=o;n[s]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:i}}return n}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(s){return Ue(s,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(s){return Ue(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Ue(s,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++}}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 i=Ie(t._name,t._default,e);if(i.length>0)throw new Error(ke(t._name,i));n=e}const i=t.create(n),o=this.getStorage(t),r=!o.has(e);o.set(e,i);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}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.recordRemovedTick_(t,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}getComponentTypes(e){const t=new Set;for(const[s,n]of this.builtinMethodCache_)try{n.has(e)&&t.add(s)}catch{}if(this.cppRegistry_)for(const[s,n]of Z)if(Q(n)&&!t.has(s))try{this.getBuiltinMethods(n._cppName).has(e)&&t.add(s)}catch{}const s=this.entityComponents_.get(e);if(s){const e=G();for(const n of s)for(const[s,i]of e)if(i._id===n){t.add(s);break}}return Array.from(t)}getEntitiesWithComponents(e,t=[],s=[],n){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();const i=n??He(e,t,s),o=this.queryCache_.get(i);if(o&&o.version===this.worldVersion_)return o.result;let r=null,a=1/0;for(const t of e)if(!Q(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<a&&(a=s,r=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=r?r.keys():this.entities_.keys();for(const n of c){let i=!0;for(const t of e)if(!this.has(n,t)){i=!1;break}if(i)for(const e of t)if(!this.has(n,e)){i=!1;break}if(i)for(const e of s)if(this.has(n,e)){i=!1;break}i&&l.push(n)}return this.queryCache_.set(i,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,s){const n=this.componentAddedTicks_.get(t._id);if(!n)return!1;const i=n.get(e);return void 0!==i&&i>s}isChangedSince(e,t,s){const n=this.componentChangedTicks_.get(t._id);if(!n)return!1;const i=n.get(e);return void 0!==i&&i>s}getRemovedEntitiesSince(e,t){const s=this.componentRemovedBuffer_.get(e._id);if(!s)return[];const n=[];for(const e of s)e.tick>t&&n.push(e.entity);return n}cleanRemovedBuffer(e){for(const[t,s]of this.componentRemovedBuffer_){let n=0;for(let t=0;t<s.length;t++)s[t].tick>=e&&(s[n++]=s[t]);s.length=n,0===n&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let s=this.componentAddedTicks_.get(e._id);s||(s=new Map,this.componentAddedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordChangedTick_(e,t){let s=this.componentChangedTicks_.get(e._id);s||(s=new Map,this.componentChangedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordRemovedTick_(e,t){let s=this.componentRemovedBuffer_.get(e._id);s||(s=[],this.componentRemovedBuffer_.set(e._id,s)),s.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function Xe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function je(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Ve(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Ye(e){return Xe(e)||je(e)||Ve(e)?e._component:e}function Ge(e,t=[],s=[]){const n=[],i=[],o=[];return e.forEach((e,t)=>{Xe(e)&&n.push(t),je(e)?i.push({index:t,component:e._component}):Ve(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s,_addedFilters:i,_changedFilters:o,with:(...n)=>Ge(e,[...t,...n],s),without:(...n)=>Ge(e,t,[...s,...n])}}class qe{constructor(e,t,s=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=s,this.actualComponents_=t._components.map(Ye),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=He(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:s}=this.descriptor_;if(0===t.length&&0===s.length)return!0;const n=this.lastRunTick_;for(const s of t)if(!this.world_.isAddedSince(e,s.component,n))return!1;for(const t of s)if(!this.world_.isChangedSince(e,t.component,n))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),n=t.length,i=e.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const u of s)if(!o||this.passesChangeFilters_(u)){if(null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}r[0]=u;for(let e=0;e<n;e++)r[e+1]=this.world_.get(u,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];c=u}yield r}}finally{if(this.world_.endIteration(),null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class Ke{constructor(e,t,s){this.world_=e,this.component_=t,this.lastRunTick_=s}*[Symbol.iterator](){yield*this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}isEmpty(){return 0===this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_).length}toArray(){return this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}}class Je{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=Q(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Qe{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Je(this,null);return this.spawned_.push(e),e}entity(e){return new Je(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"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)}}}class Ze{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(e){this.writeBuffer_.push(e)}getReadBuffer(){return this.readBuffer_}swap(){const e=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=e,this.writeBuffer_.length=0}}class et{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Ze)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Ze,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}class tt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class st{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var nt;function it(){return{_type:"get_world"}}exports.Schedule=void 0,(nt=exports.Schedule||(exports.Schedule={}))[nt.Startup=0]="Startup",nt[nt.First=1]="First",nt[nt.PreUpdate=2]="PreUpdate",nt[nt.Update=3]="Update",nt[nt.PostUpdate=4]="PostUpdate",nt[nt.Last=5]="Last",nt[nt.FixedPreUpdate=10]="FixedPreUpdate",nt[nt.FixedUpdate=11]="FixedUpdate",nt[nt.FixedPostUpdate=12]="FixedPostUpdate";let ot=0;function rt(e,t,s){const n=++ot;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function at(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}class lt{constructor(e,t,s){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=s??null}setTimingEnabled(e){this.timings_=e?new Map:null}getTimings(){return this.timings_}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);const s=this.timings_?performance.now():0;try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Qe&&t[e].flush()}finally{this.timings_&&this.timings_.set(e._name,performance.now()-s),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new qe(this.world_,e,this.currentLastRunTick_);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Qe(this.world_,this.resources_);case"event_writer":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new tt(s)}case"event_reader":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new st(s)}case"removed":{const t=e;return new Ke(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class ct{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 ut=Me(new ct,"Input");class dt{constructor(e){this.target_=e??null}build(e){const s=new ct;e.insertResource(ut,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,rt([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ht=new dt,pt=Me({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var ft;function mt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(ft=exports.BlendMode||(exports.BlendMode={}))[ft.Normal=0]="Normal",ft[ft.Additive=1]="Additive",ft[ft.Multiply=2]="Multiply",ft[ft.Screen=3]="Screen",ft[ft.PremultipliedAlpha=4]="PremultipliedAlpha";let gt=null,yt=null,_t=1;const xt=new Map;function wt(e){gt=e,yt=e.getResourceManager(),Rt()}function vt(){0!==Mt&>&&(gt._free(Mt),Mt=0),xt.clear(),_t=1,Pt=!1,Et.clear(),Ct=null,yt=null,gt=null}function bt(){if(!yt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return yt}const St={createShader:(e,t)=>bt().createShader(e,t),releaseShader(e){e>0&&bt().releaseShader(e)},create(e){const t=_t++,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 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,gt?.invalidateMaterialCache(e))},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,gt?.invalidateMaterialCache(e))},getBlendMode(e){const t=xt.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=xt.get(e);s&&(s.depthTest=t,gt?.invalidateMaterialCache(e))},getShader(e){const t=xt.get(e);return t?.shader??0},release(e){xt.delete(e),gt?.invalidateMaterialCache(e)},isValid:e=>xt.has(e),releaseAll(){xt.clear(),gt?.clearMaterialCache()},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=xt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=_t++,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 Pt=!1,Mt=0;const Tt=16384,Et=new Map;let Ct=null;function At(e){const t=(0===Mt&>&&(Mt=gt._malloc(Tt)),Mt);if(0===t||!gt)return{ptr:0,count:0};let s=0,n=0;const i=gt.HEAPU8,o=gt.HEAPU32,r=gt.HEAPF32;for(const[a,l]of e){if(mt(l))continue;let e=Et.get(a);e||(Ct||(Ct=new TextEncoder),e=Ct.encode(a),Et.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(s+(4+u+4+16)>Tt){console.warn(`[ESEngine] Material uniform buffer full (${s}/${Tt} bytes), skipping remaining uniforms`);break}o[t+s>>2]=c,s+=4,i.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++)r[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function Rt(){if(!gt||Pt)return;gt.materialDataProvider=(e,t,s,n,i)=>{const o=xt.get(e);if(!o)return gt.HEAPU32[t>>2]=0,gt.HEAPU32[s>>2]=0,gt.HEAPU32[n>>2]=0,void(gt.HEAPU32[i>>2]=0);gt.HEAPU32[t>>2]=o.shader,gt.HEAPU32[s>>2]=o.blendMode;const{ptr:r,count:a}=At(o.uniforms);gt.HEAPU32[n>>2]=r,gt.HEAPU32[i>>2]=a},Pt=!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,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const i=this.pending_.get(e);if(i&&!i.aborted)return i.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),i=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,i),this.pending_.delete(e),i})(),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 kt{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&&(St.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())St.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await r(t))throw new Error(`Material file not found: ${t}`);const s=await o(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:St.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}}function Bt(e){const t=new Set;for(const s of e.frames)s.texture&&t.add(s.texture);return Array.from(t)}function Dt(e,t,s){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>{const t={texture:s.get(e.texture)??0};if(e.atlasFrame){const s=e.atlasFrame;t.uvOffset={x:s.x/s.pageWidth,y:1-(s.y+s.height)/s.pageHeight},t.uvScale={x:s.width/s.pageWidth,y:s.height/s.pageHeight}}return t})}}const Ut=new Map;function Lt(e){Ut.set(e.name,e)}const zt=q("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function Wt(e,t){const s=e.getEntitiesWithComponents([zt]);for(const n of s){const s=e.get(n,zt);if(!s.enabled||!s.playing||!s.clip)continue;const i=Ut.get(s.clip);if(!i||0===i.frames.length)continue;const o=1/(i.fps*s.speed),r=0===s.frameTimer&&0===s.currentFrame;s.frameTimer+=t;let a=r;if(s.frameTimer>=o&&(s.frameTimer-=o,s.currentFrame++,s.currentFrame>=i.frames.length&&(s.loop&&i.loop?s.currentFrame=0:(s.currentFrame=i.frames.length-1,s.playing=!1)),a=!0),a&&e.has(n,ce)){const t=i.frames[s.currentFrame],o=e.get(n,ce);o.texture=t.texture,t.uvOffset&&(o.uvOffset=t.uvOffset,o.uvScale=t.uvScale),e.insert(n,ce,o)}a&&e.insert(n,zt,s)}}class $t{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null,this.bgmVolume_=1,this.disposed_=!1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}static async preload(e){if(this.bufferCache_.has(e))return;const t=await this.backend_.loadBuffer(e);this.bufferCache_.set(e,t)}static async preloadAll(e){await Promise.all(e.map(e=>this.preload(e)))}static playSFX(e,t){const s={bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0},n=this.bufferCache_.get(e);if(!n){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const n=this.bufferCache_.get(e);n&&t.resolve(this.backend_.play(n,s))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(n,s)}static playBGM(e,t){const s=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const s=t?.volume??1,n=this.bgmVolume_;this.bgmVolume_=s,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,n):this.bgmHandle_&&this.bgmHandle_.stop();const i=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:i?0:s,loop:!0}),i&&this.fadeIn(this.bgmHandle_,i,s)},n=this.bufferCache_.get(e);n?s(n):this.preload(e).then(()=>{if(this.disposed_)return;const t=this.bufferCache_.get(e);t&&s(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else this.bgmHandle_.stop(),this.bgmHandle_=null}static setMasterVolume(e){this.mixer_&&(this.mixer_.master.volume=e)}static setMusicVolume(e){this.mixer_&&(this.mixer_.music.volume=e)}static setSFXVolume(e){this.mixer_&&(this.mixer_.sfx.volume=e)}static setUIVolume(e){this.mixer_&&(this.mixer_.ui.volume=e)}static muteBus(e,t){const s=this.mixer_?.getBus(e);s&&(s.muted=t)}static getBufferHandle(e){return this.bufferCache_.get(e)}static dispose(){this.disposed_=!0,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}static fadeIn(e,t,s){e.setVolume(0);const n=performance.now(),i=()=>{const o=(performance.now()-n)/1e3,r=Math.min(o/t,1);e.setVolume(r*s),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,s){const n=performance.now(),i=()=>{const o=(performance.now()-n)/1e3,r=Math.min(o/t,1);e.setVolume(s*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}static createDeferredHandle(){let e=null;return{id:-1,stop(){e?.stop()},pause(){e?.pause()},resume(){e?.resume()},setVolume(t){e?.setVolume(t)},setPan(t){e?.setPan(t)},setLoop(t){e?.setLoop(t)},setPlaybackRate(t){e?.setPlaybackRate(t)},get isPlaying(){return e?.isPlaying??!1},get currentTime(){return e?.currentTime??0},get duration(){return e?.duration??0},resolve(t){e=t}}}}$t.mixer_=null,$t.bufferCache_=new Map,$t.bgmHandle_=null,$t.bgmVolume_=1,$t.fadeAnimId_=0,$t.disposed_=!1;const Ot=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}],["AudioSource",{fields:[{field:"clip",type:"audio"}]}]]);function Ht(e){const t=Ot.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s}function Nt(e){return Ot.get(e)?.fields??[]}function Xt(e){return Ot.get(e)?.spine??null}const jt=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Vt(e){return jt.get(e)}function Yt(e,t){const s=jt.get(e.type);if(!s)return;const n=e.data;for(const i of s){const s=n[i];if("number"==typeof s&&0!==s){const o=t.get(s);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${s} which does not exist`),n[i]=void 0!==o?o:0}}}function Gt(e,t){const s=new Map;for(const n of t.entities){if(!1===n.visible)continue;const t=e.spawn();s.set(n.id,t),e.insert(t,ye,{value:n.name})}for(const n of t.entities){if(!1===n.visible)continue;const t=s.get(n.id);for(const i of n.components)Yt(i,s),Qt(e,t,i,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),i=s.get(n.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return s}function qt(e,t){return Gt(e,t)}async function Kt(e,t,s){const n=s?.assetServer,i=s?.assetBaseUrl??n?.baseUrl,o=new Map;n&&await async function(e,t,s,n,i){const o=new Map;for(const e of Jt.keys())o.set(e,new Set);const r=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ot.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...Jt.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,s,n);l.set(e,r)}),u=r.map(async e=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)});if(await Promise.all([...c,...u]),i){for(const e of n.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ot.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const n=s[e.field];if("string"!=typeof n||!n)continue;const i=t.get(n);void 0!==i&&(s[e.field]=i)}}}(t,n,i,o,s?.collectAssets);const r=Gt(e,t);if(n&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&n.setTextureMetadataByPath(t,s.sliceBorder)}return r}const Jt=new Map([["texture",{async load(e,t,s,n){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),n.set(e,o)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(o),i}}],["material",{async load(e,t,s){const n=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,s);n.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),n.set(e,0)}});return await Promise.all(i),n}}],["font",{async load(e,t,s){const n=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,s);n.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),n.set(e,0)}});return await Promise.all(i),n}}],["anim-clip",{async load(e,t,s,n){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=Bt(i),r=new Map,a=o.map(async e=>{try{const i=s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),n.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);Lt(Dt(e,i,r))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(i),new Map}}],["audio",{async load(e,t,s){const n=[...e].map(e=>s?`${s}/${e}`:`/${e}`);return await $t.preloadAll(n).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}]]);function Qt(e,t,s,n){if("LocalTransform"!==s.type&&"WorldTransform"!==s.type||(s.type="Transform"),"UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===s.type){const e=s.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=te(s.type);if(i)e.insert(t,i,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function Zt(e,t){const s=e.getEntitiesWithComponents([ue]);for(const n of s){const s=e.get(n,ue);s&&(s.aspectRatio=t,e.insert(n,ue,s))}}class es{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.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=l($.textCanvasSize,$.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new kt(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),i=this.textureCache_.get(n);if(!i)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),St.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const i=this.resolveUrl(t,s),o=await this.fetchText(i);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=r?`${r}/${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"===v(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),i=l.find(e=>e.name===s);if(i){const s=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,i.info.width,i.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}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=v(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 i=s?`${s}/${n}`:n;return this.loadFntFile(i)}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],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${n}`:n,r=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,r.handle,r.width,r.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,async()=>{const e=await this.fetchJson(s);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const s of e.entities){for(const e of s.components){if(!e.data)continue;for(const s of Ht(e.type)){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}const s=Xt(e.type);if(s)for(const n of[s.skeletonField,s.atlasField]){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}}if(s.nestedPrefab?.prefabPath){const e=t(s.nestedPrefab.prefabPath);e&&(s.nestedPrefab.prefabPath=e)}}}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const 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 Kt(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 i=n.metadata?.atlas;i&&s.push(this.loadSpine(n.path,i).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return this.loadImageFromSrc(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){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=e})}createTextureFromImage(e,t){const{width:s,height:n}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,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,i){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const r=this.module_.GL,a=r.getNewId(r.textures);r.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 i=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(o);const r=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=r.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.getEmbedded(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:i}=this.parseEsShader(t);if(!n||!i)throw new Error(`Invalid shader format: ${e}`);return St.createShader(n,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await r(t))throw new Error(`Shader file not found: ${e}`);const n=await o(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 St.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://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(M(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(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.getEmbedded(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return o(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(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.getEmbedded(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return i(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(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 i="";for(const e of n){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const 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 ts=Me(null,"Assets");class ss{build(e){const t=e.wasmModule;t?e.insertResource(ts,new es(t)):console.warn("AssetPlugin: No WASM module available")}}const ns=new ss;async function is(e,t,s){const{entities:n,rootId:i}=await rs(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}))},r=await Kt(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=r.get(i);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:r}}const os=10;async function rs(e,t,s,n,i,o=0){if(o>os)throw new Error(`Prefab nesting depth exceeded ${os}. Check for deep or circular nesting in: ${e.name}`);const r=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,a++)}const l=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(i?.has(n.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${n.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await rs(e,n.nestedPrefab.overrides,s,a,i,o+1);r.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?r.get(n.parent)??null:null),l.push(...t.entities);continue}const c=r.get(n.prefabEntityId),u=n.prefabEntityId===e.rootEntityId,d={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?null:null!==n.parent?r.get(n.parent)??null:null,children:n.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};as(d.components,r),ls(d,t),l.push(d)}const c=r.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function as(e,t){for(const s of e){const e=Vt(s.type);if(e)for(const n of e){const e=s.data[n];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(s.data[n]=i)}}}}function ls(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 cs{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,i=await this.assetServer_.loadPrefab(n,t?.baseUrl);return is(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const us=Me(null,"Prefabs");class ds{constructor(){this.name="PrefabsPlugin",this.dependencies=[ts]}build(e){const t=e.getResource(ts);e.insertResource(us,new cs(e.world,t))}}const hs=new ds;let ps=null,fs=0,ms=0,gs=0;const ys=new Float32Array(256);function _s(e){ps=e,fs=ps._malloc(64),ms=ps._malloc(64),gs=ps._malloc(1024)}function xs(){ps&&(fs&&(ps._free(fs),fs=0),ms&&(ps._free(ms),ms=0),gs&&(ps._free(gs),gs=0)),ps=null}function ws(){if(!ps)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return ps}const vs={r:1,g:1,b:1,a:1},bs={begin(e){const t=ws();try{t.HEAPF32.set(e,fs/4),t.draw_begin(fs)}catch(e){Ue(e,"Draw.begin")}},end(){try{ws().draw_end()}catch(e){Ue(e,"Draw.end")}},line(e,t,s,n=1){try{ws().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ue(e,"Draw.line")}},rect(e,t,s,n=!0){try{ws().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ue(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{ws().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ue(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,i=32){try{ws().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){Ue(e,"Draw.circle")}},circleOutline(e,t,s,n=1,i=32){try{ws().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){Ue(e,"Draw.circleOutline")}},texture(e,t,s,n=vs){try{ws().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Ue(e,"Draw.texture")}},textureRotated(e,t,s,n,i=vs){try{ws().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,i.r,i.g,i.b,i.a)}catch(e){Ue(e,"Draw.textureRotated")}},setLayer(e){ws().draw_setLayer(e)},setDepth(e){ws().draw_setDepth(e)},getDrawCallCount:()=>ps?ps.draw_getDrawCallCount():0,getPrimitiveCount:()=>ps?ps.draw_getPrimitiveCount():0,setBlendMode(e){ws().draw_setBlendMode(e)},setDepthTest(e){ws().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=ws();n.HEAPF32.set(s,ms/4),n.draw_mesh(e,t,ms)}catch(s){Ue(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=ws(),i=St.get(t);if(!i)return;if(bs.setBlendMode(i.blendMode),bs.setDepthTest(i.depthTest),0===i.uniforms.size)return void bs.drawMesh(e,i.shader,s);let o;if(n.HEAPF32.set(s,ms/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,s]of i.uniforms){const n=Ms(t);if(!(n<0)){if(mt(s))ys[o++]=10,ys[o++]=n,ys[o++]=s.slot??e++,ys[o++]=s.textureId;else if("number"==typeof s)ys[o++]=1,ys[o++]=n,ys[o++]=s;else if(Array.isArray(s)){ys[o++]=s.length,ys[o++]=n;for(let e=0;e<s.length;e++)ys[o++]=s[e]}else"w"in s?(ys[o++]=4,ys[o++]=n,ys[o++]=s.x,ys[o++]=s.y,ys[o++]=s.z,ys[o++]=s.w):"z"in s?(ys[o++]=3,ys[o++]=n,ys[o++]=s.x,ys[o++]=s.y,ys[o++]=s.z):(ys[o++]=2,ys[o++]=n,ys[o++]=s.x,ys[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<o)&&(i.cachedBuffer_=new Float32Array(o)),i.cachedBuffer_.set(ys.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void n.draw_mesh(e,i.shader,ms);n.HEAPF32.set(i.cachedBuffer_.subarray(0,o),gs/4),n.draw_meshWithUniforms(e,i.shader,ms,gs,o)}catch(s){Ue(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Ss={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17},Ps=new Set;function Ms(e){const t=Ss[e];return void 0!==t?t:(Ps.has(e)||(Ps.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Ss).join(", ")}`)),-1)}const Ts=new Map;function Es(e,t,s){Ts.set(e,{fn:t,scene:s??""})}function Cs(e){Ts.delete(e)}function As(){Ts.clear()}var Rs;exports.DataType=void 0,(Rs=exports.DataType||(exports.DataType={}))[Rs.Float=1]="Float",Rs[Rs.Float2=2]="Float2",Rs[Rs.Float3=3]="Float3",Rs[Rs.Float4=4]="Float4",Rs[Rs.Int=5]="Int",Rs[Rs.Int2=6]="Int2",Rs[Rs.Int3=7]="Int3",Rs[Rs.Int4=8]="Int4";let Is=null,Fs=0,ks=0,Bs=0;function Ds(e){Is=e,Fs=Is._malloc(262144),ks=Is._malloc(65536),Bs=Is._malloc(256)}function Us(){Is&&(Fs&&Is._free(Fs),ks&&Is._free(ks),Bs&&Is._free(Bs),Fs=0,ks=0,Bs=0),Is=null}function Ls(){if(!Is)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Is}const zs={create(e){const t=Ls(),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,Fs/4);const i=e.layout.length,o=new Int32Array(i);for(let t=0;t<i;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Bs,i).set(o),t.geometry_init(s,Fs,n,Bs,i,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,ks,n).set(e.indices),t.geometry_setIndices16(s,ks,n)}else{new Uint32Array(t.HEAPU8.buffer,ks,n).set(e.indices),t.geometry_setIndices32(s,ks,n)}}return s},updateVertices(e,t,s=0){const n=Ls(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);n.HEAPF32.set(t,Fs/4),n.geometry_updateVertices(e,Fs,i,s)},release(e){e>0&&Ls().geometry_release(e)},isValid:e=>!(!Is||e<=0)&&Is.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return zs.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 i=n/t*Math.PI*2,o=Math.cos(i)*e,r=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;s.push(o,r,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return zs.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,i=-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),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(n-t),a=(r.y-s)/(i-s);o.push(r.x,r.y,e,a)}const r=[];for(let t=1;t<e.length-1;t++)r.push(0,t,t+1);return zs.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(r)})}};let Ws=null;function $s(e){Ws=e}function Os(){Ws&&Ns.isInitialized()&&Ns.shutdown(),Ws=null}function Hs(){if(!Ws)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ws}const Ns={init(e,t){try{return Hs().postprocess_init(e,t)}catch(s){return Ue(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Hs().postprocess_shutdown()}catch(e){Ue(e,"PostProcess.shutdown")}},resize(e,t){try{Hs().postprocess_resize(e,t)}catch(s){Ue(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Hs().postprocess_addPass(e,t)}catch(t){return Ue(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Hs().postprocess_removePass(e)}catch(t){Ue(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Hs().postprocess_setPassEnabled(e,t)}catch(t){Ue(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Hs().postprocess_isPassEnabled(e)}catch(t){return Ue(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{Hs().postprocess_setUniformFloat(e,t,s)}catch(s){Ue(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{Hs().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){Ue(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Hs().postprocess_begin()}catch(e){Ue(e,"PostProcess.begin")}},end(){try{Hs().postprocess_end()}catch(e){Ue(e,"PostProcess.end")}},getPassCount(){try{return Hs().postprocess_getPassCount()}catch(e){return Ue(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Ws)return!1;try{return Ws.postprocess_isInitialized()}catch(e){return Ue(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Hs().postprocess_setBypass(e)}catch(e){Ue(e,"PostProcess.setBypass")}},isBypassed(){if(!Ws)return!0;try{return Ws.postprocess_isBypassed()}catch(e){return Ue(e,"PostProcess.isBypassed"),!0}},createBlur:()=>St.createShader(Xs,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>St.createShader(Xs,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>St.createShader(Xs,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>St.createShader(Xs,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},Xs="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var js;exports.RenderStage=void 0,(js=exports.RenderStage||(exports.RenderStage={}))[js.Background=0]="Background",js[js.Opaque=1]="Opaque",js[js.Transparent=2]="Transparent",js[js.Overlay=3]="Overlay";let Vs=null,Ys=0;function Gs(e){Vs=e,Ys=Vs._malloc(64)}function qs(){Vs&&Ys&&(Vs._free(Ys),Ys=0),Vs=null}const Ks={init(e,t){Vs?.renderer_init(e,t)},resize(e,t){Vs?.renderer_resize(e,t)},begin(e,t){if(Vs&&Ys)try{Vs.HEAPF32.set(e,Ys/4),Vs.renderer_begin(Ys,t??0)}catch(e){Ue(e,"Renderer.begin")}},flush(){try{Vs?.renderer_flush()}catch(e){Ue(e,"Renderer.flush")}},end(){try{Vs?.renderer_end()}catch(e){Ue(e,"Renderer.end")}},submitSprites(e){if(Vs)try{Vs.renderer_submitSprites(e._cpp)}catch(e){Ue(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Vs)try{Vs.renderer_submitBitmapText(e._cpp)}catch(e){Ue(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Vs)try{Vs.renderer_submitSpine?.(e._cpp)}catch(e){Ue(e,"Renderer.submitSpine")}},setStage(e){Vs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Vs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Vs?.renderer_releaseTarget(e)},getTargetTexture:e=>Vs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Vs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Vs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Vs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,i){Vs?.renderer_setScissor(e,t,s,n,i)},clearBuffers(e){Vs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Vs?Vs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Vs?{drawCalls:Vs.renderer_getDrawCalls(),triangles:Vs.renderer_getTriangles(),sprites:Vs.renderer_getSprites(),text:Vs.renderer_getText(),spine:Vs.renderer_getSpine?.()??0,meshes:Vs.renderer_getMeshes(),culled:Vs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Js=null;function Qs(e){Js=e}function Zs(){Js=null}const en={enable(){Js?.gl_enableErrorCheck(!0)},disable(){Js?.gl_enableErrorCheck(!1)},check:e=>Js?.gl_checkErrors(e)??0,diagnose(){Js?.renderer_diagnose()}};class tn{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:i,elapsed:o}=e;n===this.lastWidth_&&i===this.lastHeight_||(Ks.resize(n,i),Ns.isInitialized()&&Ns.getPassCount()>0&&Ns.resize(n,i),this.lastWidth_=n,this.lastHeight_=i),Ks.setViewport(0,0,n,i),Ks.clearBuffers(3),Ks.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,i),Ks.submitSprites(t),Ks.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ks.submitSpine(t),Ks.flush(),this.executeDrawCallbacks(s,o),Ks.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:i,elapsed:o}=e;Ks.setViewport(n.x,n.y,n.w,n.h),Ks.setScissor(n.x,n.y,n.w,n.h,!0),Ks.clearBuffers(i),Ks.setScissor(0,0,0,0,!1),Ks.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Ks.submitSprites(t),Ks.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ks.submitSpine(t),Ks.flush(),this.executeDrawCallbacks(s,o),Ks.end()}executeDrawCallbacks(e,t){const s=Ts;if(s.size>0){bs.begin(e);const n=[];for(const[e,i]of s.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}bs.end();for(const e of n)Cs(e)}}}const sn="__scene_transition_overlay__";class nn{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class on{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,_e,{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),Es(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Ns.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Ns.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,_e)){const s=this.app_.world.get(e,_e);s.persistent=t,this.app_.world.insert(e,_e,s)}}}class rn{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??$.sceneTransitionDuration,i=t.color??{...$.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:i,targetScene:e,options:t,resolve:s},Es(sn,()=>{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;bs.setLayer(9999),bs.setDepth(9999),bs.rect({x:0,y:0},{x:2e4,y:2e4},{r:i.r,g:i.g,b:i.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()=>{try{s&&s!==e&&await this.unload(s,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,Cs(sn),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Cs(sn),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new nn(t);this.scenes_.set(e,s);const n=new on(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(ts)?this.app_.getResource(ts):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(s,e,t,i),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new nn(t);this.scenes_.set(e,s);const n=new on(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(ts)?this.app_.getResource(ts):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(s,e,t,i),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const i=t?.keepPersistent??!0;for(const e of s.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,_e)){if(this.app_.world.get(e,_e).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())Cs(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Ns.removePass(e)}catch{}s.postProcessPasses.length=0,this.releaseSceneAssets_(s),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)}async loadSceneData_(e,t,s,n){if(n){const s={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:s};this.app_.hasResource(ts)&&(i.assetServer=this.app_.getResource(ts));const o=await Kt(this.app_.world,n,i);e.loadedAssets=s;for(const s of o.values())e.entities.add(s),this.app_.world.insert(s,_e,{scene:t,persistent:!1})}if(s.systems)for(const{schedule:e,system:n}of s.systems){const s=ln(this.app_,t,n);this.app_.addSystemToSchedule(e,s)}const i=this.contexts_.get(t);s.setup&&await s.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const s=this.app_.hasResource(ts)?this.app_.getResource(ts):null;if(s){for(const e of t.textureUrls)s.releaseTexture(e);for(const e of t.fontPaths)s.releaseFont(e);for(const e of t.spineKeys)s.releaseSpine(e)}for(const e of t.materialHandles)St.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n={};let i=!1;if(s.has(e,ce)){const t=s.get(e,ce);n.sprite=t.color.a,t.color.a=0,s.insert(e,ce,t),i=!0}if(s.has(e,ge)){const t=s.get(e,ge);n.spine=t.color.a,t.color.a=0,s.insert(e,ge,t),i=!0}if(s.has(e,me)){const t=s.get(e,me);n.bitmapText=t.color.a,t.color.a=0,s.insert(e,me,t),i=!0}i&&t.savedAlphas.set(e,n)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n=t.savedAlphas.get(e);if(n){if(void 0!==n.sprite&&s.has(e,ce)){const t=s.get(e,ce);t.color.a=n.sprite,s.insert(e,ce,t)}if(void 0!==n.spine&&s.has(e,ge)){const t=s.get(e,ge);t.color.a=n.spine,s.insert(e,ge,t)}if(void 0!==n.bitmapText&&s.has(e,me)){const t=s.get(e,me);t.color.a=n.bitmapText,s.insert(e,me,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{Ns.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 an=Me(null,"SceneManager");function ln(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(an).getSceneStatus(t)&&s._fn(...n)}}}const cn=rt([Ee(an),Te(Re)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),un={name:"SceneManager",build(e){const t=new rn(e);e.insertResource(an,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(an),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(exports.Schedule.Startup,s),e.addSystemToSchedule(exports.Schedule.Last,cn)}};class dn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new et,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=c(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(exports.Schedule.Last);else{this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new Ne,this.resources_=new Ae;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new dn}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}removeSystem(e){let t=!1;for(const[s,n]of this.systems_){const i=n.filter(t=>t.system._id!==e);i.length!==n.length&&(this.systems_.set(s,i),this.sortedSystemsCache_.delete(s),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return De(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}enableStats(){return this.statsEnabled_=!0,this.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}getEntityCount(){return this.world_.entityCount()}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(an).register(e),this}setInitialScene(e){return this.getResource(an).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new lt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(Re)||this.resources_.insert(Re,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(exports.Schedule.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(exports.Schedule.Last);else{this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new lt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(Re,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(exports.Schedule.Startup),this.lastTime_=c(),this.mainLoop())}quit(){this.running_=!1,As();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[Zs,qs,Os,Us,vt,xs];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let 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 i=t.get(n);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,i=new Set,o=r=>{if(n.has(r))return;if(i.has(r)){const t=e[r].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(r);const a=e[r];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}i.delete(r),n.add(r),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));const n=this.phaseTimings_?performance.now():0;for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}this.phaseTimings_&&this.phaseTimings_.set(exports.Schedule[e],performance.now()-n)}updateTime(e){const t=this.resources_.get(Re);t.delta=e,t.elapsed+=e,t.frameCount++}}function hn(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const pn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function fn(e,t,s,n,i){const o=e*t/s,r=e;switch(n){case oe.FixedWidth:return o;case oe.FixedHeight:return r;case oe.Expand:return Math.max(o,r);case oe.Shrink:return Math.min(o,r);case oe.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const mn=[];function gn(e){if(e<mn.length)return mn[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return mn.push(t),t}function yn(e,t,s,n,i,o){if(0===s||0===n)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,_e);return!t||""===t.scene||o.has(t.scene)}):r;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 i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*s/(i.viewportH*n);let a,u=0,d=0;if(i.projectionType===ne.Orthographic){if(d=i.orthoSize,l){d=fn(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=d*r,a=xn(-u,u,-d,d,-i.farPlane,i.farPlane)}else a=vn(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const h=Sn(o.position.x,o.position.y,o.position.z),p=gn(c.length);p.entity=e,p.viewProjection.set(Mn(a,h)),p.viewportRect.x=i.viewportX,p.viewportRect.y=i.viewportY,p.viewportRect.w=i.viewportW,p.viewportRect.h=i.viewportH,p.clearFlags=i.clearFlags,p.priority=i.priority,p.halfW=u,p.halfH=d,p.cameraX=o.position.x,p.cameraY=o.position.y,c.push(p)}return c.sort((e,t)=>e.priority-t.priority),c}const _n=new Float32Array(16);function xn(e,t,s,n,i,o){const r=_n;r.fill(0);const a=t-e,l=n-s,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(n+s)/l,r[14]=-(o+i)/c,r[15]=1,r}const wn=new Float32Array(16);function vn(e,t,s,n){const i=wn;i.fill(0);const o=1/Math.tan(e/2),r=s-n;return i[0]=o/t,i[5]=o,i[10]=(n+s)/r,i[11]=-1,i[14]=2*n*s/r,i}const bn=new Float32Array(16);function Sn(e,t,s){const n=bn;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=-e,n[13]=-t,n[14]=-s,n[15]=1,n}const Pn=new Float32Array(16);function Mn(e,t){const s=Pn;for(let n=0;n<4;n++)for(let i=0;i<4;i++)s[4*i+n]=e[0+n]*t[4*i+0]+e[4+n]*t[4*i+1]+e[8+n]*t[4*i+2]+e[12+n]*t[4*i+3];return s}const Tn={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function En(e,t,s,n,i,o,r={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,u=o.left+t.x*a,d=o.bottom+e.y*l,h=o.bottom+t.y*l;let p,f,m,g;e.x===t.x?(p=c+s.x-i.x*r.x,m=p+i.x):(p=c+s.x,m=u+n.x),e.y===t.y?(f=d+s.y-i.y*r.y,g=f+i.y):(f=d+s.y,g=h+n.y);const y=Math.max(0,m-p),_=Math.max(0,g-f);return{originX:p+r.x*y,originY:f+r.y*_,width:y,height:_,rect:{left:p,bottom:f,right:m,top:g}}}const Cn=se("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});let An=null,Rn=null;function In(e,t){e.has(t,ce)||e.insert(t,ce,{texture:N,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0})}function Fn(e,t){switch(e){case Tn.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Tn.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Tn.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function kn(e,t,s,n){if(!e.has(t,Cn))return;const i=e.get(t,Cn),o=Fn(s,n);i.anchorMin=o.anchorMin,i.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(i.size={...i.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,Cn,i)}function Bn(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Dn(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Un(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),i=[];for(const t of n){if(!t){i.push("");continue}let n="";for(let o=0;o<t.length;o++){const r=t[o],a=n+r;if(e.measureText(a).width>s&&n){if(Dn(r.charCodeAt(0))&&n.length>0&&Dn(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!Dn(n.charCodeAt(t))){e=t;break}e>=0?(i.push(n.substring(0,e+1)),n=n.substring(e+1)+r):(i.push(n),n=r)}else i.push(n),n=r}else n=a}n&&i.push(n)}return i.length>0?i:[""]}function Ln(e){let t=1;for(;t<e;)t*=2;return t}function zn(e,t){let s=0,n=t;for(;e.has(n,pe);){const t=e.get(n,pe).entity;if(!e.valid(t))break;s++,n=t}return s}function Wn(e,t){if(An&&Rn){const e=An.getUIRectComputedWidth(Rn,t);if(e>0)return e}return e.size.x}function $n(e,t){if(An&&Rn){const e=An.getUIRectComputedHeight(Rn,t);if(e>0)return e}return e.size.y}function On(e,t,s){let n=t;for(;e.has(n,pe);){const t=e.get(n,pe).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function Hn(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function Nn(e,t,s,n,i){if(!e.has(t,Cn))return;const o=e.get(t,Cn),r=En(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s,o.pivot),a=r.rect.right-r.rect.left,l=r.rect.top-r.rect.bottom;if(e.has(t,ce)){const s=e.get(t,ce);s.size.x===a&&s.size.y===l||(s.size.x=a,s.size.y=l,e.insert(t,ce,s))}if(e.has(t,re)){const s=e.get(t,re);s.position.x=r.originX-n,s.position.y=r.originY-i,e.insert(t,re,s)}}function Xn(e){const t=Object.keys(e),s=t.map(t=>e[t]);return{take(e){const n={};for(let i=0;i<t.length;i++)n[t[i]]=s[i](e);return n},changed(e,n){for(let i=0;i<t.length;i++)if(e[t[i]]!==s[i](n))return!0;return!1},update(e,n){for(let i=0;i<t.length;i++)e[t[i]]=s[i](n)}}}const jn=.1,Vn=30,Yn={r:.3,g:.5,b:.8,a:1},Gn={Left:0,Center:1,Right:2},qn={Top:0,Middle:1,Bottom:2},Kn={Visible:0,Clip:1,Ellipsis:2},Jn=q("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Gn.Left,verticalAlign:qn.Top,wordWrap:!0,overflow:Kn.Visible,lineHeight:1.2});class Qn{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=l($.textCanvasSize,$.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,Ln(this.frameMaxW_)),e.height=Math.max(e.height,Ln(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Ln(this.frameMaxW_),e.height=Ln(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,o=i?t.size.x:0,r=i?t.size.y:0,a=e.wordWrap&&i;let l=Un(s,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=i?Math.ceil(o):d+2*u,f=i?Math.ceil(r):h+2*u;if(i&&e.overflow===Kn.Ellipsis&&h>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}this.frameMaxW_=Math.max(this.frameMaxW_,p),this.frameMaxH_=Math.max(this.frameMaxH_,f),(n.width<p||n.height<f)&&(n.width=Math.max(n.width,Ln(p)),n.height=Math.max(n.height,Ln(f)));const m=Math.round(255*e.color.r),g=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(${m}, ${g}, ${y}, ${_})`,i&&e.overflow===Kn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const x=l.length*c;let w;if(i){switch(e.verticalAlign){case qn.Top:w=u;break;case qn.Middle:w=u+(f-2*u-x)/2;break;case qn.Bottom:w=f-x-u;break;default:w=u}w<0&&(w=0)}else w=u;let v=w;for(const t of l){let n;switch(e.align){case Gn.Left:n=u;break;case Gn.Center:n=p/2;break;case Gn.Right:n=p-u;break;default:n=u}s.fillText(t,n,v),v+=c}i&&e.overflow===Kn.Clip&&s.restore();const b=s.getImageData(0,0,p,f),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(p,f,M,S.length,1,!0);return this.module._free(M),{textureHandle:T,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const i=this.renderText(t,s);return this.cache.set(e,i),i}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}measureWidth(e){let t=0;for(const s of e)t=Math.max(t,this.ctx.measureText(s).width);return t}mapAlign(e){switch(e){case Gn.Left:return"left";case Gn.Center:return"center";case Gn.Right:return"right"}}}const Zn=Xn({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?Wn(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?$n(e.uiRect,e.entity):0});class ei{build(e){ee("Text",Jn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Qn(t),n=e.world,i=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Jn));for(const e of i.keys())if(!n.valid(e)||!n.has(e,Jn)){if(n.valid(e)&&n.has(e,ce)){const t=n.get(e,ce);n.insert(e,ce,{texture:N,color:{r:t.color.r,g:t.color.g,b:t.color.b,a:t.color.a},size:{x:t.size.x,y:t.size.y},uvOffset:{x:t.uvOffset.x,y:t.uvOffset.y},uvScale:{x:t.uvScale.x,y:t.uvScale.y},layer:t.layer,flipX:t.flipX,flipY:t.flipY,material:t.material,enabled:t.enabled})}i.delete(e)}const e=n.getEntitiesWithComponents([Jn]);for(const t of e){const e=n.get(t,Jn),o=n.has(t,Cn)?n.get(t,Cn):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!Zn.changed(a,r)){if(n.has(t,ce)&&n.get(t,ce).texture!==N)continue}In(n,t);const l=o?{size:{x:Wn(o,t),y:$n(o,t)}}:null,c=s.renderForEntity(t,e,l),u=n.get(t,ce);n.insert(t,ce,{texture:c.textureHandle,color:{r:u.color.r,g:u.color.g,b:u.color.b,a:u.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:u.layer,flipX:u.flipX,flipY:u.flipY,material:u.material,enabled:u.enabled}),i.set(t,Zn.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const ti=new ei,si=0,ni=1,ii=se("UIMask",{enabled:!0,mode:si});function oi(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),i=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,i-s),h:Math.max(0,o-n)}}function ri(e,t){const s=t??new Float32Array(16),n=e[0],i=e[1],o=e[2],r=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],m=e[12],g=e[13],y=e[14],_=e[15],x=n*l-i*a,w=n*c-o*a,v=n*u-r*a,b=i*c-o*l,S=i*u-r*l,P=o*u-r*c,M=d*g-h*m,T=d*y-p*m,E=d*_-f*m,C=h*y-p*g,A=h*_-f*g,R=p*_-f*y;let I=x*R-w*A+v*C+b*E-S*T+P*M;return 0===I||(I=1/I,s[0]=(l*R-c*A+u*C)*I,s[1]=(o*A-i*R-r*C)*I,s[2]=(g*P-y*S+_*b)*I,s[3]=(p*S-h*P-f*b)*I,s[4]=(c*E-a*R-u*T)*I,s[5]=(n*R-o*E+r*T)*I,s[6]=(y*v-m*P-_*w)*I,s[7]=(d*P-p*v+f*w)*I,s[8]=(a*A-l*E+u*M)*I,s[9]=(i*E-n*A-r*M)*I,s[10]=(m*S-g*v+_*x)*I,s[11]=(h*v-d*S-f*x)*I,s[12]=(l*T-a*C-c*M)*I,s[13]=(n*C-i*T+o*M)*I,s[14]=(g*w-m*b-y*x)*I,s[15]=(d*b-h*w+p*x)*I),s}function ai(e,t,s,n,i,o,r){const a=(e-n)/o*2-1,l=(t-i)/r*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 li(e,t){return 2*Math.atan2(e,t)}function ci(e,t,s,n,i,o,r){const a=s[0]*e+s[4]*t+s[12],l=s[1]*e+s[5]*t+s[13],c=s[3]*e+s[7]*t+s[15];return[n+(.5*(a/c)+.5)*o,i+(.5*(l/c)+.5)*r]}function ui(e,t,s,n,i,o,r){if(!e.has(t,Cn)||!e.has(t,re))return null;const a=e.get(t,Cn),l=e.get(t,re),c=Wn(a,t)*l.worldScale.x,u=$n(a,t)*l.worldScale.y,d=l.worldPosition.x,h=l.worldPosition.y,p=a.pivot.x,f=a.pivot.y,m=-c*p,g=c*(1-p),y=-u*f,_=u*(1-f),x=li(l.worldRotation.z,l.worldRotation.w),w=Math.cos(x),v=Math.sin(x),b=[[d+m*w-y*v,h+m*v+y*w],[d+g*w-y*v,h+g*v+y*w],[d+g*w-_*v,h+g*v+_*w],[d+m*w-_*v,h+m*v+_*w]];let S=1/0,P=1/0,M=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=ci(e,t,s,n,i,o,r);S=Math.min(S,a),P=Math.min(P,l),M=Math.max(M,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(P),w:Math.round(M-S),h:Math.round(T-P)}}function di(e,t){return(s,n,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([ii]);if(0===l.length)return;const c=[],u=[],d=new Set,h=new Set;for(const e of l){const s=t.get(e,ii);s.enabled&&(d.add(e),s.mode===ni?(u.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,i,o,r,a,l,c){const u=[];for(const e of n){let s=!0;On(t,e,e=>{if(i.has(e)){if(t.get(e,ii).mode===si)return s=!1,!0}return!1}),s&&u.push(e)}function d(n,u){const h=e.getChildEntities(s,n);for(const s of h){let n=u;if(i.has(s)){if(t.get(s,ii).mode===si){const e=ui(t,s,o,r,a,l,c);e&&(n=oi(u,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=ui(t,e,o,r,a,l,c);s&&d(e,s)}}(e,t,s,c,d,n,i,o,r,a),u.length>0&&function(e,t,s,n,i){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0;On(t,e,e=>!!i.has(e)&&(s=!1,!0)),s&&o.push(e)}let r=1,a=!1;function l(){return r>255?(a||console.warn("Stencil mask overflow"),a=!0,null):r++}function c(t,n){if(a)return;e.renderer_setEntityStencilMask(t,n);const o=e.getChildEntities(s,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),u(t,n)}function u(t,n){if(a)return;const o=e.getChildEntities(s,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),u(t,n)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,s,u,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class hi{build(e){if(ee("UIMask",ii),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(di(e.wasmModule,e.world))}}const pi=new hi,fi=se("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),mi=se("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),gi={Normal:0,Hovered:1,Pressed:2,Disabled:3},yi=q("Button",{state:gi.Normal,transition:null});class _i{constructor(){this.events_=[]}emit(e,t,s){const n=s??e;this.events_.push({entity:e,type:t,target:n,currentTarget:e})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const xi=Me(new _i,"UIEvents");class wi{build(e){ee("UIRect",Cn);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){An=e,Rn=t}(s,n);e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([Te(pt)],e=>{e.valid&&(s.uiLayout_update(n,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),s.uiFlexLayout_update(n),s.transform_update(n))},{name:"UILayoutSystem"})),e.addSystemToSchedule(exports.Schedule.PostUpdate,rt([Te(pt)],e=>{e.valid&&(s.uiLayout_update(n,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),s.uiFlexLayout_update(n))},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(exports.Schedule.PostUpdate,rt([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const vi=new wi;let bi=!1,Si=!1;function Pi(){return bi}function Mi(){return Si}const Ti=function(){const e=new Float32Array(16),t=new Float32Array(16);let s=!0;return{update(e){for(let n=0;n<16;n++)if(t[n]!==e[n]){t.set(e),s=!0;break}},getInverse:t=>(s&&(ri(t,e),s=!1),e)}}();function Ei(e,t,s,n){t.emit(s,n,s),On(e,s,i=>{if(!e.has(i,fi))return!1;const o=e.get(i,fi);return o.enabled&&t.emit(i,n,s),o.blockRaycast})}class Ci{build(e){ee("Interactable",fi),ee("Button",yi);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),i=new _i;e.insertResource(xi,i);let o=null,r=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([Te(ut),Te(pt)],(e,a)=>{if(i.drain(),Pi()&&!Mi())return;const l=t.getEntitiesWithComponents([mi]);for(const e of l){const s=t.get(e,mi);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,mi,s))}if(!a.valid)return;const c=u(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;Ti.update(a.viewProjection);const p=ai(d,h,Ti.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=p.x,a.worldMouseY=p.y;const f=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),g=e.isMouseButtonReleased(0);s.uiHitTest_update(n,p.x,p.y,f,m,g);const y=s.uiHitTest_getHitEntity(),_=4294967295===y?null:y;if(null===o||t.valid(o)||(o=null),o!==_){if(null!==o&&t.valid(o)&&t.has(o,mi)){const e=t.get(o,mi);e.hovered=!1,t.insert(o,mi,e),i.emit(o,"hover_exit")}if(null!==_){Hn(t,_,mi);const e=t.get(_,mi);e.hovered=!0,t.insert(_,mi,e),i.emit(_,"hover_enter")}o=_}if(m&&null!==_){const e=t.get(_,mi);e.pressed=!0,e.justPressed=!0,t.insert(_,mi,e),r=_,Ei(t,i,_,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,mi)){const e=t.get(r,mi);e.pressed=!1,e.justReleased=!0,t.insert(r,mi,e),Ei(t,i,r,"release"),r===o&&Ei(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(exports.Schedule.Update,rt([],()=>{const e=t.getEntitiesWithComponents([yi]);for(const s of e){if(Hn(t,s,fi,{enabled:!0}),!t.has(s,mi))continue;const e=t.get(s,mi),n=t.get(s,yi),i=t.get(s,fi),o=!a.has(s),r=n.state;if(i.enabled?e.pressed?n.state=gi.Pressed:e.hovered?n.state=gi.Hovered:n.state=gi.Normal:n.state=gi.Disabled,o&&a.add(s),(o||r!==n.state)&&n.transition&&t.has(s,ce)){const o=t.get(s,ce);o.color=Bn(n.transition,i.enabled,e.pressed,e.hovered),t.insert(s,ce,o)}}},{name:"ButtonSystem"}))}}const Ai=new Ci,Ri=q("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}),Ii=q("Focusable",{tabIndex:0,isFocused:!1});class Fi{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const ki=Me(new Fi,"FocusManager");class Bi{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(ee("TextInput",Ri),Pi()&&!Mi())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,i=l($.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=0,a=0,c=!1,u=!0,d=0,h=0;const p=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(!p)return;const f=p;function m(){const t=e.getResource(ki);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,Ri)?n:null}const g=()=>{c||null===m()||v()},y=()=>{c=!0},_=()=>{c=!1,v()},x=t=>{const n=m();if(null===n)return;if("Escape"===t.key)return void b();const i=s.get(n,Ri);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(xi).emit(n,"submit"),void b()}let o=i.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?o=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=i.value.length),o!==i.cursorPos&&(i.cursorPos=o,f.selectionStart=o,f.selectionEnd=o,i.dirty=!0,S())},w=()=>{const t=m();if(null!==t){const n=s.get(t,Ri);n.focused=!1,n.dirty=!0;e.getResource(ki).blur()}};function v(){const t=m();if(null===t)return;const n=s.get(t,Ri);if(n.readOnly)return;let i=f.value;if(n.maxLength>0&&i.length>n.maxLength&&(i=i.substring(0,n.maxLength),f.value=i),i!==n.value){n.value=i;e.getResource(xi).emit(t,"change")}n.cursorPos=f.selectionStart??i.length,n.dirty=!0,S()}function b(){const t=m();if(null!==t){const e=s.get(t,Ri);e.focused=!1,e.dirty=!0}e.getResource(ki).blur(),f.blur()}function S(){u=!0,d=0}f.addEventListener("input",g),f.addEventListener("compositionstart",y),f.addEventListener("compositionend",_),f.addEventListener("keydown",x),f.addEventListener("blur",w),this.cleanupListeners_=()=>{f.removeEventListener("input",g),f.removeEventListener("compositionstart",y),f.removeEventListener("compositionend",_),f.removeEventListener("keydown",x),f.removeEventListener("blur",w),f.remove();const e=t.getResourceManager();for(const t of n.values())e.releaseTexture(t);n.clear(),0!==r&&(t._free(r),r=0,a=0)};let P=null;function M(e,l,c,d){(i.width<c||i.height<d)&&(i.width=Ln(Math.max(i.width,c)),i.height=Ln(Math.max(i.height,d))),o.clearRect(0,0,i.width,i.height);const h=l.backgroundColor;o.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,o.fillRect(0,0,c,d),o.save(),o.beginPath(),o.rect(l.padding,0,c-2*l.padding,d),o.clip(),o.font=`${l.fontSize}px ${l.fontFamily}`,o.textBaseline="top",o.textAlign="left";const p=0===l.value.length,f=p?l.placeholder:l.password?"●".repeat(l.value.length):l.value,m=p?l.placeholderColor:l.color;o.fillStyle=`rgba(${Math.round(255*m.r)}, ${Math.round(255*m.g)}, ${Math.round(255*m.b)}, ${m.a})`;const g=Math.ceil(1.2*l.fontSize),y=l.padding;if(l.multiline){const e=Un(o,f,c-2*y);let t=y;for(const s of e)o.fillText(s,y,t),t+=g}else{const e=(d-l.fontSize)/2;o.fillText(f,y,e)}if(l.focused&&u){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,s,n;if(l.multiline){const e=Un(o,l.value,c-2*y);let i=0,r=0,a=0;for(let t=0;t<e.length;t++){const s=e[t].length;if(i+s>=l.cursorPos){r=t,a=l.cursorPos-i;break}i+=s,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,r=t+1,a=0}const u=r<e.length?e[r].substring(0,a):"";t=y+o.measureText(u).width,s=y+r*g,n=g}else t=y+o.measureText(e).width,s=(d-l.fontSize)/2,n=l.fontSize;o.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,o.fillRect(t,s,2,n)}o.restore();const _=o.getImageData(0,0,c,d),x=new Uint8Array(_.data.buffer),w=t.getResourceManager();x.length>a&&(0!==r&&t._free(r),r=t._malloc(x.length),a=x.length),t.HEAPU8.set(x,r);const v=n.get(e);void 0!==v&&w.releaseTexture(v);const b=w.createTexture(c,d,r,x.length,1,!0);n.set(e,b);const S=s.get(e,ce);S.texture=b,S.size.x=c,S.size.y=d,S.uvOffset.x=0,S.uvOffset.y=0,S.uvScale.x=1,S.uvScale.y=1,S.color={r:1,g:1,b:1,a:1},s.insert(e,ce,S)}e.addSystemToSchedule(exports.Schedule.Update,rt([Te(ki)],e=>{const t=s.getEntitiesWithComponents([Ri]);for(const e of t)Hn(s,e,Ii,{tabIndex:0,isFocused:!1}),Hn(s,e,fi,{enabled:!0,blockRaycast:!0});const n=m();if(n!==P){if(null!==P&&s.valid(P)&&s.has(P,Ri)){const e=s.get(P,Ri);e.focused=!1,e.dirty=!0,f.blur()}null!==n&&function(e){const t=s.get(e,Ri);t.readOnly||(t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),S())}(n),P=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===h?0:(e-h)/1e3;h=e,i=Math.min(i,.1);const o=m();if(null!==o&&(d+=i,d>=.5)){d-=.5,u=!u;s.get(o,Ri).dirty=!0}const r=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Ri)||(r.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Ri,Cn]);for(const e of a){const t=s.get(e,Ri);if(!t.dirty)continue;const n=s.get(e,Cn),i=Math.ceil(n.size.x),o=Math.ceil(n.size.y);i<=0||o<=0||(In(s,e),M(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Di=new Bi,Ui={Simple:0,Sliced:1,Tiled:2,Filled:3},Li={Horizontal:0,Vertical:1},zi={Left:0,Right:1,Bottom:2,Top:3},Wi=q("Image",{texture:N,color:{r:1,g:1,b:1,a:1},imageType:Ui.Simple,fillMethod:Li.Horizontal,fillOrigin:zi.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),$i=Xn({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,layer:e=>e.image.layer,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?Wn(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?$n(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class Oi{build(e){ee("Image",Wi);const t=e.world,s=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,Wi)||s.delete(e);const e=t.getEntitiesWithComponents([Wi]);for(const n of e){const e=t.get(n,Wi),i=t.has(n,Cn)?t.get(n,Cn):null,o={image:e,uiRect:i,entity:n},r=s.get(n);if(r&&!$i.changed(r,o))continue;In(t,n);const a=t.get(n,ce);if(e.enabled){if(a.texture=e.texture,a.color.r=e.color.r,a.color.g=e.color.g,a.color.b=e.color.b,a.color.a=e.color.a,a.layer=e.layer,a.material=e.material,i&&(a.size.x=Wn(i,n),a.size.y=$n(i,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Ui.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===Li.Horizontal?e.fillOrigin===zi.Left?(a.uvScale.x=t,a.size.x=s*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=s*t):e.fillOrigin===zi.Bottom?(a.uvScale.y=t,a.size.y=n*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=n*t)}else e.imageType===Ui.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale.x=a.size.x/e.tileSize.x,a.uvScale.y=a.size.y/e.tileSize.y);t.insert(n,ce,a),s.set(n,$i.take(o))}else a.color.a=0,t.insert(n,ce,a),s.set(n,$i.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const Hi=new Oi,Ni=q("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Xi=q("ToggleGroup",{allowSwitchOff:!1});class ji{build(e){ee("Toggle",Ni),ee("ToggleGroup",Xi);const t=e.world,s=new Set;e.addSystemToSchedule(exports.Schedule.Update,rt([Te(xi)],e=>{const n=t.getEntitiesWithComponents([Ni]);if(!Pi()||Mi()){const i=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,Ni);n.isOn&&0!==n.group&&t.valid(n.group)&&(i.has(n.group)?(n.isOn=!1,t.insert(e,Ni,n)):i.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,Ni);if(0!==s.group&&t.valid(s.group)){let t=o.get(s.group);t||(t=[],o.set(s.group,t)),t.push(e)}}for(const s of n){if(Hn(t,s,fi,{enabled:!0}),!t.has(s,mi))continue;const n=t.get(s,mi),i=t.get(s,Ni),r=t.get(s,fi);if(n.justPressed&&r.enabled){const n=i.group,r=0!==n&&t.valid(n)&&t.has(n,Xi);if(i.isOn&&r){if(!t.get(n,Xi).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(s,Ni,i),i.isOn&&r){const i=o.get(n);if(i)for(const n of i){if(n===s)continue;const i=t.get(n,Ni);i.isOn&&(i.isOn=!1,t.insert(n,Ni,i),e.emit(n,"change"))}}e.emit(s,"change")}if(i.transition&&t.has(s,ce)){const e=t.get(s,ce);e.color=Bn(i.transition,r.enabled,n.pressed,n.hovered),t.insert(s,ce,e)}}}for(const e of n){const s=t.get(e,Ni);if(s.graphicEntity&&t.valid(s.graphicEntity)&&t.has(s.graphicEntity,ce)){const e=t.get(s.graphicEntity,ce);e.enabled=s.isOn,t.insert(s.graphicEntity,ce,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const Vi=new ji,Yi=Tn,Gi=q("ProgressBar",{value:0,fillEntity:0,direction:Tn.LeftToRight});function qi(e,t,s,n){if(!e.has(t,Cn))return;const i=e.get(t,Cn),o=s/2,r=n/2,a={left:-o,bottom:-r,right:o,top:r},l=En(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,ce)){const s=e.get(t,ce);s.size.x===l.width&&s.size.y===l.height||(s.size.x=l.width,s.size.y=l.height,e.insert(t,ce,s))}if(e.has(t,re)){const s=e.get(t,re),n=s.position;n.x===l.originX&&n.y===l.originY||(s.position={x:l.originX,y:l.originY,z:n.z},e.insert(t,re,s))}}class Ki{build(e){ee("ProgressBar",Gi);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([],()=>{const e=t.getEntitiesWithComponents([Gi,Cn]);for(const s of e){const e=t.get(s,Gi);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,Cn),i=Math.max(0,Math.min(1,e.value));kn(t,e.fillEntity,e.direction,i);const o=Wn(n,s),r=$n(n,s);qi(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Ji=new Ki,Qi=q("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Zi=q("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});class eo{build(e){ee("Draggable",Qi),ee("DragState",Zi);const t=e.world,s=e.getResource(xi);let n=null,i={x:0,y:0},o=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([Te(ut),Te(pt)],(e,r)=>{if(Pi()&&!Mi())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Qi,mi]);let s=null,o=-1/0,r=-1;for(const n of e){if(!t.get(n,Qi).enabled)continue;if(t.get(n,mi).hovered){let e=0;t.has(n,ce)&&(e=t.get(n,ce).layer);const i=zn(t,n);(e>o||e===o&&i>=r)&&(o=e,r=i,s=n)}}if(null!==s){n=s,i={x:a.x,y:a.y},t.has(s,Zi)||t.insert(s,Zi);const e=t.get(s,Zi),o=t.get(s,re);e.startWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.currentWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==n&&!e.isMouseButtonDown(0)){if(t.valid(n)&&t.has(n,Zi)){t.get(n,Zi).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),u=t.get(n,Qi);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=n,n=null;t.get(o,Zi).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Zi))return void(o=null);const n=t.get(o,Zi),i=t.get(o,Qi),r=a.x-n.pointerStartWorld.x,l=a.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+r,u=n.startWorldPos.y+l;const d=function(e,t,s,n){let i=e.lockX?t.startWorldPos.x:s,o=e.lockY?t.startWorldPos.y:n;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:i,y:o}}(i,n,c,u);c=d.x,u=d.y;const h=n.currentWorldPos.x,p=n.currentWorldPos.y;if(n.deltaWorld={x:c-h,y:u-p},n.currentWorldPos={x:c,y:u},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:u-n.startWorldPos.y},t.has(o,re)){const e=function(e,t,s,n){if(!e.has(t,pe))return{x:s,y:n};const i=e.get(t,pe).entity;if(!e.valid(i)||!e.has(i,re))return{x:s,y:n};const o=e.get(i,re),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=li(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(s*u-n*c)/r,y:(s*c+n*u)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,re);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,re,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}}const to=new eo,so=q("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function no(e,t,s,n){return n<=0?1:e<t?Math.max(0,1-(t-e)/n):e>s?Math.max(0,1-(e-s)/n):1}function io(e,t,s,n,i){const o=2/(n=Math.max(1e-4,n)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(s+o*l)*i,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(s-o*c)*a}}class oo{build(e){ee("ScrollView",so);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(exports.Schedule.PostUpdate,rt([Te(ut),Te(pt),Te(Re)],(e,i,o)=>{const r=Pi()&&!Mi(),a=Math.min(o.delta,.05);for(const[e]of s)t.valid(e)||s.delete(e);i.valid&&(n.x=i.worldMouseX,n.y=i.worldMouseY);const l=t.getEntitiesWithComponents([so,Cn]);for(const o of l){Hn(t,o,ii,{enabled:!0,mode:si});const l=t.get(o,so),c=t.get(o,Cn);let u=s.get(o);u||(u={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},s.set(o,u));const d=Wn(c,o),h=$n(c,o);let p=l.contentWidth,f=l.contentHeight;if((0===p||0===f)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,fe)){const e=t.get(l.contentEntity,fe).entities;let s=0,n=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,re))continue;const e=t.get(r,re);let a=0,l=0,c=.5,u=.5;if(t.has(r,Cn)){const e=t.get(r,Cn);a=Wn(e,r)||e.size.x,l=$n(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,ce)){const e=t.get(r,ce);a=e.size.x,l=e.size.y}const d=e.position.x-a*c,h=e.position.x+a*(1-c),p=e.position.y-l*u,f=e.position.y+l*(1-u);d<s&&(s=d),h>n&&(n=h),p<i&&(i=p),f>o&&(o=f)}0===p&&(p=n-s),0===f&&(f=o-i)}const m=Math.max(0,p-d),g=Math.max(0,f-h);if(!r&&i.valid){Hn(t,o,fi,{enabled:!0,blockRaycast:!0});const s=t.has(o,mi)?t.get(o,mi):null;if(s?.justPressed&&(u.isDragging=!0,u.lastWorldX=n.x,u.lastWorldY=n.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=n.x-u.lastWorldX,t=n.y-u.lastWorldY,s=Math.min(1,10*a);if(l.horizontalEnabled){const t=no(l.scrollX,0,m,d);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const n=a>0?-e*t/a:0;u.velocityX+=(n-u.velocityX)*s}}if(l.verticalEnabled){const e=no(l.scrollY,0,g,h);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const n=a>0?t*e/a:0;u.velocityY+=(n-u.velocityY)*s}}u.lastWorldX=n.x,u.lastWorldY=n.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*d,t=5*h;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(s?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=no(l.scrollY,0,g,h);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=no(l.scrollX,0,m,d);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>g;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=io(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<jn&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>jn?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:g,t=io(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<jn&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>jn?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,m)),l.scrollY=Math.max(0,Math.min(l.scrollY,g)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*d,t=.5*h;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,g+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,re)){const e=t.get(l.contentEntity,re),s=e.position.x,n=e.position.y;(isNaN(u.lastAppliedX)||Math.abs(s-u.lastAppliedX)>.01)&&(u.contentBaseX=s),(isNaN(u.lastAppliedY)||Math.abs(n-u.lastAppliedY)>.01)&&(u.contentBaseY=n),e.position.x=u.contentBaseX-l.scrollX,e.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=e.position.x,u.lastAppliedY=e.position.y,t.insert(l.contentEntity,re,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const ro=new oo,ao=Tn,lo=q("Slider",{value:0,minValue:0,maxValue:1,direction:Tn.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function co(e,t,s,n,i,o){const r=Wn(n,i)*s.worldScale.x,a=$n(n,i)*s.worldScale.y,l=li(s.worldRotation.z,s.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),d=e-s.worldPosition.x,h=t-s.worldPosition.y,p=d*u-h*c,f=d*c+h*u,m=-n.pivot.x*r,g=-n.pivot.y*a;switch(o){case Tn.LeftToRight:return r>0?(p-m)/r:0;case Tn.RightToLeft:return r>0?1-(p-m)/r:0;case Tn.BottomToTop:return a>0?(f-g)/a:0;case Tn.TopToBottom:return a>0?1-(f-g)/a:0}}function uo(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case Tn.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case Tn.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case Tn.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case Tn.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class ho{build(e){ee("Slider",lo);const t=e.world;let s=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([Te(ut),Te(pt),Te(xi)],(e,n,i)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([lo,Cn]);for(const r of o){const o=t.get(r,lo),a=t.get(r,Cn);if(!Pi()||Mi()){if(t.has(r,re)){Hn(t,r,fi,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Hn(t,o.handleEntity,fi,{enabled:!0,blockRaycast:!1});const l=t.get(r,re),c=t.has(r,mi)?t.get(r,mi):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,mi)&&(u=t.get(o.handleEntity,mi).justPressed),u&&(s=r),s===r&&e.isMouseButtonDown(0)){let e=co(n.worldMouseX,n.worldMouseY,l,a,r,o.direction);e=Math.max(0,Math.min(1,e));let s=o.minValue+e*(o.maxValue-o.minValue);o.wholeNumbers&&(s=Math.round(s));const c=o.value;o.value=Math.max(o.minValue,Math.min(o.maxValue,s)),t.insert(r,lo,o),o.value!==c&&i.emit(r,"change")}s===r&&e.isMouseButtonReleased(0)&&(s=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,u=Wn(a,r),d=$n(a,r),h={left:-u/2,bottom:-d/2,right:u/2,top:d/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(kn(t,o.fillEntity,o.direction,c),Nn(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Cn)){const e=t.get(o.handleEntity,Cn);uo(e,o.direction,c),t.insert(o.handleEntity,Cn,e),Nn(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const po=new ho;class fo{build(e){ee("Focusable",Ii);const t=e.world,s=new Fi;e.insertResource(ki,s),e.addSystemToSchedule(exports.Schedule.Update,rt([Te(ut),Te(xi)],(e,n)=>{if(Pi()&&!Mi())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const i=t.getEntitiesWithComponents([Ii]);for(const e of i){if(!t.has(e,mi))continue;t.get(e,mi).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const n=function(){const e=[];for(const s of i){if(!t.valid(s))continue;if(t.has(s,fi)){if(!t.get(s,fi).enabled)continue}const n=t.get(s,Ii);e.push({entity:s,tabIndex:n.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===n.length)return;const r=null!==s.focusedEntity?n.findIndex(e=>e===s.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?n.length-1:0:a?(r-1+n.length)%n.length:(r+1)%n.length,o(n[l])}function o(e){const i=s.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Ii)){t.get(i,Ii).isFocused=!1,n.emit(i,"blur",i)}s.focus(e);t.get(e,Ii).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const mo=new fo,go=q("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function yo(){return s()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:s,screenWidth:n,screenHeight:i}=t;return{top:s.top,bottom:i-s.bottom,left:s.left,right:n-s.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}class _o{build(e){ee("SafeArea",go);const t=e.world;let n=yo(),i=!0,o=0,r=0;if(s()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=yo(),i=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=yo(),i=!0});e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([Te(pt)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===r||(o=e.screenH,r=a,i=!0),!i)return;i=!1;const l=u(),c=s()?a/e.screenH:l*a/e.screenH,d=t.getEntitiesWithComponents([go,Cn]);for(const e of d){const s=t.get(e,go),i=t.get(e,Cn),o=s.applyTop?n.top*c:0,r=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let u=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},u=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,Cn,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const xo=new _o,wo=q("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let vo=null;class bo{build(e){ee("ListView",wo);const t=e.world,s=new Map;vo=s,e.addSystemToSchedule(exports.Schedule.PostUpdate,rt([Te(ut)],e=>{const n=Pi()&&!Mi();for(const[e,n]of s)if(!t.valid(e)){for(const e of n.itemEntities.values())t.valid(e)&&t.despawn(e);s.delete(e)}const i=t.getEntitiesWithComponents([wo,Cn]);for(const o of i){Hn(t,o,fi,{enabled:!0,blockRaycast:!0}),Hn(t,o,ii,{enabled:!0,mode:si});let i=s.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},s.set(o,i));const r=t.get(o,wo),a=t.get(o,Cn),l=$n(a,o),c=Wn(a,o);if(!n){const s=t.has(o,mi)?t.get(o,mi):null;if(s?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const u=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,u));const d=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),h=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,s]of i.itemEntities)(e<d||e>=h)&&(t.valid(s)&&t.despawn(s),i.itemEntities.delete(e));for(let e=d;e<h;e++){let s=i.itemEntities.get(e);if(s&&t.valid(s)||(s=t.spawn(),t.insert(s,ye,{value:`ListItem_${e}`}),t.insert(s,Cn,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(s,o),i.itemEntities.set(e,s),i.renderer&&i.renderer(e,s)),t.has(s,re)){const n=t.get(s,re);n.position.y=-(e*r.itemHeight-r.scrollY),t.insert(s,re,n)}}i.visibleStart=d,i.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const So=new bo,Po=q("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class Mo{build(e){ee("Dropdown",Po);const t=e.world,s=new Map;function n(e){if(0===e||!t.valid(e))return;if(!t.has(e,re))return;const s=t.get(e,re);0===s.scale.x&&0===s.scale.y&&0===s.scale.z&&t.insert(e,re,{position:{x:s.position.x,y:s.position.y,z:s.position.z},rotation:{x:s.rotation.x,y:s.rotation.y,z:s.rotation.z,w:s.rotation.w},scale:{x:1,y:1,z:1}})}function i(e){if(t.has(e,ce)){const s=t.get(e,ce);1===s.color.r&&1===s.color.g&&1===s.color.b&&1===s.color.a&&t.insert(e,ce,{texture:s.texture,color:{r:.9,g:.9,b:.9,a:1},size:{x:s.size.x,y:s.size.y},uvOffset:{x:s.uvOffset.x,y:s.uvOffset.y},uvScale:{x:s.uvScale.x,y:s.uvScale.y},layer:s.layer,flipX:s.flipX,flipY:s.flipY,material:s.material,enabled:s.enabled})}}function o(e,s,n){s.isOpen=!0,n.highlightIndex=s.selectedIndex;const i=s.listEntity;if(0===i||!t.valid(i))return;u(i,!0),c(n);const o=t.get(e,ce),r=o.size.x,a=o.size.y;n.ddWidth=r;const l=s.options.length*Vn;t.insert(i,Cn,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:l},pivot:{x:.5,y:.5}}),t.insert(i,re,{position:{x:0,y:-(a+l)/2,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(i,ce,{texture:N,color:{r:1,g:1,b:1,a:1},size:{x:r,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<s.options.length;e++){const o=t.spawn(),a=l/2-(e+.5)*Vn;t.insert(o,ye,{value:`Option_${e}`}),t.insert(o,Cn,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Vn},offsetMax:{x:0,y:0},size:{x:r,y:Vn},pivot:{x:.5,y:.5}}),t.insert(o,re,{position:{x:0,y:a,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(o,ce,{texture:N,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:Vn},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,fi,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),n.optionEntities.push(o);const c=t.spawn();t.insert(c,re,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(c,Jn,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Gn.Left,verticalAlign:qn.Middle,wordWrap:!1,overflow:Kn.Clip,lineHeight:1.2}),t.insert(c,Cn,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:Vn},pivot:{x:.5,y:.5}}),t.setParent(c,o),n.textEntities.push(c)}d(n)}function r(e,t,s){t.isOpen=!1,c(s),u(t.listEntity,!1)}function a(e,t,s,n,i){t.selectedIndex=n,r(0,t,s),i.emit(e,"change")}function l(e){const s=e.labelEntity;if(0===s||!t.valid(s))return;if(!t.has(s,Jn))return;const n=t.get(s,Jn);let i={r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},o=n.content,r=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},r=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,r=!0)}r&&t.insert(s,Jn,{content:o,fontSize:n.fontSize,fontFamily:n.fontFamily,color:i,align:n.align,verticalAlign:n.verticalAlign,wordWrap:n.wordWrap,overflow:n.overflow,lineHeight:n.lineHeight})}function c(e){for(const s of e.textEntities)t.valid(s)&&t.despawn(s);for(const s of e.optionEntities)t.valid(s)&&t.despawn(s);e.optionEntities=[],e.textEntities=[]}function u(e,s){if(0!==e&&t.valid(e)&&(t.has(e,fi)&&t.insert(e,fi,{enabled:s,blockRaycast:!0,raycastTarget:!0}),t.has(e,ce))){const n=t.get(e,ce);t.insert(e,ce,{texture:n.texture,color:{r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:s})}}function d(e){for(let s=0;s<e.optionEntities.length;s++){const n=e.optionEntities[s];if(!t.valid(n)||!t.has(n,ce))continue;const i=s===e.highlightIndex?{...Yn}:{r:.95,g:.95,b:.95,a:1};t.insert(n,ce,{texture:N,color:i,size:{x:e.ddWidth,y:Vn},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function h(e){for(const s of e.optionEntities){if(!t.valid(s)||!t.has(s,mi))continue;if(t.get(s,mi).hovered)return!0}return!1}e.addSystemToSchedule(exports.Schedule.Update,rt([Te(ut),Te(xi)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const p=Pi()&&!Mi(),f=t.getEntitiesWithComponents([Po]);for(const m of f){const f=t.get(m,Po);let g=s.get(m);if(g||(g={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},s.set(m,g)),n(f.listEntity),i(m),f.isOpen||u(f.listEntity,!1),l(f),p)continue;Hn(t,m,fi,{enabled:!0,blockRaycast:!0});const y=t.has(m,mi)?t.get(m,mi):null;if(y?.justPressed&&(f.isOpen?r(m,f,g):o(m,f,g)),f.isOpen){for(let e=0;e<g.optionEntities.length;e++){const s=g.optionEntities[e];if(!t.valid(s)||!t.has(s,mi))continue;if(t.get(s,mi).justPressed){a(m,f,g,e,c);break}}let s=-1;for(let e=0;e<g.optionEntities.length;e++){const n=g.optionEntities[e];if(!t.valid(n)||!t.has(n,mi))continue;if(t.get(n,mi).hovered){s=e;break}}s>=0&&s!==g.highlightIndex&&(g.highlightIndex=s,d(g)),e.isKeyPressed("ArrowDown")?(g.highlightIndex>=f.options.length-1?g.highlightIndex=0:g.highlightIndex++,d(g)):e.isKeyPressed("ArrowUp")?(g.highlightIndex<=0?g.highlightIndex=f.options.length-1:g.highlightIndex--,d(g)):e.isKeyPressed("Enter")&&g.highlightIndex>=0?a(m,f,g,g.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,f,g),e.isMouseButtonPressed(0)&&(y?.hovered||h(g)||r(m,f,g))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}}const To=new Mo,Eo=0,Co=0,Ao=2,Ro=q("LayoutGroup",{direction:Eo,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Co,reverseOrder:!1});class Io{build(e){ee("LayoutGroup",Ro);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([],()=>{const e=t.getEntitiesWithComponents([Ro,Cn,fe]);for(const s of e){const e=t.get(s,Ro),n=t.get(s,Cn),i=t.get(s,fe);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,Cn)&&t.has(e,re)&&o.push({entity:e,rect:t.get(e,Cn)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=Wn(n,s),a=$n(n,s),l=n.pivot.x,c=n.pivot.y,u=e.padding,d=e.direction===Eo;let h=0;for(let s=0;s<o.length;s++){const n=o[s],i=Wn(n.rect,n.entity),p=$n(n.rect,n.entity),f=n.rect.pivot.x,m=n.rect.pivot.y;let g,y;d?(g=-l*r+u.left+h+f*i,y=e.childAlignment===Co?(1-c)*a-u.top-(1-m)*p:e.childAlignment===Ao?-c*a+u.bottom+m*p:(.5-c)*a+.5*(u.bottom-u.top)+(m-.5)*p,h+=i,s<o.length-1&&(h+=e.spacing)):(g=e.childAlignment===Co?-l*r+u.left+f*i:e.childAlignment===Ao?(1-l)*r-u.right-(1-f)*i:(.5-l)*r+.5*(u.left-u.right)+(f-.5)*i,y=(1-c)*a-u.top-h-(1-m)*p,h+=p,s<o.length-1&&(h+=e.spacing));const _=t.get(n.entity,re);_.position.x=g,_.position.y=y,t.insert(n.entity,re,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}}const Fo=new Io;class ko{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(exports.Schedule.PostUpdate,rt([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const Bo=new ko;async function Do(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 Uo=Me({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Lo=Me(null,"PhysicsAPI");function zo(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Wo(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class $o{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(Uo,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Do(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const i=function(e){const t=e.world.getEntitiesWithComponents([de]);for(const s of t){const t=e.world.get(s,de);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/i,r=e.world;r.onDespawn(e=>{t.has(e)&&(n._physics_destroyBody(e),t.delete(e),s.delete(e))}),e.addSystemToSchedule(exports.Schedule.PostUpdate,rt([Te(Re)],a=>{const l=r.getEntitiesWithComponents([xe,re]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,xe),l=r.get(i,re);if(t.has(i)){const e=s.get(i);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(i,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const r=zo(l.worldRotation);n._physics_createBody(i,a.bodyType,l.worldPosition.x*o,l.worldPosition.y*o,r,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Oo(e,n,i),t.add(i),s.set(i,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===Se.Kinematic){const e=zo(l.worldRotation);n._physics_setBodyTransform(i,l.worldPosition.x*o,l.worldPosition.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 i=t._physics_getDynamicBodyTransforms(),o=i>>2;for(let i=0;i<n;i++){const n=o+4*i,r=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(r))continue;const u=e.world.get(r,re);if(!u)continue;let d=a,h=l,p=c;if(e.world.has(r,pe)){const t=e.world.get(r,pe);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,re)){const s=e.world.get(t.entity,re),n=zo(s.worldRotation),i=a-s.worldPosition.x,o=l-s.worldPosition.y,r=Math.cos(-n),u=Math.sin(-n);d=(i*r-o*u)/(0!==s.worldScale.x?s.worldScale.x:1),h=(i*u+o*r)/(0!==s.worldScale.y?s.worldScale.y:1),p=c-n}}u.position.x=d,u.position.y=h;const f=Wo(p);u.rotation.w=f.w,u.rotation.x=f.x,u.rotation.y=f.y,u.rotation.z=f.z,e.world.insert(r,re,u)}}(e,n,i),function(e,t,s){t._physics_collectEvents();const n=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<i;o++){const i=e+6*o;n.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*s,contactY:t.HEAPF32[i+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 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(Uo,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,i)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Lo,Ho._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function Oo(e,t,s){const n=e.world;if(n.has(s,we)){const e=n.get(s,we);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,ve)){const e=n.get(s,ve);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,be)){const e=n.get(s,be);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 Ho{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(Ho.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}const No={nearest:0,linear:1},Xo={repeat:0,clamp:1,mirror:2};function jo(e,t,s=!0,n){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),n&&(n.filterMode||n.wrapMode)&&i.createTextureEx){const e=No[n.filterMode??"linear"]??1,a=Xo[n.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,s,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,s);return e._free(o),r}function Vo(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 Yo(e,t,s,n){const i=e.worldScale.x*t*(s?-1:1),o=e.worldScale.y*t*(n?-1:1),r=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,u=e.worldRotation.w,d=a+a,h=l+l,p=c+c,f=a*d,m=a*h,g=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))*i,(m+b)*i,(g-v)*i,0,(m-b)*o,(1-(f+x))*o,(_+w)*o,0,(g+v)*r,(_-w)*r,(1-(f+y))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function Go(e){const{app:t,module:s,sceneData:n,provider:i,spineModule:o,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,u=await async function(e,t,s){const n={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=Nt(t.type);for(const r of o){if("texture"!==r.type)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===n[o])try{const t=i?.[o];n[o]=jo(e,await s.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),n[o]=0}}}return n}(s,n,i);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const i=s[e];if(i&&i>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(s,n,u);let d={},h=null;if(o&&(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"])}}(o),d=await async function(e,t,s,n,i){const o={};for(const r of n.entities)for(const n of r.components){const r=Xt(n.type);if(!r||!n.data)continue;const a=n.data[r.skeletonField],l=n.data[r.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),u=i.resolvePath(l);try{const n=await i.readText(l),r="binary"===v(c)?.contentType;let d,h;if(r){const e=await i.readBinary(a);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await i.readText(a),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,r);if(t._free(d),p<0)continue;o[a]=p;const f=Vo(n),m=u.substring(0,u.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=m+"/"+f[t];try{const o=i.loadPixelsRaw?await i.loadPixelsRaw(n):await i.loadPixels(n),r=jo(e,o,!1),a=e.getResourceManager().getTextureGLId(r);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(s,o,h,n,i)),r){const e={gravity:a?.gravity??{...z},fixedTimestep:a?.fixedTimestep??W,subStepCount:a?.subStepCount??4};new $o("",e,()=>Promise.resolve(r)).build(t)}const p=await async function(e,t,s){const n={};for(const i of t.entities)for(const t of i.components){const i=Nt(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{let t,i;const r=v(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await s.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){n[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await s.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),u=jo(e,c,!1),d=e.getResourceManager();n[o]=d.loadBitmapFont(t,u,c.width,c.height)}catch{n[o]=0}}return n}(s,n,i),f=await async function(e,t){const s={},n={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Nt(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){s[o]=0;continue}const i=e.vertexSource+e.fragmentSource;let r=n[i];r||(r=St.createShader(e.vertexSource,e.fragmentSource),n[i]=r),s[o]=St.createFromAsset(e,r)}catch{s[o]=0}}return s}(n,i);await async function(e,t,s){const n=new Set;for(const i of t.entities)for(const t of i.components){const i=Nt(t.type);for(const o of i){if("anim-clip"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!n.has(i)){n.add(i);try{const t=await s.readText(i),n=JSON.parse(t),o=Bt(n),r=new Map;for(const t of o)try{const n=await s.loadPixels(t);r.set(t,jo(e,n))}catch{r.set(t,0)}Lt(Dt(i,n,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(s,n,i),await async function(e){const t=[],s=new Set;for(const n of e.entities)for(const e of n.components){const n=Nt(e.type);for(const i of n){if("audio"!==i.type)continue;const n=e.data[i.field];"string"==typeof n&&n&&!s.has(n)&&(s.add(n),t.push(n))}}t.length>0&&await $t.preloadAll(t).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)})}(n),function(e,t,s,n){const i={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=Nt(e.type);if(0===t.length)continue;const s=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof s[e.field]&&(s[e.field]=t[s[e.field]]||0)}}}(n,u,p,f);const m=qt(t.world,n);if(c&&t.hasResource(an))for(const e of m.values())t.world.insert(e,_e,{scene:c,persistent:!1});if(o&&h){const e=function(e,t,s,n){const i={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const r=Xt(t.type);if(!r||!t.data)continue;const a=s[t.data[r.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=n.get(o.id);void 0!==c&&(i[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return i}(h,n,d,m);!function(e,t,s,n,i){let o=0;e.setSpineRenderer((r,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=L);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,ge)?c.get(o,ge):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(r,l*d);let h=0;if(c.has(o,re)){const e=Yo(c.get(o,re),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=n.getMeshBatchCount(r);for(let e=0;e<p;e++){const i=n.getMeshBatchVertexCount(r,e),o=n.getMeshBatchIndexCount(r,e);if(!i||!o)continue;const a=8*i*4,l=2*o,c=s._malloc(a),u=s._malloc(l),d=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(r,e,c,u,d,p);const f=s.HEAPU32[d>>2],m=s.HEAPU32[p>>2],g=new Float32Array(s.HEAPF32.buffer,c,8*i),y=new Uint16Array(s.HEAPU8.buffer,u,o),_=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(g,_>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(y),t.renderer_submitTriangles(_,i,x,o,f,m,h),t._free(_),t._free(x),s._free(c),s._free(u),s._free(d),s._free(p)}h&&t._free(h)}})}(t,s,o,h,e)}if(l){const e=t.getResource(ts);e&&e.setAddressableManifest(l)}}function qo(e,t,s){return{name:e,async setup(){await Go({...s,sceneData:t,sceneName:e})}}}async function Ko(e){const{app:t,firstScene:s,aspectRatio:n}=e;hn(t);const i={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},o=t.getResource(an);for(const t of e.scenes)o.register(qo(t.name,t.data,i));s&&(o.setInitial(s),await o.load(s)),void 0!==n&&Zt(t.world,n)}class Jo{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 i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Xt(e.type);if(i){const n=e.data[i.skeletonField],o=e.data[i.atlasField];n&&("binary"===v(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=Nt(e.type);for(const s of o){const i=e.data[s.field];"string"==typeof i&&i&&("font"===s.type?(n.add(i),t.add(i)):("material"===s.type||"anim-clip"===s.type)&&t.add(i))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const o=[];for(const e of n){const t=v(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(),i=await createImageBitmap(n),o=new OffscreenCanvas(i.width,i.height).getContext("2d");o.drawImage(i,0,0);const r=o.getImageData(0,0,i.width,i.height);return i.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Qo="__preview__";const Zo={create(e){const t=e.depth??!0,s="linear"===e.filter,n=(t?1:0)|(s?2:0),i=Ks.createRenderTarget(e.width,e.height,n);return{_handle:i,textureId:Ks.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:s?"linear":"nearest"}},release(e){Ks.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Ks.releaseRenderTarget(e._handle),Zo.create({width:t,height:s,depth:e._depth,filter:e._filter})),begin(e,t){Ks.begin(t,e._handle)},end(){Ks.end()},getDepthTexture:e=>Ks.getTargetDepthTexture(e._handle)};var er;exports.LogLevel=void 0,(er=exports.LogLevel||(exports.LogLevel={}))[er.Debug=0]="Debug",er[er.Info=1]="Info",er[er.Warn=2]="Warn",er[er.Error=3]="Error";class tr{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 sr{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new tr)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,s){this.log(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 i={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const nr=new sr;const ir={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},or={Running:0,Paused:1,Completed:2,Cancelled:3},rr={None:0,Restart:1,PingPong:2};const ar=1.70158,lr=2.70158,cr=2.5949095;const ur=2*Math.PI/3,dr=2*Math.PI/4.5;const hr=7.5625,pr=2.75;const fr=1e-6;function mr(e,t,s){switch(e){case ir.Linear:return t;case ir.EaseInQuad:return function(e){return e*e}(t);case ir.EaseOutQuad:return function(e){return e*(2-e)}(t);case ir.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case ir.EaseInCubic:return function(e){return e*e*e}(t);case ir.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case ir.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case ir.EaseInBack:return function(e){return lr*e*e*e-ar*e*e}(t);case ir.EaseOutBack:return function(e){const t=e-1;return 1+lr*t*t*t+ar*t*t}(t);case ir.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-cr)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+cr)+2)/2}(t);case ir.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*ur)}(t);case ir.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*ur)+1}(t);case ir.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*dr)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*dr)/2+1}(t);case ir.EaseOutBounce:return function(e){return e<1/pr?hr*e*e:e<2/pr?hr*(e-=1.5/pr)*e+.75:e<2.5/pr?hr*(e-=2.25/pr)*e+.9375:hr*(e-=2.625/pr)*e+.984375}(t);case ir.CubicBezier:return s?function(e,t,s,n,i){let o=e;for(let s=0;s<8;s++){const s=1-o,i=3*t*s*s*o+3*n*s*o*o+o*o*o-e;if(Math.abs(i)<fr)break;const r=3*t*(1-2*o)*(1-o)+6*n*o*(1-o)-3*n*o*o+3*o*o;if(Math.abs(r)<fr)break;o-=i/r}const r=1-o;return 3*s*r*r*o+3*i*r*o*o+o*o*o}(t,s.p1x,s.p1y,s.p2x,s.p2y):t;case ir.Step:return function(e){return e<1?0:1}(t);default:return t}}const gr=new class{constructor(){this.entries_=new Map,this.nextId_=1,this.cppSequences_=new Map,this.module_=null,this.registry_=null}init(e,t){this.module_=e,this.registry_=t}create(e,t,s,n,i){const o=this.nextId_++;return this.entries_.set(o,{id:o,from:e,to:t,duration:s,elapsed:0,delay:i?.delay??0,easing:i?.easing??ir.Linear,bezierPoints:null,state:or.Running,loop:i?.loop??rr.None,loopCount:i?.loopCount??0,loopsRemaining:i?.loopCount??0,callback:n,sequenceNext:null,sequenceNextExternal:null}),o}update(e){if(this.module_&&this.registry_)for(const[e,t]of this.cppSequences_){this.module_._anim_getTweenState(this.registry_,e)===or.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==or.Running)continue;if(t.delay>0){if(t.delay-=e,t.delay>0)continue;e=-t.delay,t.delay=0}t.elapsed+=e;const s=Math.min(t.elapsed/t.duration,1),n=mr(t.easing,s,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*n),s>=1){if(t.loop!==rr.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===rr.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=or.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===or.Running&&(t.state=or.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===or.Paused&&(t.state=or.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=or.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:or.Cancelled}setBezier(e,t,s,n,i){const o=this.entries_.get(e);o&&(o.bezierPoints={p1x:t,p1y:s,p2x:n,p2y:i})}setSequenceNext(e,t){const s=this.entries_.get(e);s&&(s.sequenceNext=t,this.pause(t))}setSequenceNextExternal(e,t){const s=this.entries_.get(e);s&&(s.sequenceNextExternal=t,t.pause())}registerCppSequence(e,t){this.cppSequences_.set(e,t),this.pause(t)}shutdown(){this.entries_.clear(),this.cppSequences_.clear(),this.module_=null,this.registry_=null,this.nextId_=1}};class yr{constructor(e){this.id=e}get state(){return gr.getState(this.id)}bezier(e,t,s,n){return gr.setBezier(this.id,e,t,s,n),this}then(e){return e instanceof yr?gr.setSequenceNext(this.id,e.id):gr.setSequenceNextExternal(this.id,e),this}pause(){gr.pause(this.id)}resume(){gr.resume(this.id)}cancel(){gr.cancel(this.id)}}class _r{constructor(e,t,s){this.module_=e,this.registry_=t,this.entity=s}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,s,n){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,s,n),this}then(e){return e instanceof yr?(gr.registerCppSequence(this.entity,e.id),this):(this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this)}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let xr=null,wr=null;function vr(e,t){xr=e,wr=t,gr.init(e,t)}function br(){gr.shutdown(),xr=null,wr=null}function Sr(){if(!xr)throw new Error("Tween API not initialized");return xr}function Pr(){if(!wr)throw new Error("Tween API not initialized");return wr}const Mr={to(e,t,s,n,i,o){const r=Sr(),a=Pr(),l=o?.easing??ir.Linear,c=o?.delay??0,u=o?.loop??rr.None,d=o?.loopCount??0,h=r._anim_createTween(a,e,t,s,n,i,l,c,u,d);return new _r(r,a,h)},value(e,t,s,n,i){const o=gr.create(e,t,s,n,i);return new yr(o)},cancel(e){Sr()._anim_cancelTween(Pr(),e.entity)},cancelAll(e){Sr()._anim_cancelAllTweens(Pr(),e)},update(e){Sr()._anim_updateTweens(Pr(),e),gr.update(e)}};class Tr{constructor(){this.name="AnimationPlugin"}build(e){vr(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(exports.Schedule.Update,rt([Te(Re)],e=>{Mr.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(exports.Schedule.Update,rt([Te(Re)],e=>{Wt(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){br()}}const Er=new Tr;var Cr;exports.AttenuationModel=void 0,(Cr=exports.AttenuationModel||(exports.AttenuationModel={}))[Cr.Linear=0]="Linear",Cr[Cr.Inverse=1]="Inverse",Cr[Cr.Exponential=2]="Exponential";const Ar={model:exports.AttenuationModel.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function Rr(e,t=Ar){const{model:s,refDistance:n,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(s){case exports.AttenuationModel.Linear:{const e=i-n;if(e<=0)return 1;a=1-(Math.min(Math.max(r,n),i)-n)/e;break}case exports.AttenuationModel.Inverse:a=n/Math.max(r,n);break;case exports.AttenuationModel.Exponential:a=Math.pow(Math.max(r,n)/n,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function Ir(e,t,s,n,i){const o=e-s;return Math.max(-1,Math.min(1,o/i))}const Fr=q("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:exports.AttenuationModel.Inverse,rolloff:1,priority:0,enabled:!0}),kr=q("AudioListener",{enabled:!0});class Br{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const s=t().createAudioBackend(),n=this.config_;s.initialize({initialPoolSize:n.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const i=s.mixer;$t.init(s,i),i&&(void 0!==n.masterVolume&&(i.master.volume=n.masterVolume),void 0!==n.musicVolume&&(i.music.volume=n.musicVolume),void 0!==n.sfxVolume&&(i.sfx.volume=n.sfxVolume));const o=new Map;this.activeSourceHandles_=o;const r=new Set;this.playedEntities_=r;const a=new Set;let l=!1,c=!1;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([Te(Re)],t=>{if(!(!Pi()||Mi()))return void(c&&(l=!1,c=!1));c=!0;const n=e.world;let i=0,u=0,d=!1;const h=n.getEntitiesWithComponents([kr,le]);for(const e of h){if(n.get(e,kr).enabled){const t=n.get(e,le);i=t.position.x,u=t.position.y,d=!0;break}}const p=n.getEntitiesWithComponents([Fr]);a.clear();for(const e of p){const t=n.get(e,Fr);if(!t.enabled||!t.clip)continue;const c=e;if(a.add(c),t.playOnAwake&&!r.has(c)&&!o.has(c)&&s.isReady){const e=$t.getBufferHandle(t.clip);if(e){const n=s.play(e,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});o.set(c,n),r.add(c)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(c)){const s=o.get(c);if(!s.isPlaying){o.delete(c);continue}d||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=n.tryGet?.(e,le),a=r?.position.x??0,h=r?.position.y??0,p=a-i,f=h-u,m=Rr(Math.sqrt(p*p+f*f),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=Ir(a,0,i,0,t.maxDistance);s.setVolume(t.volume*m),s.setPan(g)}}for(const[e,t]of o)a.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),$t.dispose()}}const Dr=new Br;function Ur(e,t){return e.toFixed(t)}function Lr(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}class zr{constructor(e,t="bottom-left"){this.visible_=!0,this.disposed_=!1,this.el_=document.createElement("div"),this.el_.style.cssText="\nposition: fixed;\nz-index: 99999;\npointer-events: none;\nbackground: rgba(30, 30, 30, 0.85);\nborder: 1px solid rgba(60, 60, 60, 0.8);\nborder-radius: 4px;\npadding: 6px 10px;\nfont: 11px monospace;\ncolor: #cccccc;\nline-height: 1.6;\nmin-width: 200px;\nwhite-space: pre;\n"+function(e){switch(e){case"top-left":return"top: 12px; left: 12px;";case"top-right":return"top: 12px; right: 12px;";case"bottom-left":return"bottom: 12px; left: 12px;";case"bottom-right":return"bottom: 12px; right: 12px;"}}(t),e.appendChild(this.el_)}update(e){if(!this.visible_||this.disposed_)return;const t=[];if(t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div><div>FPS: <span style="color:#d19a66">${Ur(e.fps,1)}</span> Frame: <span style="color:#d19a66">${Ur(e.frameTimeMs,1)}ms</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div><div>DC: <span style="color:#d19a66">${e.drawCalls}</span> Tri: <span style="color:#d19a66">${e.triangles}</span></div><div>Sprites: <span style="color:#d19a66">${e.sprites}</span> Culled: <span style="color:#d19a66">${e.culled}</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div><div>Entities: <span style="color:#d19a66">${e.entityCount}</span></div>`),e.systemTimings.size>0){const s=[...e.systemTimings.entries()].sort((e,t)=>t[1]-e[1]).slice(0,5);let n='<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';for(const[e,t]of s){n+=`<div>${Lr(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${Ur(t,1)}ms</span></div>`}t.push(n)}this.el_.innerHTML=t.join("")}show(){this.visible_=!0,this.el_.style.display=""}hide(){this.visible_=!1,this.el_.style.display="none"}dispose(){this.disposed_=!0,this.el_.parentElement?.removeChild(this.el_)}}function Wr(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const $r=Me(Wr(),"Stats");const Or="StatsCollect";class Hr{constructor(){this.deltas_=[],this.cursor_=0,this.count_=0,this.sum_=0}pushFrame(e){!Number.isFinite(e)||e<0||(this.count_<60?(this.deltas_.push(e),this.sum_+=e,this.count_++):(this.sum_-=this.deltas_[this.cursor_],this.deltas_[this.cursor_]=e,this.sum_+=e,this.cursor_=(this.cursor_+1)%60))}getFps(){return 0===this.count_||this.sum_<=0?0:this.count_/this.sum_}getFrameTimeMs(){return 0===this.count_||this.sum_<=0?0:this.sum_/this.count_*1e3}reset(){this.deltas_.length=0,this.cursor_=0,this.count_=0,this.sum_=0}}class Nr{constructor(e){this.name="Stats",this.collector_=new Hr,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource($r,Wr());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new zr(e,this.options_.position)}const t=this.collector_,s=this.overlay_,n=rt([Te(Re),{_type:"get_world"}],(n,i)=>{t.pushFrame(n.delta);const o=e.getResource($r);o.fps=t.getFps(),o.frameTimeMs=t.getFrameTimeMs(),o.entityCount=i.entityCount();const r=e.getSystemTimings();if(r){const e=new Map(r);e.delete(Or),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=Ks.getStats();o.drawCalls=l.drawCalls,o.triangles=l.triangles,o.sprites=l.sprites,o.text=l.text,o.spine=l.spine,o.meshes=l.meshes,o.culled=l.culled,s?.update(o)},{name:Or});e.addSystemToSchedule(exports.Schedule.Last,n)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const Xr=new Nr;class jr{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,s)=>{const n=new Image;n.onload=()=>{const e=document.createElement("canvas");e.width=n.width,e.height=n.height;const s=e.getContext("2d");s.drawImage(n,0,0);const i=s.getImageData(0,0,n.width,n.height);t({width:n.width,height:n.height,pixels:new Uint8Array(i.data.buffer)})},n.onerror=s,n.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return function(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}(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}async function Vr(e,t){try{const s=function(e){const t=atob(e),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s}(t);return await e({instantiateWasm:(e,t)=>(WebAssembly.instantiate(s.buffer,e).then(e=>{t(e.instance,e.module)}),{})})}catch(e){return null}}const Yr=[ti,pi,vi,Hi,Ji,Ai,to,ro,po,Vi,Di,mo,xo,So,To,Fo,Bo],Gr=[...Yr,Er,Dr];function qr(e,t){return function(e,t){const s=dn.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),_s(e),wt(e),Ds(e),$s(e),Gs(e),Qs(e);const i=new tn;s.setPipeline(i);let o=c();const r=t?.getViewportSize??(()=>{const e=u();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=yn(e,n,t,i));const r=s.getResource(pt);if(o.length>0){const e=o[0],s=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(s.x*t),r.vpY=Math.round((1-s.y-s.h)*i),r.vpW=Math.round(s.w*t),r.vpH=Math.round(s.h*i),r.screenW=t,r.screenH=i,r.worldLeft=e.cameraX-e.halfW,r.worldRight=e.cameraX+e.halfW,r.worldBottom=e.cameraY-e.halfH,r.worldTop=e.cameraY+e.halfH,r.valid=!0}else r.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,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=r();a(e,t)}},d={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const u=e.registry_getCanvasEntity(n);if(u>=0){const e=n.getCanvas(u).backgroundColor;Ks.setClearColor(e.x,e.y,e.z,e.w)}const d=(c()-o)/1e3;let h;if(Ks.resize(t,l),Ns.isInitialized()&&Ns.getPassCount()>0&&!Ns.isBypassed()&&Ns.resize(t,l),s.hasResource(an)){const e=s.getResource(an).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const p=yn(e,n,t,l,s.world,h);if(a(t,l,p),0===p.length)i.render({registry:{_cpp:n},viewProjection:pn,width:t,height:l,elapsed:d});else{for(const e of p){const s=e.viewportRect,o=Math.round(s.x*t),r=Math.round((1-s.y-s.h)*l),a=Math.round(s.w*t),c=Math.round(s.h*l);i.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:d})}Ks.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(exports.Schedule.First,l),s.addSystemToSchedule(exports.Schedule.Last,d),s.addPlugin(ns),s.addPlugin(hs),s.addPlugin(ht),s.addPlugin(un),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Gr,...t})}class Kr{constructor(e){this.resolvePath_=e}async loadPixels(e){return async function(e){return t().loadImagePixels(e)}(this.resolvePath_(e))}async readText(e){return o(this.resolvePath_(e))}async readBinary(e){const t=await i(this.resolvePath_(e));return new Uint8Array(t)}resolvePath(e){return this.resolvePath_(e)}}function Jr(e){return(t,s)=>(a(e,t).then(e=>{s(e.instance,e.module)}),{})}async function Qr(e,t){try{return await e({instantiateWasm:Jr(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}k||(k=!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},i=await f(s,n);return{ok:i.ok,status:i.status,statusText:i.statusText,headers:new Headers(i.headers),json:()=>i.json(),text:()=>i.text(),arrayBuffer:()=>i.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 m(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 i=e.charCodeAt(t);i<128?s[n++]=i:i<2048?(s[n++]=192|i>>6,s[n++]=128|63&i):i>=55296&&i<=56319?(i=e.charCodeAt(++t)-56320+(i-55296<<10)+65536,s[n++]=240|i>>18,s[n++]=128|i>>12&63,s[n++]=128|i>>6&63,s[n++]=128|63&i):(s[n++]=224|i>>12,s[n++]=128|i>>6&63,s[n++]=128|63&i)}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 i=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(i>>10),56320+(1023&i)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=B,exports.Added=function(e){return{_filterType:"added",_component:e}},exports.AnimationPlugin=Tr,exports.App=dn,exports.AssetPlugin=ss,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=es,exports.Assets=ts,exports.AsyncCache=Ft,exports.Audio=$t,exports.AudioBus=d,exports.AudioListener=kr,exports.AudioMixer=class{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new d(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new d(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new d(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new d(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new d(e,{name:"voice",volume:t.voiceVolume??1}),this.master.addChild(this.voice),this.buses_.set("master",this.master),this.buses_.set("music",this.music),this.buses_.set("sfx",this.sfx),this.buses_.set("ui",this.ui),this.buses_.set("voice",this.voice)}getBus(e){return this.buses_.get(e)}createBus(e){const t=new d(this.context_,e),s=e.parent?this.buses_.get(e.parent):this.master;return s&&s.addChild(t),this.buses_.set(e.name,t),t}},exports.AudioPlugin=Br,exports.AudioPool=class{constructor(e,t=16){this.pool_=[],this.activeCount_=0,this.context_=e;for(let e=0;e<t;e++)this.pool_.push(this.createNode())}createNode(){const e=this.context_.createGain(),t=this.context_.createStereoPanner();return e.connect(t),{gain:e,panner:t,source:null,inUse:!1,startTime:0}}acquire(){let e=this.pool_.find(e=>!e.inUse);return e||(e=this.createNode(),this.pool_.push(e)),e.inUse=!0,e.startTime=this.context_.currentTime,e.gain.gain.value=1,e.panner.pan.value=0,this.activeCount_++,e}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}},exports.AudioSource=Fr,exports.BitmapText=me,exports.BodyType=Se,exports.BoxCollider=we,exports.Button=yi,exports.ButtonState=gi,exports.Camera=ue,exports.Canvas=de,exports.CapsuleCollider=be,exports.Changed=function(e){return{_filterType:"changed",_component:e}},exports.Children=fe,exports.CircleCollider=ve,exports.ClearFlags=ie,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=Qe,exports.DEFAULT_DESIGN_HEIGHT=U,exports.DEFAULT_DESIGN_WIDTH=D,exports.DEFAULT_FALLBACK_DT=L,exports.DEFAULT_FIXED_TIMESTEP=W,exports.DEFAULT_FONT_FAMILY="Arial",exports.DEFAULT_FONT_SIZE=24,exports.DEFAULT_GRAVITY=z,exports.DEFAULT_LINE_HEIGHT=1.2,exports.DEFAULT_MAX_DELTA_TIME=.5,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_SPINE_SKIN="default",exports.DEFAULT_SPRITE_SIZE={x:100,y:100},exports.DEFAULT_TEXT_CANVAS_SIZE=512,exports.DragPlugin=eo,exports.DragState=Zi,exports.Draggable=Qi,exports.Draw=bs,exports.Dropdown=Po,exports.DropdownPlugin=Mo,exports.EasingType=ir,exports.EntityCommands=Je,exports.EventReader=function(e){return{_type:"event_reader",_event:e}},exports.EventReaderInstance=st,exports.EventRegistry=et,exports.EventWriter=function(e){return{_type:"event_writer",_event:e}},exports.EventWriterInstance=tt,exports.FillDirection=Tn,exports.FillMethod=Li,exports.FillOrigin=zi,exports.FocusManager=ki,exports.FocusManagerState=Fi,exports.FocusPlugin=fo,exports.Focusable=Ii,exports.FrameHistory=class{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,s){const n={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:s?new Map(s):new Map};this.count_<this.capacity_?(this.buffer_.push(n),this.count_++):this.buffer_[this.cursor_]=n,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}},exports.GLDebug=en,exports.Geometry=zs,exports.GetWorld=it,exports.INVALID_ENTITY=0,exports.INVALID_FONT=X,exports.INVALID_MATERIAL=0,exports.INVALID_TEXTURE=N,exports.Image=Wi,exports.ImagePlugin=Oi,exports.ImageType=Ui,exports.Input=ut,exports.InputPlugin=dt,exports.InputState=ct,exports.Interactable=fi,exports.LayoutGroupPlugin=Io,exports.ListView=wo,exports.ListViewPlugin=bo,exports.LocalTransform=ae,exports.Logger=sr,exports.LoopMode=rr,exports.Material=St,exports.MaterialLoader=kt,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ye,exports.Parent=pe,exports.Physics=Ho,exports.PhysicsEvents=Uo,exports.PhysicsPlugin=$o,exports.PostProcess=Ns,exports.PrefabServer=cs,exports.Prefabs=us,exports.PrefabsPlugin=ds,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(an);t.register({name:Qo,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Qo),this.loadPromise_=t.load(Qo).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await n(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new Jo(this.baseUrl_);await s.prefetch(t);let i=null;const o=this.app_.spineInitPromise;if(o){i=(await o).controller.raw}await Go({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:s,spineModule:i,sceneName:Qo})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([ue]);for(const n of s){if(e.get(n,ue).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([de]);for(const i of n){const n=e.get(i,de);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const i=this.app_.getResource(an).getScene(Qo),o=i?i.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,re,r);const a={isActive:!0,projectionType:ne.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:ie.ColorAndDepth};e.insert(o,ue,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(an);await e.switchTo(Qo),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}},exports.ProgressBar=Gi,exports.ProgressBarDirection=Yi,exports.ProgressBarPlugin=Ki,exports.ProjectionType=ne,exports.Query=function(...e){return Ge(e)},exports.QueryInstance=qe,exports.Removed=function(e){return{_type:"removed",_component:e}},exports.RemovedQueryInstance=Ke,exports.RenderPipeline=tn,exports.RenderTexture=Zo,exports.Renderer=Ks,exports.Res=Te,exports.ResMut=Ee,exports.RigidBody=xe,exports.RuntimeConfig=$,exports.SafeArea=go,exports.SafeAreaPlugin=_o,exports.ScaleMode=oe,exports.SceneManager=an,exports.SceneManagerState=rn,exports.SceneOwner=_e,exports.ScrollView=so,exports.ScrollViewPlugin=oo,exports.ShaderSources=It,exports.Slider=lo,exports.SliderDirection=ao,exports.SliderPlugin=ho,exports.SpineAnimation=ge,exports.Sprite=ce,exports.SpriteAnimator=zt,exports.Stats=$r,exports.StatsCollector=Hr,exports.StatsOverlay=zr,exports.StatsPlugin=Nr,exports.SystemRunner=lt,exports.Text=Jn,exports.TextAlign=Gn,exports.TextInput=Ri,exports.TextInputPlugin=Bi,exports.TextOverflow=Kn,exports.TextPlugin=ei,exports.TextRenderer=Qn,exports.TextVerticalAlign=qn,exports.Time=Re,exports.Toggle=Ni,exports.TogglePlugin=ji,exports.Transform=re,exports.Tween=Mr,exports.TweenHandle=_r,exports.TweenState=or,exports.TweenTarget={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12},exports.UICameraInfo=pt,exports.UIEventQueue=_i,exports.UIEvents=xi,exports.UIInteraction=mi,exports.UIInteractionPlugin=Ci,exports.UILayoutPlugin=wi,exports.UIMask=ii,exports.UIMaskPlugin=hi,exports.UIRect=Cn,exports.UIRenderOrderPlugin=ko,exports.Velocity=he,exports.WeChatAssetProvider=Kr,exports.WebAssetProvider=Jo,exports.World=Ne,exports.WorldTransform=le,exports.addStartupSystem=function(e){at().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){at().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){at().push({schedule:e,system:t})},exports.animationPlugin=Er,exports.applyBuildRuntimeConfig=H,exports.applyDirectionalFill=kn,exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=$.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=$.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=$.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=$.canvasMatchWidthOrHeight)},exports.assetPlugin=ns,exports.audioPlugin=Dr,exports.calculateAttenuation=Rr,exports.calculatePanning=Ir,exports.clearAnimClips=function(){Ut.clear()},exports.clearDrawCallbacks=As,exports.clearUserComponents=function(){const e=G();for(const t of e.keys())Z.delete(t);e.clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeFillAnchors=Fn,exports.computeFillSize=function(e,t,s,n){switch(e){case Tn.BottomToTop:case Tn.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}},exports.computeHandleAnchors=function(e,t){switch(e){case Tn.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case Tn.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case Tn.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1-t}};default:return{anchorMin:{x:t,y:0},anchorMax:{x:t,y:1}}}},exports.computeUIRectLayout=En,exports.createMaskProcessor=di,exports.createRuntimeSceneConfig=qo,exports.createWebApp=qr,exports.debug=function(e,t,s){nr.debug(e,t,s)},exports.defaultFrameStats=Wr,exports.defineComponent=q,exports.defineEvent=function(e){return{_id:Symbol(`Event_${e}`),_name:e}},exports.defineResource=Me,exports.defineSystem=rt,exports.defineTag=function(e){const t=Z.get(e)??G().get(e);if(t)return t;const s=Y(e,{});return G().set(e,s),Z.set(e,s),J(e,{},!0),s},exports.dragPlugin=to,exports.dropdownPlugin=To,exports.error=function(e,t,s){nr.error(e,t,s)},exports.extractAnimClipTexturePaths=Bt,exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([ye]);for(const n of s){const s=e.get(n,ye);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=hn,exports.focusPlugin=mo,exports.getAddressableType=function(e){return v(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of g)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return x},exports.getAnimClip=function(e){return Ut.get(e)},exports.getAssetBuildTransform=function(e){return v(e)?.buildTransform},exports.getAssetMimeType=function(e){return y[e.toLowerCase()]},exports.getAssetTypeEntry=v,exports.getComponent=te,exports.getComponentAssetFieldDescriptors=Nt,exports.getComponentAssetFields=Ht,exports.getComponentDefaults=function(e){const t=te(e);return t?j(t._default):null},exports.getComponentEntityFields=Vt,exports.getComponentSpineFieldDescriptor=Xt,exports.getCustomExtensions=S,exports.getEditorType=function(e){return v(e)?.editorType??"unknown"},exports.getLogger=function(){return nr},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=K,exports.getWeChatPackOptions=function(){return S().map(e=>({type:"suffix",value:e}))},exports.imagePlugin=Hi,exports.info=function(e,t,s){nr.info(e,t,s)},exports.initDrawAPI=_s,exports.initGLDebugAPI=Qs,exports.initGeometryAPI=Ds,exports.initMaterialAPI=wt,exports.initPlayableRuntime=async function(e){const{app:t,module:s,assets:n,sceneData:i,sceneName:o}=e,r=t.getResource(ts);r&&(r.registerEmbeddedAssets(n),r.setEmbeddedOnly(!0));const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await Vr(ESSpineModule,e);return t||console.warn("Spine module not available"),t}(e.spineWasmBase64):null,l=e.physicsWasmBase64?await async function(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await Vr(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new jr(n);await Ko({app:t,module:s,provider:c,scenes:[{name:o,data:i}],firstScene:o,spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()},exports.initPostProcessAPI=$s,exports.initRendererAPI=Gs,exports.initRuntime=Ko,exports.initTweenAPI=vr,exports.initWeChatRuntime=async function(e){const t=await o("asset-manifest.json"),s=JSON.parse(t),n=function(e){const{assetIndex:t,pathIndex:s}=e;return e=>{const n=M(e),i=t[e]||t[n]||s[n]||s[e];return i?i.path:n}}(function(e){const t={},s={};for(const n in e.groups){const i=e.groups[n];for(const e in i.assets){const n=i.assets[e];t[e]=n,s[n.path]=n}}return{assetIndex:t,pathIndex:s}}(s)),i=wx.createCanvas(),r=wx.getSystemInfoSync();i.width=r.windowWidth*r.pixelRatio,i.height=r.windowHeight*r.pixelRatio;const a=await e.engineFactory({canvas:i,instantiateWasm:Jr("esengine.wasm")}),l=i.getContext("webgl2")||i.getContext("webgl");if(!l)return void console.error("[ESEngine] Failed to create WebGL context");const c=a.GL.registerContext(l,{majorVersion:0===l.getParameter(l.VERSION).indexOf("WebGL 2")?2:1,minorVersion:0,enableExtensionsByDefault:!0}),u=qr(a,{glContextHandle:c,getViewportSize:()=>({width:i.width,height:i.height})});e.runtimeConfig&&H(u,e.runtimeConfig);let d=null;e.spineFactory&&(d=await Qr(e.spineFactory,"spine.wasm"));let h=null;e.physicsFactory&&(h=await Qr(e.physicsFactory,"physics.wasm"));const p=new Kr(n),f=[];for(const t of e.sceneNames){const e=await o(`scenes/${t}.json`);f.push({name:t,data:JSON.parse(e)})}await Ko({app:u,module:a,provider:p,scenes:f,firstScene:e.firstScene,spineModule:d,physicsModule:h,physicsConfig:e.physicsConfig,manifest:s,aspectRatio:i.width/i.height}),u.run()},exports.inputPlugin=ht,exports.instantiatePrefab=is,exports.intersectRects=oi,exports.invertMatrix4=ri,exports.isBuiltinComponent=Q,exports.isCustomExtension=P,exports.isEditor=Pi,exports.isKnownAssetExtension=b,exports.isPlatformInitialized=function(){return null!==e},exports.isPlayMode=Mi,exports.isRuntime=function(){return!bi},exports.isTextureRef=mt,exports.isWeChat=s,exports.isWeb=function(){return"web"===e?.name},exports.layoutGroupPlugin=Fo,exports.listViewPlugin=So,exports.loadComponent=Qt,exports.loadPhysicsModule=Do,exports.loadRuntimeScene=Go,exports.loadSceneData=qt,exports.loadSceneWithAssets=Kt,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&b(w(e)))},exports.parseAnimClipData=Dt,exports.platformFetch=n,exports.platformFileExists=r,exports.platformInstantiateWasm=a,exports.platformReadFile=i,exports.platformReadTextFile=o,exports.pointInOBB=function(e,t,s,n,i,o,r,a,l,c){const u=li(l,c),d=Math.sin(-u),h=Math.cos(-u),p=e-s,f=t-n,m=p*h-f*d+s,g=p*d+f*h+n;return m>=s-i*r&&m<=s+i*(1-r)&&g>=n-o*a&&g<=n+o*(1-a)},exports.pointInWorldRect=function(e,t,s,n,i,o,r,a){return e>=s-i*r&&e<=s+i*(1-r)&&t>=n-o*a&&t<=n+o*(1-a)},exports.prefabsPlugin=hs,exports.progressBarPlugin=Ji,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerAnimClip=Lt,exports.registerAssetBuildTransform=function(e,t){for(const s of g)s.editorType===e&&(s.buildTransform=t)},exports.registerComponent=ee,exports.registerComponentAssetFields=function(e,t){Ot.set(e,t)},exports.registerComponentEntityFields=function(e,t){jt.set(e,t)},exports.registerDrawCallback=Es,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(ts);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=Rt,exports.remapEntityFields=Yt,exports.safeAreaPlugin=xo,exports.sceneManagerPlugin=un,exports.screenToWorld=ai,exports.scrollViewPlugin=ro,exports.setEditorMode=function(e){bi=e},exports.setListViewRenderer=function(e,t){if(!vo)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=vo.get(e);s?s.renderer=t:vo.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})},exports.setLogLevel=function(e){nr.setMinLevel(e)},exports.setPlayMode=function(e){Si=e},exports.setWasmErrorHandler=De,exports.shutdownDrawAPI=xs,exports.shutdownGLDebugAPI=Zs,exports.shutdownGeometryAPI=Us,exports.shutdownMaterialAPI=vt,exports.shutdownPostProcessAPI=Os,exports.shutdownRendererAPI=qs,exports.shutdownTweenAPI=br,exports.sliderPlugin=po,exports.spriteAnimatorSystemUpdate=Wt,exports.statsPlugin=Xr,exports.syncFillSpriteSize=function(e,t,s,n,i,o){if(!e.has(t,ce))return;const r=e.get(t,ce);let a,l;switch(s){case Tn.BottomToTop:case Tn.TopToBottom:a=i,l=o*n;break;default:a=i*n,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,ce,r))},exports.textInputPlugin=Di,exports.textPlugin=ti,exports.toBuildPath=M,exports.togglePlugin=Vi,exports.transitionTo=async function(e,t,s){const n=e.getResource(an);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=Ai,exports.uiLayoutPlugin=vi,exports.uiMaskPlugin=pi,exports.uiPlugins=Yr,exports.uiRenderOrderPlugin=Bo,exports.unregisterAnimClip=function(e){Ut.delete(e)},exports.unregisterComponent=function(e){G().delete(e),Z.delete(e)},exports.unregisterDrawCallback=Cs,exports.updateCameraAspectRatio=Zt,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){nr.warn(e,t,s)},exports.wrapSceneSystem=ln,exports.wxFileExists=function(e){return new Promise(t=>{E().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})},exports.wxFileExistsSync=A,exports.wxGetImagePixels=I,exports.wxLoadImage=R,exports.wxLoadImagePixels=F,exports.wxReadFile=function(e){return new Promise((t,s)=>{E().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(C(e,t.errMsg)))}})})},exports.wxReadTextFile=function(e,t="utf-8"){return new Promise((s,n)=>{E().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(C(e,t.errMsg)))}})})},exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{E().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 3ccfe646b..c4628171b 100644--- a/desktop/public/sdk/cjs/index.wechat.js+++ b/desktop/public/sdk/cjs/index.wechat.js@@ -1,2 +1,2 @@-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function s(){return null!==e}function n(){return e?.name??null}function i(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function r(e,s){return t().fetch(e,s)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,s){return t().instantiateWasm(e,s)}function d(e,s){return t().createCanvas(e,s)}function h(){return t().now()}function f(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}class p{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,t.volume??1)),this.muted_=t.muted??!1,this.gainNode_.gain.value=this.muted_?0:this.volume_}get name(){return this.name_}get node(){return this.gainNode_}get volume(){return this.volume_}set volume(e){this.volume_=Math.max(0,Math.min(1,e)),this.muted_||this.gainNode_.gain.setTargetAtTime(this.volume_,this.gainNode_.context.currentTime,.015)}get muted(){return this.muted_}set muted(e){this.muted_=e,this.gainNode_.gain.setTargetAtTime(e?0:this.volume_,this.gainNode_.context.currentTime,.015)}connect(e){e instanceof p?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class m{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new p(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new p(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new p(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new p(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new p(e,{name:"voice",volume:t.voiceVolume??1}),this.master.addChild(this.voice),this.buses_.set("master",this.master),this.buses_.set("music",this.music),this.buses_.set("sfx",this.sfx),this.buses_.set("ui",this.ui),this.buses_.set("voice",this.voice)}getBus(e){return this.buses_.get(e)}createBus(e){const t=new p(this.context_,e),s=e.parent?this.buses_.get(e.parent):this.master;return s&&s.addChild(t),this.buses_.set(e.name,t),t}}class g{constructor(e,t=16){this.pool_=[],this.activeCount_=0,this.context_=e;for(let e=0;e<t;e++)this.pool_.push(this.createNode())}createNode(){const e=this.context_.createGain(),t=this.context_.createStereoPanner();return e.connect(t),{gain:e,panner:t,source:null,inUse:!1,startTime:0}}acquire(){let e=this.pool_.find(e=>!e.inUse);return e||(e=this.createNode(),this.pool_.push(e)),e.inUse=!0,e.startTime=this.context_.currentTime,e.gain.gain.value=1,e.panner.pan.value=0,this.activeCount_++,e}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}}class _{constructor(e,t,s){this.panWarned_=!1,this.id=e,this.ctx_=t,this.contexts_=s}stop(){this.ctx_.stop(),this.ctx_.destroy(),this.contexts_.delete(this.id)}pause(){this.ctx_.pause()}resume(){this.ctx_.play()}setVolume(e){this.ctx_.volume=e}setPan(e){this.panWarned_||(console.warn("[Audio] WeChat InnerAudioContext does not support stereo panning"),this.panWarned_=!0)}setLoop(e){this.ctx_.loop=e}setPlaybackRate(e){this.ctx_.playbackRate=e}get isPlaying(){return!this.ctx_.paused}get currentTime(){return this.ctx_.currentTime}get duration(){return this.ctx_.duration}}class y{constructor(){this.name="WeChat",this.contexts_=new Map,this.urlCache_=new Map,this.nextId_=0}get mixer(){return null}get isReady(){return!0}async initialize(e){}async ensureResumed(){}async loadBuffer(e){const t=++this.nextId_;return this.urlCache_.set(t,e),{id:t,duration:0}}unloadBuffer(e){this.urlCache_.delete(e.id)}play(e,t){const s=this.urlCache_.get(e.id);if(!s)throw new Error(`Buffer ${e.id} not found`);const n=wx.createInnerAudioContext();n.src=s,n.loop=t.loop??!1,n.volume=t.volume??1,n.playbackRate=t.playbackRate??1,n.startTime=t.startOffset??0,n.obeyMuteSwitch=!1;const i=++this.nextId_;this.contexts_.set(i,n);const o=new _(i,n,this.contexts_);return n.onEnded(()=>{o.onEnd?.(),n.loop||(n.destroy(),this.contexts_.delete(i))}),n.autoplay=!0,o}suspend(){for(const e of this.contexts_.values())e.pause()}resume(){for(const e of this.contexts_.values())e.paused&&e.play()}dispose(){for(const e of this.contexts_.values())e.destroy();this.contexts_.clear(),this.urlCache_.clear()}}function w(e,t){return new Promise((s,n)=>{const i=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===i?"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 x(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 v=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],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},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0}],b={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",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",bmfont:"application/json",fnt:"text/plain"},S=new Map,M=new Set;for(const e of v)for(const t of e.extensions)S.set(t,e),M.add(t);function P(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function T(e){return S.get(P(e))}function E(e){return T(e)?.editorType??"unknown"}function C(e){return T(e)?.addressableType??null}function A(e){for(const t of v)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function R(e){return M.has(e.toLowerCase())}function I(){return M}function F(e){return"string"==typeof e&&(!!e.includes("/")&&R(P(e)))}function k(){const e=[];for(const t of v)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function B(){return k().map(e=>({type:"suffix",value:e}))}function z(e){return b[e.toLowerCase()]}function $(e){const t=T(e);return t?.wechatPackInclude??!1}function U(e){const t=T(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const s=e.lastIndexOf(".");return s>=0?e.substring(0,s)+".json":e}let W=null;function D(){return W||(W=wx.getFileSystemManager()),W}function O(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 L(e){return new Promise((t,s)=>{D().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(O(e,t.errMsg)))}})})}function H(e,t="utf-8"){return new Promise((s,n)=>{D().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(O(e,t.errMsg)))}})})}function j(e){return new Promise(t=>{D().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function X(e){const t=D();try{return t.accessSync(e),!0}catch{return!1}}function Y(e,t){return new Promise((s,n)=>{D().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function V(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 N(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 i=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(i.data.buffer)}}async function G(e){return N(await V(e))}let q=!1;const K=new class{constructor(){this.name="wechat",this.inputCleanup_=null}async fetch(e,t){return w(e,t)}async readFile(e){return function(e){return D().readFileSync(e)}(U(e))}async readTextFile(e){return function(e,t="utf-8"){return D().readFileSync(e,t)}(U(e))}async fileExists(e){return X(U(e))}async loadImagePixels(e){return G(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return x(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){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const s=t=>e.onKeyDown(t.code),n=t=>e.onKeyUp(t.code),i="function"==typeof wx.onKeyDown;i&&(wx.onKeyDown(s),wx.onKeyUp(n));const o=t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX,s.clientY)},r=t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX,s.clientY)},a=t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)};wx.onTouchStart(o),wx.onTouchMove(r),wx.onTouchEnd(a),this.inputCleanup_=()=>{i&&(wx.offKeyDown(s),wx.offKeyUp(n)),wx.offTouchStart(o),wx.offTouchMove(r),wx.offTouchEnd(a)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new y}},J=1920,Q=1080,Z=100,ee=512,te={x:100,y:100},se="Arial",ne=24,ie=1.2,oe=.5,re=1/60,ae={x:0,y:-9.81},le=1/60,ce="default",ue={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function de(e){e.Text&&(e.Text._default.fontFamily=ue.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=ue.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=ue.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=ue.canvasMatchWidthOrHeight)}const he={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function fe(e,t){if(void 0!==t.maxDeltaTime&&(ue.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(ue.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(ue.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(ue.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(ue.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");ue.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&(ue.canvasScaleMode=he[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(ue.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight)}const pe=0,me=4294967295,ge=4294967295,_e=0,ye=(e=0,t=0)=>({x:e,y:t}),we=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),xe=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),ve=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),be=(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 Me=0;function Pe(e,t){const s=++Me,n=function(e){for(const t in e){const s=e[t];if(null!==s&&"object"==typeof s)return!0}return!1}(t);return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>n?e?{...Se(t),...e}:Se(t):e?{...t,...e}:{...t}}}function Te(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function Ee(e,t){const s=Be.get(e)??Te().get(e);if(s)return s;const n=Pe(e,t);return Te().set(e,n),Be.set(e,n),Fe(e,t,!1),n}function Ce(e){const t=Be.get(e)??Te().get(e);if(t)return t;const s=Pe(e,{});return Te().set(e,s),Be.set(e,s),Fe(e,{},!0),s}function Ae(e){return Te().get(e)}function Re(){const e=Te();for(const t of e.keys())Be.delete(t);e.clear()}function Ie(e){Te().delete(e),Be.delete(e)}function Fe(e,t,s){const n=globalThis;n.__esengine_registerComponent&&n.__esengine_registerComponent(e,t,s)}function ke(e){return!0===e._builtin}const Be=new Map;function ze(e,t){Be.set(e,t)}function $e(e){return Be.get(e)??Ae(e)}function Ue(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return Be.set(e,s),s}const We={Perspective:0,Orthographic:1},De={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},Oe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},Le=Ue("Transform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}}),He=Le,je=Le,Xe=Ue("Sprite",{texture:me,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),Ye=Ue("Camera",{projectionType:We.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:De.ColorAndDepth}),Ve=Ue("Canvas",{designResolution:{x:J,y:Q},pixelsPerUnit:100,scaleMode:Oe.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Ne=Ue("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Ge=Ue("Parent",{entity:0}),qe=Ue("Children",{entities:[]}),Ke=Ue("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:ge,enabled:!0}),Je=Ue("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),Qe=Ee("Name",{value:""}),Ze=Ee("SceneOwner",{scene:"",persistent:!1});function et(e){const t=$e(e);return t?Se(t._default):null}const tt=Ue("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),st=Ue("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),nt=Ue("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),it=Ue("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ot={Static:0,Kinematic:1,Dynamic:2};let rt=0;function at(e,t){const s=++rt;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function lt(e){return{_type:"res",_resource:e}}function ct(e){return{_type:"res_mut",_resource:e}}class ut{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class dt{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new ut(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const ht=at({delta:0,elapsed:0,frameCount:0},"Time");function ft(e,t,s){const n=[];for(const[e,i]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const s=pt(t[e]),o=pt(i);"null"!==s&&"undefined"!==s&&(s!==o&&null!=i&&n.push({field:e,expected:s,actual:o,value:i}))}return n}function pt(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function mt(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}let gt=null;function _t(e){gt=e}function yt(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),gt&>(e,t)}function wt(e){let t=!1;for(const s of Object.keys(e)){const n=e[s];if(null!=n&&"object"==typeof n&&!Array.isArray(n)){if("r"in n&&"g"in n&&"b"in n&&"a"in n&&!("x"in n)){t=!0;break}}}if(!t)return e;const s={};for(const t of Object.keys(e)){const n=e[t];if(null==n||"object"!=typeof n||Array.isArray(n))s[t]=n;else{const e=n;s[t]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:n}}return s}let xt=1;const vt=new WeakMap;function bt(e){let t=vt.get(e);return void 0===t&&(t=xt++,vt.set(e,t)),t}const St=[];function Mt(e,t=[],s=[]){St.length=0;for(const t of e)St.push(bt(t));St.sort((e,t)=>e-t);let n=St.join(",");if(t.length>0){St.length=0;for(const e of t)St.push(bt(e));St.sort((e,t)=>e-t),n+="|+"+St.join(",")}if(s.length>0){St.length=0;for(const e of s)St.push(bt(e));St.sort((e,t)=>e-t),n+="|-"+St.join(",")}return n}class Pt{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw yt(e,"spawn"),e}else e=++this.nextEntityId_;let t=0;if(this.module_&&this.cppRegistry_)try{t=this.module_.registry_getGeneration(this.cppRegistry_,e)}catch{}else t=++this.nextGeneration_;this.entities_.set(e,t),this.worldVersion_++;for(const t of this.spawnCallbacks_)try{t(e)}catch{}return e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch{}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){yt(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t){this.tsStorage_.get(s)?.delete(e),this.componentAddedTicks_.get(s)?.delete(e),this.componentChangedTicks_.get(s)?.delete(e);let t=this.componentRemovedBuffer_.get(s);t||(t=[],this.componentRemovedBuffer_.set(s,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){yt(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){yt(t,`removeParent(entity=${e})`)}}insert(e,t,s){return ke(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}set(e,t,s){if(ke(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,wt(s))}catch(s){yt(s,`set(${t._name}, entity=${e})`)}this.recordChangedTick_(t,e)}else this.getStorage(t).set(e,s),this.recordChangedTick_(t,e)}get(e,t){return ke(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return ke(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(ke(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return yt(s,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");ke(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_,n=s[`add${e}`],i=s[`get${e}`],o=s[`has${e}`],r=s[`remove${e}`];if("function"!=typeof n||"function"!=typeof i||"function"!=typeof o||"function"!=typeof r)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:n.bind(s),get:i.bind(s),has:o.bind(s),remove:r.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=ft(t._name,t._default,n);if(e.length>0)throw new Error(mt(t._name,e))}const i={...t._default,...n};let o=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(t._cppName);o=!s.has(e),s.add(e,wt(i))}catch(s){yt(s,`insertBuiltin(${t._name}, entity=${e})`)}return o&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let s=!1;for(const n of Object.keys(t)){const i=t[n];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){const t=e[n];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){s=!0;break}}}if(!s)return e;const n={};for(const s of Object.keys(e)){const i=e[s],o=t[s];if(null==i||"object"!=typeof i||Array.isArray(i)||null==o||"object"!=typeof o||Array.isArray(o))n[s]=i;else{const e=i,t=o;n[s]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:i}}return n}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(s){return yt(s,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(s){return yt(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){yt(s,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++}}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 i=ft(t._name,t._default,e);if(i.length>0)throw new Error(mt(t._name,i));n=e}const i=t.create(n),o=this.getStorage(t),r=!o.has(e);o.set(e,i);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}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.recordRemovedTick_(t,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}getComponentTypes(e){const t=new Set;for(const[s,n]of this.builtinMethodCache_)try{n.has(e)&&t.add(s)}catch{}if(this.cppRegistry_)for(const[s,n]of Be)if(ke(n)&&!t.has(s))try{this.getBuiltinMethods(n._cppName).has(e)&&t.add(s)}catch{}const s=this.entityComponents_.get(e);if(s){const e=Te();for(const n of s)for(const[s,i]of e)if(i._id===n){t.add(s);break}}return Array.from(t)}getEntitiesWithComponents(e,t=[],s=[],n){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();const i=n??Mt(e,t,s),o=this.queryCache_.get(i);if(o&&o.version===this.worldVersion_)return o.result;let r=null,a=1/0;for(const t of e)if(!ke(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<a&&(a=s,r=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=r?r.keys():this.entities_.keys();for(const n of c){let i=!0;for(const t of e)if(!this.has(n,t)){i=!1;break}if(i)for(const e of t)if(!this.has(n,e)){i=!1;break}if(i)for(const e of s)if(this.has(n,e)){i=!1;break}i&&l.push(n)}return this.queryCache_.set(i,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,s){const n=this.componentAddedTicks_.get(t._id);if(!n)return!1;const i=n.get(e);return void 0!==i&&i>s}isChangedSince(e,t,s){const n=this.componentChangedTicks_.get(t._id);if(!n)return!1;const i=n.get(e);return void 0!==i&&i>s}getRemovedEntitiesSince(e,t){const s=this.componentRemovedBuffer_.get(e._id);if(!s)return[];const n=[];for(const e of s)e.tick>t&&n.push(e.entity);return n}cleanRemovedBuffer(e){for(const[t,s]of this.componentRemovedBuffer_){let n=0;for(let t=0;t<s.length;t++)s[t].tick>=e&&(s[n++]=s[t]);s.length=n,0===n&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let s=this.componentAddedTicks_.get(e._id);s||(s=new Map,this.componentAddedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordChangedTick_(e,t){let s=this.componentChangedTicks_.get(e._id);s||(s=new Map,this.componentChangedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordRemovedTick_(e,t){let s=this.componentRemovedBuffer_.get(e._id);s||(s=[],this.componentRemovedBuffer_.set(e._id,s)),s.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function Tt(e){return{_type:"mut",_component:e}}function Et(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Ct(e){return{_filterType:"added",_component:e}}function At(e){return{_filterType:"changed",_component:e}}function Rt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function It(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Ft(e){return Et(e)||Rt(e)||It(e)?e._component:e}function kt(e,t=[],s=[]){const n=[],i=[],o=[];return e.forEach((e,t)=>{Et(e)&&n.push(t),Rt(e)?i.push({index:t,component:e._component}):It(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s,_addedFilters:i,_changedFilters:o,with:(...n)=>kt(e,[...t,...n],s),without:(...n)=>kt(e,t,[...s,...n])}}function Bt(...e){return kt(e)}class zt{constructor(e,t,s=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=s,this.actualComponents_=t._components.map(Ft),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=Mt(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:s}=this.descriptor_;if(0===t.length&&0===s.length)return!0;const n=this.lastRunTick_;for(const s of t)if(!this.world_.isAddedSince(e,s.component,n))return!1;for(const t of s)if(!this.world_.isChangedSince(e,t.component,n))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),n=t.length,i=e.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const u of s)if(!o||this.passesChangeFilters_(u)){if(null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}r[0]=u;for(let e=0;e<n;e++)r[e+1]=this.world_.get(u,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];c=u}yield r}}finally{if(this.world_.endIteration(),null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function $t(e){return{_type:"removed",_component:e}}class Ut{constructor(e,t,s){this.world_=e,this.component_=t,this.lastRunTick_=s}*[Symbol.iterator](){yield*this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}isEmpty(){return 0===this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_).length}toArray(){return this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}}function Wt(){return{_type:"commands"}}class Dt{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=ke(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 Ot{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Dt(this,null);return this.spawned_.push(e),e}entity(e){return new Dt(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"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}function Lt(e){return{_id:Symbol(`Event_${e}`),_name:e}}class Ht{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(e){this.writeBuffer_.push(e)}getReadBuffer(){return this.readBuffer_}swap(){const e=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=e,this.writeBuffer_.length=0}}class jt{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Ht)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Ht,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function Xt(e){return{_type:"event_writer",_event:e}}function Yt(e){return{_type:"event_reader",_event:e}}class Vt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class Nt{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var Gt;function qt(){return{_type:"get_world"}}!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(Gt||(Gt={}));let Kt=0;function Jt(e,t,s){const n=++Kt;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Qt(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function Zt(e){Qt().push({schedule:Gt.Update,system:e})}function es(e){Qt().push({schedule:Gt.Startup,system:e})}function ts(e,t){Qt().push({schedule:e,system:t})}class ss{constructor(e,t,s){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=s??null}setTimingEnabled(e){this.timings_=e?new Map:null}getTimings(){return this.timings_}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);const s=this.timings_?performance.now():0;try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Ot&&t[e].flush()}finally{this.timings_&&this.timings_.set(e._name,performance.now()-s),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new zt(this.world_,e,this.currentLastRunTick_);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Ot(this.world_,this.resources_);case"event_writer":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Vt(s)}case"event_reader":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Nt(s)}case"removed":{const t=e;return new Ut(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class ns{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 is=at(new ns,"Input");class os{constructor(e){this.target_=e??null}build(e){const s=new ns;e.insertResource(is,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(Gt.Last,Jt([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const rs=new os,as=at({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var ls;function cs(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"}(ls||(ls={}));let us=null,ds=null,hs=1;const fs=new Map;function ps(e){us=e,ds=e.getResourceManager(),Ms()}function ms(){0!==ws&&us&&(us._free(ws),ws=0),fs.clear(),hs=1,ys=!1,vs.clear(),bs=null,ds=null,us=null}function gs(){if(!ds)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return ds}const _s={createShader:(e,t)=>gs().createShader(e,t),releaseShader(e){e>0&&gs().releaseShader(e)},create(e){const t=hs++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??ls.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 fs.set(t,s),t},get:e=>fs.get(e),setUniform(e,t,s){const n=fs.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0,us?.invalidateMaterialCache(e))},getUniform(e,t){const s=fs.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=fs.get(e);s&&(s.blendMode=t,us?.invalidateMaterialCache(e))},getBlendMode(e){const t=fs.get(e);return t?.blendMode??ls.Normal},setDepthTest(e,t){const s=fs.get(e);s&&(s.depthTest=t,us?.invalidateMaterialCache(e))},getShader(e){const t=fs.get(e);return t?.shader??0},release(e){fs.delete(e),us?.invalidateMaterialCache(e)},isValid:e=>fs.has(e),releaseAll(){fs.clear(),us?.clearMaterialCache()},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??ls.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=fs.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=hs++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return fs.set(s,n),s},toAssetData(e,t){const s=fs.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=fs.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let ys=!1,ws=0;const xs=16384,vs=new Map;let bs=null;function Ss(e){const t=(0===ws&&us&&(ws=us._malloc(xs)),ws);if(0===t||!us)return{ptr:0,count:0};let s=0,n=0;const i=us.HEAPU8,o=us.HEAPU32,r=us.HEAPF32;for(const[a,l]of e){if(cs(l))continue;let e=vs.get(a);e||(bs||(bs=new TextEncoder),e=bs.encode(a),vs.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(s+(4+u+4+16)>xs){console.warn(`[ESEngine] Material uniform buffer full (${s}/${xs} bytes), skipping remaining uniforms`);break}o[t+s>>2]=c,s+=4,i.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++)r[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function Ms(){if(!us||ys)return;us.materialDataProvider=(e,t,s,n,i)=>{const o=fs.get(e);if(!o)return us.HEAPU32[t>>2]=0,us.HEAPU32[s>>2]=0,us.HEAPU32[n>>2]=0,void(us.HEAPU32[i>>2]=0);us.HEAPU32[t>>2]=o.shader,us.HEAPU32[s>>2]=o.blendMode;const{ptr:r,count:a}=Ss(o.uniforms);us.HEAPU32[n>>2]=r,us.HEAPU32[i>>2]=a},ys=!0}const Ps={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 Ts{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 i=this.pending_.get(e);if(i&&!i.aborted)return i.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),i=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,i),this.pending_.delete(e),i})(),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 Es{constructor(e,t=""){this.cache_=new Ts,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&&(_s.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())_s.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const s=await l(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const i=this.resolveShaderPath(e,n.shader),o=await this.shaderLoader_.load(i);return{handle:_s.createFromAsset(n,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 s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}function Cs(e){const t=new Set;for(const s of e.frames)s.texture&&t.add(s.texture);return Array.from(t)}function As(e,t,s){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>({texture:s.get(e.texture)??0}))}}const Rs=new Map;function Is(e){Rs.set(e.name,e)}function Fs(e){Rs.delete(e)}function ks(e){return Rs.get(e)}function Bs(){Rs.clear()}const zs=Ee("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function $s(e,t){const s=e.getEntitiesWithComponents([zs]);for(const n of s){const s=e.get(n,zs);if(!s.enabled||!s.playing||!s.clip)continue;const i=Rs.get(s.clip);if(!i||0===i.frames.length)continue;const o=1/(i.fps*s.speed),r=0===s.frameTimer&&0===s.currentFrame;s.frameTimer+=t;let a=r;if(s.frameTimer>=o&&(s.frameTimer-=o,s.currentFrame++,s.currentFrame>=i.frames.length&&(s.loop&&i.loop?s.currentFrame=0:(s.currentFrame=i.frames.length-1,s.playing=!1)),a=!0),a&&e.has(n,Xe)){const t=i.frames[s.currentFrame],o=e.get(n,Xe);o.texture=t.texture,e.insert(n,Xe,o)}a&&e.insert(n,zs,s)}}class Us{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null,this.bgmVolume_=1,this.disposed_=!1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}static async preload(e){if(this.bufferCache_.has(e))return;const t=await this.backend_.loadBuffer(e);this.bufferCache_.set(e,t)}static async preloadAll(e){await Promise.all(e.map(e=>this.preload(e)))}static playSFX(e,t){const s={bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0},n=this.bufferCache_.get(e);if(!n){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const n=this.bufferCache_.get(e);n&&t.resolve(this.backend_.play(n,s))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(n,s)}static playBGM(e,t){const s=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const s=t?.volume??1,n=this.bgmVolume_;this.bgmVolume_=s,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,n):this.bgmHandle_&&this.bgmHandle_.stop();const i=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:i?0:s,loop:!0}),i&&this.fadeIn(this.bgmHandle_,i,s)},n=this.bufferCache_.get(e);n?s(n):this.preload(e).then(()=>{if(this.disposed_)return;const t=this.bufferCache_.get(e);t&&s(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else this.bgmHandle_.stop(),this.bgmHandle_=null}static setMasterVolume(e){this.mixer_&&(this.mixer_.master.volume=e)}static setMusicVolume(e){this.mixer_&&(this.mixer_.music.volume=e)}static setSFXVolume(e){this.mixer_&&(this.mixer_.sfx.volume=e)}static setUIVolume(e){this.mixer_&&(this.mixer_.ui.volume=e)}static muteBus(e,t){const s=this.mixer_?.getBus(e);s&&(s.muted=t)}static getBufferHandle(e){return this.bufferCache_.get(e)}static dispose(){this.disposed_=!0,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}static fadeIn(e,t,s){e.setVolume(0);const n=performance.now(),i=()=>{const o=(performance.now()-n)/1e3,r=Math.min(o/t,1);e.setVolume(r*s),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,s){const n=performance.now(),i=()=>{const o=(performance.now()-n)/1e3,r=Math.min(o/t,1);e.setVolume(s*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}static createDeferredHandle(){let e=null;return{id:-1,stop(){e?.stop()},pause(){e?.pause()},resume(){e?.resume()},setVolume(t){e?.setVolume(t)},setPan(t){e?.setPan(t)},setLoop(t){e?.setLoop(t)},setPlaybackRate(t){e?.setPlaybackRate(t)},get isPlaying(){return e?.isPlaying??!1},get currentTime(){return e?.currentTime??0},get duration(){return e?.duration??0},resolve(t){e=t}}}}Us.mixer_=null,Us.bufferCache_=new Map,Us.bgmHandle_=null,Us.bgmVolume_=1,Us.fadeAnimId_=0,Us.disposed_=!1;const Ws=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}],["AudioSource",{fields:[{field:"clip",type:"audio"}]}]]);function Ds(e,t){Ws.set(e,t)}function Os(e){const t=Ws.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 Ls(e){return Ws.get(e)?.fields??[]}function Hs(e){return Ws.get(e)?.spine??null}const js=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Xs(e,t){js.set(e,t)}function Ys(e){return js.get(e)}function Vs(e,t){const s=js.get(e.type);if(!s)return;const n=e.data;for(const i of s){const s=n[i];if("number"==typeof s&&0!==s){const o=t.get(s);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${s} which does not exist`),n[i]=void 0!==o?o:0}}}function Ns(e,t){const s=new Map;for(const n of t.entities){if(!1===n.visible)continue;const t=e.spawn();s.set(n.id,t),e.insert(t,Qe,{value:n.name})}for(const n of t.entities){if(!1===n.visible)continue;const t=s.get(n.id);for(const i of n.components)Vs(i,s),Js(e,t,i,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),i=s.get(n.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return s}function Gs(e,t){return Ns(e,t)}async function qs(e,t,s){const n=s?.assetServer,i=s?.assetBaseUrl??n?.baseUrl,o=new Map;n&&await async function(e,t,s,n,i){const o=new Map;for(const e of Ks.keys())o.set(e,new Set);const r=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ws.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}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...Ks.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,s,n);l.set(e,r)}),u=r.map(async e=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)});if(await Promise.all([...c,...u]),i){for(const e of n.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ws.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const n=s[e.field];if("string"!=typeof n||!n)continue;const i=t.get(n);void 0!==i&&(s[e.field]=i)}}}(t,n,i,o,s?.collectAssets);const r=Ns(e,t);if(n&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&n.setTextureMetadataByPath(t,s.sliceBorder)}return r}const Ks=new Map([["texture",{async load(e,t,s,n){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),n.set(e,o)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(o),i}}],["material",{async load(e,t,s){const n=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,s);n.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),n.set(e,0)}});return await Promise.all(i),n}}],["font",{async load(e,t,s){const n=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,s);n.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),n.set(e,0)}});return await Promise.all(i),n}}],["anim-clip",{async load(e,t,s,n){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=Cs(i),r=new Map,a=o.map(async e=>{try{const i=s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),n.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);Is(As(e,i,r))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(i),new Map}}],["audio",{async load(e,t,s){const n=[...e].map(e=>s?`${s}/${e}`:`/${e}`);return await Us.preloadAll(n).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}]]);function Js(e,t,s,n){if("LocalTransform"!==s.type&&"WorldTransform"!==s.type||(s.type="Transform"),"UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===s.type){const e=s.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=$e(s.type);if(i)e.insert(t,i,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function Qs(e,t){const s=e.getEntitiesWithComponents([Ye]);for(const n of s){const s=e.get(n,Ye);s&&(s.aspectRatio=t,e.insert(n,Ye,s))}}function Zs(e,t){const s=e.getEntitiesWithComponents([Qe]);for(const n of s){const s=e.get(n,Qe);if(s&&s.value===t)return n}return null}class en{constructor(e){this.textureCache_=new Ts,this.shaderCache_=new Ts,this.jsonCache_=new Ts,this.textCache_=new Ts,this.binaryCache_=new Ts,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Ts,this.prefabCache_=new Ts,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=d(ue.textCanvasSize,ue.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Es(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),i=this.textureCache_.get(n);if(!i)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),_s.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const i=this.resolveUrl(t,s),o=await this.fetchText(i);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=r?`${r}/${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"===T(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),i=l.find(e=>e.name===s);if(i){const s=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,i.info.width,i.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}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=T(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 i=s?`${s}/${n}`:n;return this.loadFntFile(i)}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],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${n}`:n,r=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,r.handle,r.width,r.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,async()=>{const e=await this.fetchJson(s);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const s of e.entities){for(const e of s.components){if(!e.data)continue;for(const s of Os(e.type)){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}const s=Hs(e.type);if(s)for(const n of[s.skeletonField,s.atlasField]){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}}if(s.nestedPrefab?.prefabPath){const e=t(s.nestedPrefab.prefabPath);e&&(s.nestedPrefab.prefabPath=e)}}}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const 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 qs(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 i=n.metadata?.atlas;i&&s.push(this.loadSpine(n.path,i).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return this.loadImageFromSrc(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){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=e})}createTextureFromImage(e,t){const{width:s,height:n}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,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,i){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const r=this.module_.GL,a=r.getNewId(r.textures);r.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 i=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(o);const r=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=r.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.getEmbedded(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:i}=this.parseEsShader(t);if(!n||!i)throw new Error(`Invalid shader format: ${e}`);return _s.createShader(n,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const n=await l(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:o}=this.parseEsShader(n);if(!i||!o)throw new Error(`Invalid shader format: ${e}`);return _s.createShader(i,o)}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://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(U(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await l(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await r(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.getEmbedded(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await r(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.getEmbedded(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 r(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 i="";for(const e of n){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const 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 tn=at(null,"Assets");class sn{build(e){const t=e.wasmModule;t?e.insertResource(tn,new en(t)):console.warn("AssetPlugin: No WASM module available")}}const nn=new sn;class on{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 rn(e,t){const s=e.getResource(tn);s&&s.registerEmbeddedAssets(t)}async function an(e,t,s){const{entities:n,rootId:i}=await cn(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}))},r=await qs(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=r.get(i);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:r}}const ln=10;async function cn(e,t,s,n,i,o=0){if(o>ln)throw new Error(`Prefab nesting depth exceeded ${ln}. Check for deep or circular nesting in: ${e.name}`);const r=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,a++)}const l=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(i?.has(n.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${n.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await cn(e,n.nestedPrefab.overrides,s,a,i,o+1);r.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?r.get(n.parent)??null:null),l.push(...t.entities);continue}const c=r.get(n.prefabEntityId),u=n.prefabEntityId===e.rootEntityId,d={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?null:null!==n.parent?r.get(n.parent)??null:null,children:n.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};un(d.components,r),dn(d,t),l.push(d)}const c=r.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function un(e,t){for(const s of e){const e=Ys(s.type);if(e)for(const n of e){const e=s.data[n];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(s.data[n]=i)}}}}function dn(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 hn{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,i=await this.assetServer_.loadPrefab(n,t?.baseUrl);return an(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const fn=at(null,"Prefabs");class pn{constructor(){this.name="PrefabsPlugin",this.dependencies=[tn]}build(e){const t=e.getResource(tn);e.insertResource(fn,new hn(e.world,t))}}const mn=new pn;let gn=null,_n=0,yn=0,wn=0;const xn=new Float32Array(256);function vn(e){gn=e,_n=gn._malloc(64),yn=gn._malloc(64),wn=gn._malloc(1024)}function bn(){gn&&(_n&&(gn._free(_n),_n=0),yn&&(gn._free(yn),yn=0),wn&&(gn._free(wn),wn=0)),gn=null}function Sn(){if(!gn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return gn}const Mn={r:1,g:1,b:1,a:1},Pn={begin(e){const t=Sn();try{t.HEAPF32.set(e,_n/4),t.draw_begin(_n)}catch(e){yt(e,"Draw.begin")}},end(){try{Sn().draw_end()}catch(e){yt(e,"Draw.end")}},line(e,t,s,n=1){try{Sn().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){yt(e,"Draw.line")}},rect(e,t,s,n=!0){try{Sn().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){yt(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{Sn().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){yt(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,i=32){try{Sn().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){yt(e,"Draw.circle")}},circleOutline(e,t,s,n=1,i=32){try{Sn().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){yt(e,"Draw.circleOutline")}},texture(e,t,s,n=Mn){try{Sn().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){yt(e,"Draw.texture")}},textureRotated(e,t,s,n,i=Mn){try{Sn().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,i.r,i.g,i.b,i.a)}catch(e){yt(e,"Draw.textureRotated")}},setLayer(e){Sn().draw_setLayer(e)},setDepth(e){Sn().draw_setDepth(e)},getDrawCallCount:()=>gn?gn.draw_getDrawCallCount():0,getPrimitiveCount:()=>gn?gn.draw_getPrimitiveCount():0,setBlendMode(e){Sn().draw_setBlendMode(e)},setDepthTest(e){Sn().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=Sn();n.HEAPF32.set(s,yn/4),n.draw_mesh(e,t,yn)}catch(s){yt(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=Sn(),i=_s.get(t);if(!i)return;if(Pn.setBlendMode(i.blendMode),Pn.setDepthTest(i.depthTest),0===i.uniforms.size)return void Pn.drawMesh(e,i.shader,s);let o;if(n.HEAPF32.set(s,yn/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,s]of i.uniforms){const n=Cn(t);if(!(n<0)){if(cs(s))xn[o++]=10,xn[o++]=n,xn[o++]=s.slot??e++,xn[o++]=s.textureId;else if("number"==typeof s)xn[o++]=1,xn[o++]=n,xn[o++]=s;else if(Array.isArray(s)){xn[o++]=s.length,xn[o++]=n;for(let e=0;e<s.length;e++)xn[o++]=s[e]}else"w"in s?(xn[o++]=4,xn[o++]=n,xn[o++]=s.x,xn[o++]=s.y,xn[o++]=s.z,xn[o++]=s.w):"z"in s?(xn[o++]=3,xn[o++]=n,xn[o++]=s.x,xn[o++]=s.y,xn[o++]=s.z):(xn[o++]=2,xn[o++]=n,xn[o++]=s.x,xn[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<o)&&(i.cachedBuffer_=new Float32Array(o)),i.cachedBuffer_.set(xn.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void n.draw_mesh(e,i.shader,yn);n.HEAPF32.set(i.cachedBuffer_.subarray(0,o),wn/4),n.draw_meshWithUniforms(e,i.shader,yn,wn,o)}catch(s){yt(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Tn={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},En=new Set;function Cn(e){const t=Tn[e];return void 0!==t?t:(En.has(e)||(En.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Tn).join(", ")}`)),-1)}const An=new Map;function Rn(e,t,s){An.set(e,{fn:t,scene:s??""})}function In(e){An.delete(e)}function Fn(){An.clear()}var kn;!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"}(kn||(kn={}));let Bn=null,zn=0,$n=0,Un=0;function Wn(e){Bn=e,zn=Bn._malloc(262144),$n=Bn._malloc(65536),Un=Bn._malloc(256)}function Dn(){Bn&&(zn&&Bn._free(zn),$n&&Bn._free($n),Un&&Bn._free(Un),zn=0,$n=0,Un=0),Bn=null}function On(){if(!Bn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Bn}const Ln={create(e){const t=On(),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,zn/4);const i=e.layout.length,o=new Int32Array(i);for(let t=0;t<i;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Un,i).set(o),t.geometry_init(s,zn,n,Un,i,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,$n,n).set(e.indices),t.geometry_setIndices16(s,$n,n)}else{new Uint32Array(t.HEAPU8.buffer,$n,n).set(e.indices),t.geometry_setIndices32(s,$n,n)}}return s},updateVertices(e,t,s=0){const n=On(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);n.HEAPF32.set(t,zn/4),n.geometry_updateVertices(e,zn,i,s)},release(e){e>0&&On().geometry_release(e)},isValid:e=>!(!Bn||e<=0)&&Bn.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Ln.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:kn.Float2},{name:"a_texCoord",type:kn.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 i=n/t*Math.PI*2,o=Math.cos(i)*e,r=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;s.push(o,r,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Ln.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:kn.Float2},{name:"a_texCoord",type:kn.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,i=-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),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(n-t),a=(r.y-s)/(i-s);o.push(r.x,r.y,e,a)}const r=[];for(let t=1;t<e.length-1;t++)r.push(0,t,t+1);return Ln.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:kn.Float2},{name:"a_texCoord",type:kn.Float2}],indices:new Uint16Array(r)})}};let Hn=null;function jn(e){Hn=e}function Xn(){Hn&&Vn.isInitialized()&&Vn.shutdown(),Hn=null}function Yn(){if(!Hn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Hn}const Vn={init(e,t){try{return Yn().postprocess_init(e,t)}catch(s){return yt(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Yn().postprocess_shutdown()}catch(e){yt(e,"PostProcess.shutdown")}},resize(e,t){try{Yn().postprocess_resize(e,t)}catch(s){yt(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Yn().postprocess_addPass(e,t)}catch(t){return yt(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Yn().postprocess_removePass(e)}catch(t){yt(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Yn().postprocess_setPassEnabled(e,t)}catch(t){yt(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Yn().postprocess_isPassEnabled(e)}catch(t){return yt(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{Yn().postprocess_setUniformFloat(e,t,s)}catch(s){yt(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{Yn().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){yt(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Yn().postprocess_begin()}catch(e){yt(e,"PostProcess.begin")}},end(){try{Yn().postprocess_end()}catch(e){yt(e,"PostProcess.end")}},getPassCount(){try{return Yn().postprocess_getPassCount()}catch(e){return yt(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Hn)return!1;try{return Hn.postprocess_isInitialized()}catch(e){return yt(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Yn().postprocess_setBypass(e)}catch(e){yt(e,"PostProcess.setBypass")}},isBypassed(){if(!Hn)return!0;try{return Hn.postprocess_isBypassed()}catch(e){return yt(e,"PostProcess.isBypassed"),!0}},createBlur:()=>_s.createShader(Nn,"#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:()=>_s.createShader(Nn,"#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:()=>_s.createShader(Nn,"#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:()=>_s.createShader(Nn,"#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")},Nn="#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 qn=null,Kn=0;function Jn(e){qn=e,Kn=qn._malloc(64)}function Qn(){qn&&Kn&&(qn._free(Kn),Kn=0),qn=null}const Zn={init(e,t){qn?.renderer_init(e,t)},resize(e,t){qn?.renderer_resize(e,t)},begin(e,t){if(qn&&Kn)try{qn.HEAPF32.set(e,Kn/4),qn.renderer_begin(Kn,t??0)}catch(e){yt(e,"Renderer.begin")}},flush(){try{qn?.renderer_flush()}catch(e){yt(e,"Renderer.flush")}},end(){try{qn?.renderer_end()}catch(e){yt(e,"Renderer.end")}},submitSprites(e){if(qn)try{qn.renderer_submitSprites(e._cpp)}catch(e){yt(e,"Renderer.submitSprites")}},submitBitmapText(e){if(qn)try{qn.renderer_submitBitmapText(e._cpp)}catch(e){yt(e,"Renderer.submitBitmapText")}},submitSpine(e){if(qn)try{qn.renderer_submitSpine?.(e._cpp)}catch(e){yt(e,"Renderer.submitSpine")}},setStage(e){qn?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>qn?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){qn?.renderer_releaseTarget(e)},getTargetTexture:e=>qn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>qn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){qn?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){qn?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,i){qn?.renderer_setScissor(e,t,s,n,i)},clearBuffers(e){qn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>qn?qn.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>qn?{drawCalls:qn.renderer_getDrawCalls(),triangles:qn.renderer_getTriangles(),sprites:qn.renderer_getSprites(),text:qn.renderer_getText(),spine:qn.renderer_getSpine?.()??0,meshes:qn.renderer_getMeshes(),culled:qn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let ei=null;function ti(e){ei=e}function si(){ei=null}const ni={enable(){ei?.gl_enableErrorCheck(!0)},disable(){ei?.gl_enableErrorCheck(!1)},check:e=>ei?.gl_checkErrors(e)??0,diagnose(){ei?.renderer_diagnose()}};class ii{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:i,elapsed:o}=e;n===this.lastWidth_&&i===this.lastHeight_||(Zn.resize(n,i),Vn.isInitialized()&&Vn.getPassCount()>0&&Vn.resize(n,i),this.lastWidth_=n,this.lastHeight_=i),Zn.setViewport(0,0,n,i),Zn.clearBuffers(3),Zn.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,i),Zn.submitSprites(t),Zn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Zn.submitSpine(t),Zn.flush(),this.executeDrawCallbacks(s,o),Zn.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:i,elapsed:o}=e;Zn.setViewport(n.x,n.y,n.w,n.h),Zn.setScissor(n.x,n.y,n.w,n.h,!0),Zn.clearBuffers(i),Zn.setScissor(0,0,0,0,!1),Zn.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Zn.submitSprites(t),Zn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Zn.submitSpine(t),Zn.flush(),this.executeDrawCallbacks(s,o),Zn.end()}executeDrawCallbacks(e,t){const s=An;if(s.size>0){Pn.begin(e);const n=[];for(const[e,i]of s.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}Pn.end();for(const e of n)In(e)}}}const oi="__scene_transition_overlay__";class ri{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class ai{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,Ze,{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),Rn(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Vn.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Vn.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,Ze)){const s=this.app_.world.get(e,Ze);s.persistent=t,this.app_.world.insert(e,Ze,s)}}}class li{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??ue.sceneTransitionDuration,i=t.color??{...ue.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:i,targetScene:e,options:t,resolve:s},Rn(oi,()=>{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;Pn.setLayer(9999),Pn.setDepth(9999),Pn.rect({x:0,y:0},{x:2e4,y:2e4},{r:i.r,g:i.g,b:i.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()=>{try{s&&s!==e&&await this.unload(s,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,In(oi),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,In(oi),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new ri(t);this.scenes_.set(e,s);const n=new ai(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(tn)?this.app_.getResource(tn):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(s,e,t,i),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new ri(t);this.scenes_.set(e,s);const n=new ai(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(tn)?this.app_.getResource(tn):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(s,e,t,i),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const i=t?.keepPersistent??!0;for(const e of s.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,Ze)){if(this.app_.world.get(e,Ze).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())In(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Vn.removePass(e)}catch{}s.postProcessPasses.length=0,this.releaseSceneAssets_(s),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)}async loadSceneData_(e,t,s,n){if(n){const s={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:s};this.app_.hasResource(tn)&&(i.assetServer=this.app_.getResource(tn));const o=await qs(this.app_.world,n,i);e.loadedAssets=s;for(const s of o.values())e.entities.add(s),this.app_.world.insert(s,Ze,{scene:t,persistent:!1})}if(s.systems)for(const{schedule:e,system:n}of s.systems){const s=ui(this.app_,t,n);this.app_.addSystemToSchedule(e,s)}const i=this.contexts_.get(t);s.setup&&await s.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const s=this.app_.hasResource(tn)?this.app_.getResource(tn):null;if(s){for(const e of t.textureUrls)s.releaseTexture(e);for(const e of t.fontPaths)s.releaseFont(e);for(const e of t.spineKeys)s.releaseSpine(e)}for(const e of t.materialHandles)_s.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n={};let i=!1;if(s.has(e,Xe)){const t=s.get(e,Xe);n.sprite=t.color.a,t.color.a=0,s.insert(e,Xe,t),i=!0}if(s.has(e,Je)){const t=s.get(e,Je);n.spine=t.color.a,t.color.a=0,s.insert(e,Je,t),i=!0}if(s.has(e,Ke)){const t=s.get(e,Ke);n.bitmapText=t.color.a,t.color.a=0,s.insert(e,Ke,t),i=!0}i&&t.savedAlphas.set(e,n)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n=t.savedAlphas.get(e);if(n){if(void 0!==n.sprite&&s.has(e,Xe)){const t=s.get(e,Xe);t.color.a=n.sprite,s.insert(e,Xe,t)}if(void 0!==n.spine&&s.has(e,Je)){const t=s.get(e,Je);t.color.a=n.spine,s.insert(e,Je,t)}if(void 0!==n.bitmapText&&s.has(e,Ke)){const t=s.get(e,Ke);t.color.a=n.bitmapText,s.insert(e,Ke,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{Vn.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 ci=at(null,"SceneManager");function ui(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(ci).getSceneStatus(t)&&s._fn(...n)}}}const di=Jt([ct(ci),lt(ht)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),hi={name:"SceneManager",build(e){const t=new li(e);e.insertResource(ci,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(ci),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Gt.Startup,s),e.addSystemToSchedule(Gt.Last,di)}};class fi{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new jt,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=h(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(Gt.Last);else{this.runSchedule(Gt.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Gt.FixedPreUpdate),this.runSchedule(Gt.FixedUpdate),this.runSchedule(Gt.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(Gt.PreUpdate),this.runSchedule(Gt.Update),this.runSchedule(Gt.PostUpdate),this.runSchedule(Gt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new Pt,this.resources_=new dt;for(const e of Object.values(Gt))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new fi}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(Gt.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Gt.Startup,e)}removeSystem(e){let t=!1;for(const[s,n]of this.systems_){const i=n.filter(t=>t.system._id!==e);i.length!==n.length&&(this.systems_.set(s,i),this.sortedSystemsCache_.delete(s),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return _t(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}enableStats(){return this.statsEnabled_=!0,this.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}getEntityCount(){return this.world_.entityCount()}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(ci).register(e),this}setInitialScene(e){return this.getResource(ci).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new ss(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(ht)||this.resources_.insert(ht,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(Gt.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(Gt.Last);else{this.runSchedule(Gt.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Gt.FixedPreUpdate),this.runSchedule(Gt.FixedUpdate),this.runSchedule(Gt.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(Gt.PreUpdate),this.runSchedule(Gt.Update),this.runSchedule(Gt.PostUpdate),this.runSchedule(Gt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new ss(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(ht,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(Gt.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1,Fn();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[si,Qn,Xn,Dn,ms,bn];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let 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 i=t.get(n);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,i=new Set,o=r=>{if(n.has(r))return;if(i.has(r)){const t=e[r].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(r);const a=e[r];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}i.delete(r),n.add(r),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));const n=this.phaseTimings_?performance.now():0;for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}this.phaseTimings_&&this.phaseTimings_.set(Gt[e],performance.now()-n)}updateTime(e){const t=this.resources_.get(ht);t.delta=e,t.elapsed+=e,t.frameCount++}}function pi(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const mi=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function gi(e,t,s,n,i){const o=e*t/s,r=e;switch(n){case Oe.FixedWidth:return o;case Oe.FixedHeight:return r;case Oe.Expand:return Math.max(o,r);case Oe.Shrink:return Math.min(o,r);case Oe.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const _i=[];function yi(e){if(e<_i.length)return _i[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return _i.push(t),t}function wi(e,t,s,n,i,o){if(0===s||0===n)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,Ze);return!t||""===t.scene||o.has(t.scene)}):r;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 i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*s/(i.viewportH*n);let a,u=0,d=0;if(i.projectionType===We.Orthographic){if(d=i.orthoSize,l){d=gi(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=d*r,a=vi(-u,u,-d,d,-i.farPlane,i.farPlane)}else a=Si(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const h=Pi(o.position.x,o.position.y,o.position.z),f=yi(c.length);f.entity=e,f.viewProjection.set(Ei(a,h)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=u,f.halfH=d,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const xi=new Float32Array(16);function vi(e,t,s,n,i,o){const r=xi;r.fill(0);const a=t-e,l=n-s,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(n+s)/l,r[14]=-(o+i)/c,r[15]=1,r}const bi=new Float32Array(16);function Si(e,t,s,n){const i=bi;i.fill(0);const o=1/Math.tan(e/2),r=s-n;return i[0]=o/t,i[5]=o,i[10]=(n+s)/r,i[11]=-1,i[14]=2*n*s/r,i}const Mi=new Float32Array(16);function Pi(e,t,s){const n=Mi;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 Ti=new Float32Array(16);function Ei(e,t){const s=Ti;for(let n=0;n<4;n++)for(let i=0;i<4;i++)s[4*i+n]=e[0+n]*t[4*i+0]+e[4+n]*t[4*i+1]+e[8+n]*t[4*i+2]+e[12+n]*t[4*i+3];return s}const Ci={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function Ai(e,t,s,n,i,o,r={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,u=o.left+t.x*a,d=o.bottom+e.y*l,h=o.bottom+t.y*l;let f,p,m,g;e.x===t.x?(f=c+s.x-i.x*r.x,m=f+i.x):(f=c+s.x,m=u+n.x),e.y===t.y?(p=d+s.y-i.y*r.y,g=p+i.y):(p=d+s.y,g=h+n.y);const _=Math.max(0,m-f),y=Math.max(0,g-p);return{originX:f+r.x*_,originY:p+r.y*y,width:_,height:y,rect:{left:f,bottom:p,right:m,top:g}}}const Ri=Ue("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});let Ii=null,Fi=null;function ki(e,t){e.has(t,Xe)||e.insert(t,Xe,{texture:me,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0})}function Bi(e,t){switch(e){case Ci.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Ci.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Ci.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function zi(e,t){switch(e){case Ci.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case Ci.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case Ci.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1-t}};default:return{anchorMin:{x:t,y:0},anchorMax:{x:t,y:1}}}}function $i(e,t,s,n){switch(e){case Ci.BottomToTop:case Ci.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}}function Ui(e,t,s,n){if(!e.has(t,Ri))return;const i=e.get(t,Ri),o=Bi(s,n);i.anchorMin=o.anchorMin,i.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(i.size={...i.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,Ri,i)}function Wi(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Di(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Oi(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),i=[];for(const t of n){if(!t){i.push("");continue}let n="";for(let o=0;o<t.length;o++){const r=t[o],a=n+r;if(e.measureText(a).width>s&&n){if(Di(r.charCodeAt(0))&&n.length>0&&Di(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!Di(n.charCodeAt(t))){e=t;break}e>=0?(i.push(n.substring(0,e+1)),n=n.substring(e+1)+r):(i.push(n),n=r)}else i.push(n),n=r}else n=a}n&&i.push(n)}return i.length>0?i:[""]}function Li(e){let t=1;for(;t<e;)t*=2;return t}function Hi(e,t){let s=0,n=t;for(;e.has(n,Ge);){const t=e.get(n,Ge).entity;if(!e.valid(t))break;s++,n=t}return s}function ji(e,t){if(Ii&&Fi){const e=Ii.getUIRectComputedWidth(Fi,t);if(e>0)return e}return e.size.x}function Xi(e,t){if(Ii&&Fi){const e=Ii.getUIRectComputedHeight(Fi,t);if(e>0)return e}return e.size.y}function Yi(e,t,s,n,i,o){if(!e.has(t,Xe))return;const r=e.get(t,Xe);let a,l;switch(s){case Ci.BottomToTop:case Ci.TopToBottom:a=i,l=o*n;break;default:a=i*n,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,Xe,r))}function Vi(e,t,s){let n=t;for(;e.has(n,Ge);){const t=e.get(n,Ge).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function Ni(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function Gi(e,t,s,n,i){if(!e.has(t,Ri))return;const o=e.get(t,Ri),r=Ai(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s,o.pivot),a=r.rect.right-r.rect.left,l=r.rect.top-r.rect.bottom;if(e.has(t,Xe)){const s=e.get(t,Xe);s.size.x===a&&s.size.y===l||(s.size.x=a,s.size.y=l,e.insert(t,Xe,s))}if(e.has(t,Le)){const s=e.get(t,Le);s.position.x=r.originX-n,s.position.y=r.originY-i,e.insert(t,Le,s)}}function qi(e){const t=Object.keys(e),s=t.map(t=>e[t]);return{take(e){const n={};for(let i=0;i<t.length;i++)n[t[i]]=s[i](e);return n},changed(e,n){for(let i=0;i<t.length;i++)if(e[t[i]]!==s[i](n))return!0;return!1},update(e,n){for(let i=0;i<t.length;i++)e[t[i]]=s[i](n)}}}const Ki=.1,Ji=30,Qi={r:.3,g:.5,b:.8,a:1},Zi={Left:0,Center:1,Right:2},eo={Top:0,Middle:1,Bottom:2},to={Visible:0,Clip:1,Ellipsis:2},so=Ee("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Zi.Left,verticalAlign:eo.Top,wordWrap:!0,overflow:to.Visible,lineHeight:1.2});class no{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=d(ue.textCanvasSize,ue.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,Li(this.frameMaxW_)),e.height=Math.max(e.height,Li(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Li(this.frameMaxW_),e.height=Li(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,o=i?t.size.x:0,r=i?t.size.y:0,a=e.wordWrap&&i;let l=Oi(s,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=i?Math.ceil(o):d+2*u,p=i?Math.ceil(r):h+2*u;if(i&&e.overflow===to.Ellipsis&&h>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(n.width<f||n.height<p)&&(n.width=Math.max(n.width,Li(f)),n.height=Math.max(n.height,Li(p)));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;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${m}, ${g}, ${_}, ${y})`,i&&e.overflow===to.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const w=l.length*c;let x;if(i){switch(e.verticalAlign){case eo.Top:x=u;break;case eo.Middle:x=u+(p-2*u-w)/2;break;case eo.Bottom:x=p-w-u;break;default:x=u}x<0&&(x=0)}else x=u;let v=x;for(const t of l){let n;switch(e.align){case Zi.Left:n=u;break;case Zi.Center:n=f/2;break;case Zi.Right:n=f-u;break;default:n=u}s.fillText(t,n,v),v+=c}i&&e.overflow===to.Clip&&s.restore();const b=s.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),M=this.module.getResourceManager(),P=this.module._malloc(S.length);this.module.HEAPU8.set(S,P);const T=M.createTexture(f,p,P,S.length,1,!0);return this.module._free(P),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let 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 i=this.renderText(t,s);return this.cache.set(e,i),i}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}measureWidth(e){let t=0;for(const s of e)t=Math.max(t,this.ctx.measureText(s).width);return t}mapAlign(e){switch(e){case Zi.Left:return"left";case Zi.Center:return"center";case Zi.Right:return"right"}}}const io=qi({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?ji(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Xi(e.uiRect,e.entity):0});class oo{build(e){ze("Text",so);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new no(t),n=e.world,i=new Map;e.addSystemToSchedule(Gt.PreUpdate,Jt([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,so));for(const e of i.keys())if(!n.valid(e)||!n.has(e,so)){if(n.valid(e)&&n.has(e,Xe)){const t=n.get(e,Xe);n.insert(e,Xe,{texture:me,color:{r:t.color.r,g:t.color.g,b:t.color.b,a:t.color.a},size:{x:t.size.x,y:t.size.y},uvOffset:{x:t.uvOffset.x,y:t.uvOffset.y},uvScale:{x:t.uvScale.x,y:t.uvScale.y},layer:t.layer,flipX:t.flipX,flipY:t.flipY,material:t.material,enabled:t.enabled})}i.delete(e)}const e=n.getEntitiesWithComponents([so]);for(const t of e){const e=n.get(t,so),o=n.has(t,Ri)?n.get(t,Ri):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!io.changed(a,r)){if(n.has(t,Xe)&&n.get(t,Xe).texture!==me)continue}ki(n,t);const l=o?{size:{x:ji(o,t),y:Xi(o,t)}}:null,c=s.renderForEntity(t,e,l),u=n.get(t,Xe);n.insert(t,Xe,{texture:c.textureHandle,color:{r:u.color.r,g:u.color.g,b:u.color.b,a:u.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:u.layer,flipX:u.flipX,flipY:u.flipY,material:u.material,enabled:u.enabled}),i.set(t,io.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const ro=new oo,ao=0,lo=1,co=Ue("UIMask",{enabled:!0,mode:ao});function uo(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),i=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,i-s),h:Math.max(0,o-n)}}function ho(e,t){const s=t??new Float32Array(16),n=e[0],i=e[1],o=e[2],r=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=n*l-i*a,x=n*c-o*a,v=n*u-r*a,b=i*c-o*l,S=i*u-r*l,M=o*u-r*c,P=d*g-h*m,T=d*_-f*m,E=d*y-p*m,C=h*_-f*g,A=h*y-p*g,R=f*y-p*_;let I=w*R-x*A+v*C+b*E-S*T+M*P;return 0===I||(I=1/I,s[0]=(l*R-c*A+u*C)*I,s[1]=(o*A-i*R-r*C)*I,s[2]=(g*M-_*S+y*b)*I,s[3]=(f*S-h*M-p*b)*I,s[4]=(c*E-a*R-u*T)*I,s[5]=(n*R-o*E+r*T)*I,s[6]=(_*v-m*M-y*x)*I,s[7]=(d*M-f*v+p*x)*I,s[8]=(a*A-l*E+u*P)*I,s[9]=(i*E-n*A-r*P)*I,s[10]=(m*S-g*v+y*w)*I,s[11]=(h*v-d*S-p*w)*I,s[12]=(l*T-a*C-c*P)*I,s[13]=(n*C-i*T+o*P)*I,s[14]=(g*x-m*b-_*w)*I,s[15]=(d*b-h*x+f*w)*I),s}function fo(e,t,s,n,i,o,r){const a=(e-n)/o*2-1,l=(t-i)/r*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 po(e,t,s,n,i,o,r,a){return e>=s-i*r&&e<=s+i*(1-r)&&t>=n-o*a&&t<=n+o*(1-a)}function mo(e,t){return 2*Math.atan2(e,t)}function go(e,t,s,n,i,o,r){const a=s[0]*e+s[4]*t+s[12],l=s[1]*e+s[5]*t+s[13],c=s[3]*e+s[7]*t+s[15];return[n+(.5*(a/c)+.5)*o,i+(.5*(l/c)+.5)*r]}function _o(e,t,s,n,i,o,r,a,l,c){const u=mo(l,c),d=Math.sin(-u),h=Math.cos(-u),f=e-s,p=t-n,m=f*h-p*d+s,g=f*d+p*h+n;return m>=s-i*r&&m<=s+i*(1-r)&&g>=n-o*a&&g<=n+o*(1-a)}function yo(e,t,s,n,i,o,r){if(!e.has(t,Ri)||!e.has(t,Le))return null;const a=e.get(t,Ri),l=e.get(t,Le),c=ji(a,t)*l.worldScale.x,u=Xi(a,t)*l.worldScale.y,d=l.worldPosition.x,h=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,m=-c*f,g=c*(1-f),_=-u*p,y=u*(1-p),w=mo(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[d+m*x-_*v,h+m*v+_*x],[d+g*x-_*v,h+g*v+_*x],[d+g*x-y*v,h+g*v+y*x],[d+m*x-y*v,h+m*v+y*x]];let S=1/0,M=1/0,P=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=go(e,t,s,n,i,o,r);S=Math.min(S,a),M=Math.min(M,l),P=Math.max(P,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(M),w:Math.round(P-S),h:Math.round(T-M)}}function wo(e,t){return(s,n,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([co]);if(0===l.length)return;const c=[],u=[],d=new Set,h=new Set;for(const e of l){const s=t.get(e,co);s.enabled&&(d.add(e),s.mode===lo?(u.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,i,o,r,a,l,c){const u=[];for(const e of n){let s=!0;Vi(t,e,e=>{if(i.has(e)){if(t.get(e,co).mode===ao)return s=!1,!0}return!1}),s&&u.push(e)}function d(n,u){const h=e.getChildEntities(s,n);for(const s of h){let n=u;if(i.has(s)){if(t.get(s,co).mode===ao){const e=yo(t,s,o,r,a,l,c);e&&(n=uo(u,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=yo(t,e,o,r,a,l,c);s&&d(e,s)}}(e,t,s,c,d,n,i,o,r,a),u.length>0&&function(e,t,s,n,i){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0;Vi(t,e,e=>!!i.has(e)&&(s=!1,!0)),s&&o.push(e)}let r=1,a=!1;function l(){return r>255?(a||console.warn("Stencil mask overflow"),a=!0,null):r++}function c(t,n){if(a)return;e.renderer_setEntityStencilMask(t,n);const o=e.getChildEntities(s,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),u(t,n)}function u(t,n){if(a)return;const o=e.getChildEntities(s,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),u(t,n)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,s,u,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class xo{build(e){if(ze("UIMask",co),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(wo(e.wasmModule,e.world))}}const vo=new xo,bo=Ue("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),So=Ue("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Mo={Normal:0,Hovered:1,Pressed:2,Disabled:3},Po=Ee("Button",{state:Mo.Normal,transition:null});class To{constructor(){this.events_=[]}emit(e,t,s){const n=s??e;this.events_.push({entity:e,type:t,target:n,currentTarget:e})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const Eo=at(new To,"UIEvents");class Co{build(e){ze("UIRect",Ri);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){Ii=e,Fi=t}(s,n);e.addSystemToSchedule(Gt.PreUpdate,Jt([lt(as)],e=>{e.valid&&(s.uiLayout_update(n,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),s.uiFlexLayout_update(n),s.transform_update(n))},{name:"UILayoutSystem"})),e.addSystemToSchedule(Gt.PostUpdate,Jt([lt(as)],e=>{e.valid&&(s.uiLayout_update(n,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),s.uiFlexLayout_update(n))},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(Gt.PostUpdate,Jt([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const Ao=new Co;let Ro=!1,Io=!1;function Fo(e){Ro=e}function ko(){return Ro}function Bo(){return!Ro}function zo(e){Io=e}function $o(){return Io}const Uo=function(){const e=new Float32Array(16),t=new Float32Array(16);let s=!0;return{update(e){for(let n=0;n<16;n++)if(t[n]!==e[n]){t.set(e),s=!0;break}},getInverse:t=>(s&&(ho(t,e),s=!1),e)}}();function Wo(e,t,s,n){t.emit(s,n,s),Vi(e,s,i=>{if(!e.has(i,bo))return!1;const o=e.get(i,bo);return o.enabled&&t.emit(i,n,s),o.blockRaycast})}class Do{build(e){ze("Interactable",bo),ze("Button",Po);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),i=new To;e.insertResource(Eo,i);let o=null,r=null;e.addSystemToSchedule(Gt.PreUpdate,Jt([lt(is),lt(as)],(e,a)=>{if(i.drain(),ko()&&!$o())return;const l=t.getEntitiesWithComponents([So]);for(const e of l){const s=t.get(e,So);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,So,s))}if(!a.valid)return;const c=f(),u=e.mouseX*c,d=a.screenH-e.mouseY*c;Uo.update(a.viewProjection);const h=fo(u,d,Uo.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=h.x,a.worldMouseY=h.y;const p=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),g=e.isMouseButtonReleased(0);s.uiHitTest_update(n,h.x,h.y,p,m,g);const _=s.uiHitTest_getHitEntity(),y=4294967295===_?null:_;if(null===o||t.valid(o)||(o=null),o!==y){if(null!==o&&t.valid(o)&&t.has(o,So)){const e=t.get(o,So);e.hovered=!1,t.insert(o,So,e),i.emit(o,"hover_exit")}if(null!==y){Ni(t,y,So);const e=t.get(y,So);e.hovered=!0,t.insert(y,So,e),i.emit(y,"hover_enter")}o=y}if(m&&null!==y){const e=t.get(y,So);e.pressed=!0,e.justPressed=!0,t.insert(y,So,e),r=y,Wo(t,i,y,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,So)){const e=t.get(r,So);e.pressed=!1,e.justReleased=!0,t.insert(r,So,e),Wo(t,i,r,"release"),r===o&&Wo(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(Gt.Update,Jt([],()=>{const e=t.getEntitiesWithComponents([Po]);for(const s of e){if(Ni(t,s,bo,{enabled:!0}),!t.has(s,So))continue;const e=t.get(s,So),n=t.get(s,Po),i=t.get(s,bo),o=!a.has(s),r=n.state;if(i.enabled?e.pressed?n.state=Mo.Pressed:e.hovered?n.state=Mo.Hovered:n.state=Mo.Normal:n.state=Mo.Disabled,o&&a.add(s),(o||r!==n.state)&&n.transition&&t.has(s,Xe)){const o=t.get(s,Xe);o.color=Wi(n.transition,i.enabled,e.pressed,e.hovered),t.insert(s,Xe,o)}}},{name:"ButtonSystem"}))}}const Oo=new Do,Lo=Ee("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}),Ho=Ee("Focusable",{tabIndex:0,isFocused:!1});class jo{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Xo=at(new jo,"FocusManager");class Yo{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(ze("TextInput",Lo),ko()&&!$o())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,i=d(ue.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=0,a=0,l=!1,c=!0,u=0,h=0;const f=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!f)return;const p=f;function m(){const t=e.getResource(Xo);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,Lo)?n:null}const g=()=>{l||null===m()||v()},_=()=>{l=!0},y=()=>{l=!1,v()},w=t=>{const n=m();if(null===n)return;if("Escape"===t.key)return void b();const i=s.get(n,Lo);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(Eo).emit(n,"submit"),void b()}let o=i.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?o=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=i.value.length),o!==i.cursorPos&&(i.cursorPos=o,p.selectionStart=o,p.selectionEnd=o,i.dirty=!0,S())},x=()=>{const t=m();if(null!==t){const n=s.get(t,Lo);n.focused=!1,n.dirty=!0;e.getResource(Xo).blur()}};function v(){const t=m();if(null===t)return;const n=s.get(t,Lo);if(n.readOnly)return;let i=p.value;if(n.maxLength>0&&i.length>n.maxLength&&(i=i.substring(0,n.maxLength),p.value=i),i!==n.value){n.value=i;e.getResource(Eo).emit(t,"change")}n.cursorPos=p.selectionStart??i.length,n.dirty=!0,S()}function b(){const t=m();if(null!==t){const e=s.get(t,Lo);e.focused=!1,e.dirty=!0}e.getResource(Xo).blur(),p.blur()}function S(){c=!0,u=0}p.addEventListener("input",g),p.addEventListener("compositionstart",_),p.addEventListener("compositionend",y),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",g),p.removeEventListener("compositionstart",_),p.removeEventListener("compositionend",y),p.removeEventListener("keydown",w),p.removeEventListener("blur",x),p.remove();const e=t.getResourceManager();for(const t of n.values())e.releaseTexture(t);n.clear(),0!==r&&(t._free(r),r=0,a=0)};let M=null;function P(e,l,u,d){(i.width<u||i.height<d)&&(i.width=Li(Math.max(i.width,u)),i.height=Li(Math.max(i.height,d))),o.clearRect(0,0,i.width,i.height);const h=l.backgroundColor;o.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,o.fillRect(0,0,u,d),o.save(),o.beginPath(),o.rect(l.padding,0,u-2*l.padding,d),o.clip(),o.font=`${l.fontSize}px ${l.fontFamily}`,o.textBaseline="top",o.textAlign="left";const f=0===l.value.length,p=f?l.placeholder:l.password?"●".repeat(l.value.length):l.value,m=f?l.placeholderColor:l.color;o.fillStyle=`rgba(${Math.round(255*m.r)}, ${Math.round(255*m.g)}, ${Math.round(255*m.b)}, ${m.a})`;const g=Math.ceil(1.2*l.fontSize),_=l.padding;if(l.multiline){const e=Oi(o,p,u-2*_);let t=_;for(const s of e)o.fillText(s,_,t),t+=g}else{const e=(d-l.fontSize)/2;o.fillText(p,_,e)}if(l.focused&&c){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,s,n;if(l.multiline){const e=Oi(o,l.value,u-2*_);let i=0,r=0,a=0;for(let t=0;t<e.length;t++){const s=e[t].length;if(i+s>=l.cursorPos){r=t,a=l.cursorPos-i;break}i+=s,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,r=t+1,a=0}const c=r<e.length?e[r].substring(0,a):"";t=_+o.measureText(c).width,s=_+r*g,n=g}else t=_+o.measureText(e).width,s=(d-l.fontSize)/2,n=l.fontSize;o.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,o.fillRect(t,s,2,n)}o.restore();const y=o.getImageData(0,0,u,d),w=new Uint8Array(y.data.buffer),x=t.getResourceManager();w.length>a&&(0!==r&&t._free(r),r=t._malloc(w.length),a=w.length),t.HEAPU8.set(w,r);const v=n.get(e);void 0!==v&&x.releaseTexture(v);const b=x.createTexture(u,d,r,w.length,1,!0);n.set(e,b);const S=s.get(e,Xe);S.texture=b,S.size.x=u,S.size.y=d,S.uvOffset.x=0,S.uvOffset.y=0,S.uvScale.x=1,S.uvScale.y=1,S.color={r:1,g:1,b:1,a:1},s.insert(e,Xe,S)}e.addSystemToSchedule(Gt.Update,Jt([lt(Xo)],e=>{const t=s.getEntitiesWithComponents([Lo]);for(const e of t)Ni(s,e,Ho,{tabIndex:0,isFocused:!1}),Ni(s,e,bo,{enabled:!0,blockRaycast:!0});const n=m();if(n!==M){if(null!==M&&s.valid(M)&&s.has(M,Lo)){const e=s.get(M,Lo);e.focused=!1,e.dirty=!0,p.blur()}null!==n&&function(e){const t=s.get(e,Lo);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),S())}(n),M=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(Gt.PreUpdate,Jt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===h?0:(e-h)/1e3;h=e,i=Math.min(i,.1);const o=m();if(null!==o&&(u+=i,u>=.5)){u-=.5,c=!c;s.get(o,Lo).dirty=!0}const r=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Lo)||(r.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Lo,Ri]);for(const e of a){const t=s.get(e,Lo);if(!t.dirty)continue;const n=s.get(e,Ri),i=Math.ceil(n.size.x),o=Math.ceil(n.size.y);i<=0||o<=0||(ki(s,e),P(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Vo=new Yo,No={Simple:0,Sliced:1,Tiled:2,Filled:3},Go={Horizontal:0,Vertical:1},qo={Left:0,Right:1,Bottom:2,Top:3},Ko=Ee("Image",{texture:me,color:{r:1,g:1,b:1,a:1},imageType:No.Simple,fillMethod:Go.Horizontal,fillOrigin:qo.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Jo=qi({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,layer:e=>e.image.layer,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?ji(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Xi(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class Qo{build(e){ze("Image",Ko);const t=e.world,s=new Map;e.addSystemToSchedule(Gt.PreUpdate,Jt([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,Ko)||s.delete(e);const e=t.getEntitiesWithComponents([Ko]);for(const n of e){const e=t.get(n,Ko),i=t.has(n,Ri)?t.get(n,Ri):null,o={image:e,uiRect:i,entity:n},r=s.get(n);if(r&&!Jo.changed(r,o))continue;ki(t,n);const a=t.get(n,Xe);if(e.enabled){if(a.texture=e.texture,a.color.r=e.color.r,a.color.g=e.color.g,a.color.b=e.color.b,a.color.a=e.color.a,a.layer=e.layer,a.material=e.material,i&&(a.size.x=ji(i,n),a.size.y=Xi(i,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===No.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===Go.Horizontal?e.fillOrigin===qo.Left?(a.uvScale.x=t,a.size.x=s*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=s*t):e.fillOrigin===qo.Bottom?(a.uvScale.y=t,a.size.y=n*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=n*t)}else e.imageType===No.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale.x=a.size.x/e.tileSize.x,a.uvScale.y=a.size.y/e.tileSize.y);t.insert(n,Xe,a),s.set(n,Jo.take(o))}else a.color.a=0,t.insert(n,Xe,a),s.set(n,Jo.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const Zo=new Qo,er=Ee("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),tr=Ee("ToggleGroup",{allowSwitchOff:!1});class sr{build(e){ze("Toggle",er),ze("ToggleGroup",tr);const t=e.world,s=new Set;e.addSystemToSchedule(Gt.Update,Jt([lt(Eo)],e=>{const n=t.getEntitiesWithComponents([er]);if(!ko()||$o()){const i=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,er);n.isOn&&0!==n.group&&t.valid(n.group)&&(i.has(n.group)?(n.isOn=!1,t.insert(e,er,n)):i.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,er);if(0!==s.group&&t.valid(s.group)){let t=o.get(s.group);t||(t=[],o.set(s.group,t)),t.push(e)}}for(const s of n){if(Ni(t,s,bo,{enabled:!0}),!t.has(s,So))continue;const n=t.get(s,So),i=t.get(s,er),r=t.get(s,bo);if(n.justPressed&&r.enabled){const n=i.group,r=0!==n&&t.valid(n)&&t.has(n,tr);if(i.isOn&&r){if(!t.get(n,tr).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(s,er,i),i.isOn&&r){const i=o.get(n);if(i)for(const n of i){if(n===s)continue;const i=t.get(n,er);i.isOn&&(i.isOn=!1,t.insert(n,er,i),e.emit(n,"change"))}}e.emit(s,"change")}if(i.transition&&t.has(s,Xe)){const e=t.get(s,Xe);e.color=Wi(i.transition,r.enabled,n.pressed,n.hovered),t.insert(s,Xe,e)}}}for(const e of n){const s=t.get(e,er);if(s.graphicEntity&&t.valid(s.graphicEntity)&&t.has(s.graphicEntity,Xe)){const e=t.get(s.graphicEntity,Xe);e.enabled=s.isOn,t.insert(s.graphicEntity,Xe,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const nr=new sr,ir=Ci,or=Ee("ProgressBar",{value:0,fillEntity:0,direction:Ci.LeftToRight});function rr(e,t,s,n){if(!e.has(t,Ri))return;const i=e.get(t,Ri),o=s/2,r=n/2,a={left:-o,bottom:-r,right:o,top:r},l=Ai(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,Xe)){const s=e.get(t,Xe);s.size.x===l.width&&s.size.y===l.height||(s.size.x=l.width,s.size.y=l.height,e.insert(t,Xe,s))}if(e.has(t,Le)){const s=e.get(t,Le),n=s.position;n.x===l.originX&&n.y===l.originY||(s.position={x:l.originX,y:l.originY,z:n.z},e.insert(t,Le,s))}}class ar{build(e){ze("ProgressBar",or);const t=e.world;e.addSystemToSchedule(Gt.PreUpdate,Jt([],()=>{const e=t.getEntitiesWithComponents([or,Ri]);for(const s of e){const e=t.get(s,or);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,Ri),i=Math.max(0,Math.min(1,e.value));Ui(t,e.fillEntity,e.direction,i);const o=ji(n,s),r=Xi(n,s);rr(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const lr=new ar,cr=Ee("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),ur=Ee("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});class dr{build(e){ze("Draggable",cr),ze("DragState",ur);const t=e.world,s=e.getResource(Eo);let n=null,i={x:0,y:0},o=null;e.addSystemToSchedule(Gt.PreUpdate,Jt([lt(is),lt(as)],(e,r)=>{if(ko()&&!$o())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([cr,So]);let s=null,o=-1/0,r=-1;for(const n of e){if(!t.get(n,cr).enabled)continue;if(t.get(n,So).hovered){let e=0;t.has(n,Xe)&&(e=t.get(n,Xe).layer);const i=Hi(t,n);(e>o||e===o&&i>=r)&&(o=e,r=i,s=n)}}if(null!==s){n=s,i={x:a.x,y:a.y},t.has(s,ur)||t.insert(s,ur);const e=t.get(s,ur),o=t.get(s,Le);e.startWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.currentWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==n&&!e.isMouseButtonDown(0)){if(t.valid(n)&&t.has(n,ur)){t.get(n,ur).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),u=t.get(n,cr);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=n,n=null;t.get(o,ur).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,ur))return void(o=null);const n=t.get(o,ur),i=t.get(o,cr),r=a.x-n.pointerStartWorld.x,l=a.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+r,u=n.startWorldPos.y+l;const d=function(e,t,s,n){let i=e.lockX?t.startWorldPos.x:s,o=e.lockY?t.startWorldPos.y:n;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:i,y:o}}(i,n,c,u);c=d.x,u=d.y;const h=n.currentWorldPos.x,f=n.currentWorldPos.y;if(n.deltaWorld={x:c-h,y:u-f},n.currentWorldPos={x:c,y:u},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:u-n.startWorldPos.y},t.has(o,Le)){const e=function(e,t,s,n){if(!e.has(t,Ge))return{x:s,y:n};const i=e.get(t,Ge).entity;if(!e.valid(i)||!e.has(i,Le))return{x:s,y:n};const o=e.get(i,Le),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=mo(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(s*u-n*c)/r,y:(s*c+n*u)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,Le);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,Le,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}}const hr=new dr,fr=Ee("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function pr(e,t,s,n){return n<=0?1:e<t?Math.max(0,1-(t-e)/n):e>s?Math.max(0,1-(e-s)/n):1}function mr(e,t,s,n,i){const o=2/(n=Math.max(1e-4,n)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(s+o*l)*i,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(s-o*c)*a}}class gr{build(e){ze("ScrollView",fr);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(Gt.PostUpdate,Jt([lt(is),lt(as),lt(ht)],(e,i,o)=>{const r=ko()&&!$o(),a=Math.min(o.delta,.05);for(const[e]of s)t.valid(e)||s.delete(e);i.valid&&(n.x=i.worldMouseX,n.y=i.worldMouseY);const l=t.getEntitiesWithComponents([fr,Ri]);for(const o of l){Ni(t,o,co,{enabled:!0,mode:ao});const l=t.get(o,fr),c=t.get(o,Ri);let u=s.get(o);u||(u={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},s.set(o,u));const d=ji(c,o),h=Xi(c,o);let f=l.contentWidth,p=l.contentHeight;if((0===f||0===p)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,qe)){const e=t.get(l.contentEntity,qe).entities;let s=0,n=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,Le))continue;const e=t.get(r,Le);let a=0,l=0,c=.5,u=.5;if(t.has(r,Ri)){const e=t.get(r,Ri);a=ji(e,r)||e.size.x,l=Xi(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,Xe)){const e=t.get(r,Xe);a=e.size.x,l=e.size.y}const d=e.position.x-a*c,h=e.position.x+a*(1-c),f=e.position.y-l*u,p=e.position.y+l*(1-u);d<s&&(s=d),h>n&&(n=h),f<i&&(i=f),p>o&&(o=p)}0===f&&(f=n-s),0===p&&(p=o-i)}const m=Math.max(0,f-d),g=Math.max(0,p-h);if(!r&&i.valid){Ni(t,o,bo,{enabled:!0,blockRaycast:!0});const s=t.has(o,So)?t.get(o,So):null;if(s?.justPressed&&(u.isDragging=!0,u.lastWorldX=n.x,u.lastWorldY=n.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=n.x-u.lastWorldX,t=n.y-u.lastWorldY,s=Math.min(1,10*a);if(l.horizontalEnabled){const t=pr(l.scrollX,0,m,d);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const n=a>0?-e*t/a:0;u.velocityX+=(n-u.velocityX)*s}}if(l.verticalEnabled){const e=pr(l.scrollY,0,g,h);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const n=a>0?t*e/a:0;u.velocityY+=(n-u.velocityY)*s}}u.lastWorldX=n.x,u.lastWorldY=n.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*d,t=5*h;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(s?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=pr(l.scrollY,0,g,h);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=pr(l.scrollX,0,m,d);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>g;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=mr(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<Ki&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Ki?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:g,t=mr(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<Ki&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Ki?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,m)),l.scrollY=Math.max(0,Math.min(l.scrollY,g)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*d,t=.5*h;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,g+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,Le)){const e=t.get(l.contentEntity,Le),s=e.position.x,n=e.position.y;(isNaN(u.lastAppliedX)||Math.abs(s-u.lastAppliedX)>.01)&&(u.contentBaseX=s),(isNaN(u.lastAppliedY)||Math.abs(n-u.lastAppliedY)>.01)&&(u.contentBaseY=n),e.position.x=u.contentBaseX-l.scrollX,e.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=e.position.x,u.lastAppliedY=e.position.y,t.insert(l.contentEntity,Le,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const _r=new gr,yr=Ci,wr=Ee("Slider",{value:0,minValue:0,maxValue:1,direction:Ci.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function xr(e,t,s,n,i,o){const r=ji(n,i)*s.worldScale.x,a=Xi(n,i)*s.worldScale.y,l=mo(s.worldRotation.z,s.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),d=e-s.worldPosition.x,h=t-s.worldPosition.y,f=d*u-h*c,p=d*c+h*u,m=-n.pivot.x*r,g=-n.pivot.y*a;switch(o){case Ci.LeftToRight:return r>0?(f-m)/r:0;case Ci.RightToLeft:return r>0?1-(f-m)/r:0;case Ci.BottomToTop:return a>0?(p-g)/a:0;case Ci.TopToBottom:return a>0?1-(p-g)/a:0}}function vr(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case Ci.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case Ci.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case Ci.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case Ci.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class br{build(e){ze("Slider",wr);const t=e.world;let s=null;e.addSystemToSchedule(Gt.PreUpdate,Jt([lt(is),lt(as),lt(Eo)],(e,n,i)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([wr,Ri]);for(const r of o){const o=t.get(r,wr),a=t.get(r,Ri);if(!ko()||$o()){if(t.has(r,Le)){Ni(t,r,bo,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Ni(t,o.handleEntity,bo,{enabled:!0,blockRaycast:!1});const l=t.get(r,Le),c=t.has(r,So)?t.get(r,So):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,So)&&(u=t.get(o.handleEntity,So).justPressed),u&&(s=r),s===r&&e.isMouseButtonDown(0)){let e=xr(n.worldMouseX,n.worldMouseY,l,a,r,o.direction);e=Math.max(0,Math.min(1,e));let s=o.minValue+e*(o.maxValue-o.minValue);o.wholeNumbers&&(s=Math.round(s));const c=o.value;o.value=Math.max(o.minValue,Math.min(o.maxValue,s)),t.insert(r,wr,o),o.value!==c&&i.emit(r,"change")}s===r&&e.isMouseButtonReleased(0)&&(s=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,u=ji(a,r),d=Xi(a,r),h={left:-u/2,bottom:-d/2,right:u/2,top:d/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(Ui(t,o.fillEntity,o.direction,c),Gi(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Ri)){const e=t.get(o.handleEntity,Ri);vr(e,o.direction,c),t.insert(o.handleEntity,Ri,e),Gi(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Sr=new br;class Mr{build(e){ze("Focusable",Ho);const t=e.world,s=new jo;e.insertResource(Xo,s),e.addSystemToSchedule(Gt.Update,Jt([lt(is),lt(Eo)],(e,n)=>{if(ko()&&!$o())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const i=t.getEntitiesWithComponents([Ho]);for(const e of i){if(!t.has(e,So))continue;t.get(e,So).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const n=function(){const e=[];for(const s of i){if(!t.valid(s))continue;if(t.has(s,bo)){if(!t.get(s,bo).enabled)continue}const n=t.get(s,Ho);e.push({entity:s,tabIndex:n.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===n.length)return;const r=null!==s.focusedEntity?n.findIndex(e=>e===s.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?n.length-1:0:a?(r-1+n.length)%n.length:(r+1)%n.length,o(n[l])}function o(e){const i=s.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Ho)){t.get(i,Ho).isFocused=!1,n.emit(i,"blur",i)}s.focus(e);t.get(e,Ho).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const Pr=new Mr,Tr=Ee("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function Er(){return i()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:s,screenWidth:n,screenHeight:i}=t;return{top:s.top,bottom:i-s.bottom,left:s.left,right:n-s.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}class Cr{build(e){ze("SafeArea",Tr);const t=e.world;let s=Er(),n=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{s=Er(),n=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{s=Er(),n=!0});e.addSystemToSchedule(Gt.PreUpdate,Jt([lt(as)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===r||(o=e.screenH,r=a,n=!0),!n)return;n=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([Tr,Ri]);for(const e of u){const n=t.get(e,Tr),i=t.get(e,Ri),o=n.applyTop?s.top*c:0,r=n.applyBottom?s.bottom*c:0,a=n.applyLeft?s.left*c:0,l=n.applyRight?s.right*c:0;let u=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},u=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,Ri,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const Ar=new Cr,Rr=Ee("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Ir=null;function Fr(e,t){if(!Ir)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=Ir.get(e);s?s.renderer=t:Ir.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}class kr{build(e){ze("ListView",Rr);const t=e.world,s=new Map;Ir=s,e.addSystemToSchedule(Gt.PostUpdate,Jt([lt(is)],e=>{const n=ko()&&!$o();for(const[e,n]of s)if(!t.valid(e)){for(const e of n.itemEntities.values())t.valid(e)&&t.despawn(e);s.delete(e)}const i=t.getEntitiesWithComponents([Rr,Ri]);for(const o of i){Ni(t,o,bo,{enabled:!0,blockRaycast:!0}),Ni(t,o,co,{enabled:!0,mode:ao});let i=s.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},s.set(o,i));const r=t.get(o,Rr),a=t.get(o,Ri),l=Xi(a,o),c=ji(a,o);if(!n){const s=t.has(o,So)?t.get(o,So):null;if(s?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const u=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,u));const d=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),h=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,s]of i.itemEntities)(e<d||e>=h)&&(t.valid(s)&&t.despawn(s),i.itemEntities.delete(e));for(let e=d;e<h;e++){let s=i.itemEntities.get(e);if(s&&t.valid(s)||(s=t.spawn(),t.insert(s,Qe,{value:`ListItem_${e}`}),t.insert(s,Ri,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(s,o),i.itemEntities.set(e,s),i.renderer&&i.renderer(e,s)),t.has(s,Le)){const n=t.get(s,Le);n.position.y=-(e*r.itemHeight-r.scrollY),t.insert(s,Le,n)}}i.visibleStart=d,i.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const Br=new kr,zr=Ee("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class $r{build(e){ze("Dropdown",zr);const t=e.world,s=new Map;function n(e){if(0===e||!t.valid(e))return;if(!t.has(e,Le))return;const s=t.get(e,Le);0===s.scale.x&&0===s.scale.y&&0===s.scale.z&&t.insert(e,Le,{position:{x:s.position.x,y:s.position.y,z:s.position.z},rotation:{x:s.rotation.x,y:s.rotation.y,z:s.rotation.z,w:s.rotation.w},scale:{x:1,y:1,z:1}})}function i(e){if(t.has(e,Xe)){const s=t.get(e,Xe);1===s.color.r&&1===s.color.g&&1===s.color.b&&1===s.color.a&&t.insert(e,Xe,{texture:s.texture,color:{r:.9,g:.9,b:.9,a:1},size:{x:s.size.x,y:s.size.y},uvOffset:{x:s.uvOffset.x,y:s.uvOffset.y},uvScale:{x:s.uvScale.x,y:s.uvScale.y},layer:s.layer,flipX:s.flipX,flipY:s.flipY,material:s.material,enabled:s.enabled})}}function o(e,s,n){s.isOpen=!0,n.highlightIndex=s.selectedIndex;const i=s.listEntity;if(0===i||!t.valid(i))return;u(i,!0),c(n);const o=t.get(e,Xe),r=o.size.x,a=o.size.y;n.ddWidth=r;const l=s.options.length*Ji;t.insert(i,Ri,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:l},pivot:{x:.5,y:.5}}),t.insert(i,Le,{position:{x:0,y:-(a+l)/2,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(i,Xe,{texture:me,color:{r:1,g:1,b:1,a:1},size:{x:r,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<s.options.length;e++){const o=t.spawn(),a=l/2-(e+.5)*Ji;t.insert(o,Qe,{value:`Option_${e}`}),t.insert(o,Ri,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Ji},offsetMax:{x:0,y:0},size:{x:r,y:Ji},pivot:{x:.5,y:.5}}),t.insert(o,Le,{position:{x:0,y:a,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(o,Xe,{texture:me,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:Ji},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,bo,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),n.optionEntities.push(o);const c=t.spawn();t.insert(c,Le,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(c,so,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Zi.Left,verticalAlign:eo.Middle,wordWrap:!1,overflow:to.Clip,lineHeight:1.2}),t.insert(c,Ri,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:Ji},pivot:{x:.5,y:.5}}),t.setParent(c,o),n.textEntities.push(c)}d(n)}function r(e,t,s){t.isOpen=!1,c(s),u(t.listEntity,!1)}function a(e,t,s,n,i){t.selectedIndex=n,r(0,t,s),i.emit(e,"change")}function l(e){const s=e.labelEntity;if(0===s||!t.valid(s))return;if(!t.has(s,so))return;const n=t.get(s,so);let i={r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},o=n.content,r=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},r=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,r=!0)}r&&t.insert(s,so,{content:o,fontSize:n.fontSize,fontFamily:n.fontFamily,color:i,align:n.align,verticalAlign:n.verticalAlign,wordWrap:n.wordWrap,overflow:n.overflow,lineHeight:n.lineHeight})}function c(e){for(const s of e.textEntities)t.valid(s)&&t.despawn(s);for(const s of e.optionEntities)t.valid(s)&&t.despawn(s);e.optionEntities=[],e.textEntities=[]}function u(e,s){if(0!==e&&t.valid(e)&&(t.has(e,bo)&&t.insert(e,bo,{enabled:s,blockRaycast:!0,raycastTarget:!0}),t.has(e,Xe))){const n=t.get(e,Xe);t.insert(e,Xe,{texture:n.texture,color:{r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:s})}}function d(e){for(let s=0;s<e.optionEntities.length;s++){const n=e.optionEntities[s];if(!t.valid(n)||!t.has(n,Xe))continue;const i=s===e.highlightIndex?{...Qi}:{r:.95,g:.95,b:.95,a:1};t.insert(n,Xe,{texture:me,color:i,size:{x:e.ddWidth,y:Ji},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function h(e){for(const s of e.optionEntities){if(!t.valid(s)||!t.has(s,So))continue;if(t.get(s,So).hovered)return!0}return!1}e.addSystemToSchedule(Gt.Update,Jt([lt(is),lt(Eo)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const f=ko()&&!$o(),p=t.getEntitiesWithComponents([zr]);for(const m of p){const p=t.get(m,zr);let g=s.get(m);if(g||(g={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},s.set(m,g)),n(p.listEntity),i(m),p.isOpen||u(p.listEntity,!1),l(p),f)continue;Ni(t,m,bo,{enabled:!0,blockRaycast:!0});const _=t.has(m,So)?t.get(m,So):null;if(_?.justPressed&&(p.isOpen?r(m,p,g):o(m,p,g)),p.isOpen){for(let e=0;e<g.optionEntities.length;e++){const s=g.optionEntities[e];if(!t.valid(s)||!t.has(s,So))continue;if(t.get(s,So).justPressed){a(m,p,g,e,c);break}}let s=-1;for(let e=0;e<g.optionEntities.length;e++){const n=g.optionEntities[e];if(!t.valid(n)||!t.has(n,So))continue;if(t.get(n,So).hovered){s=e;break}}s>=0&&s!==g.highlightIndex&&(g.highlightIndex=s,d(g)),e.isKeyPressed("ArrowDown")?(g.highlightIndex>=p.options.length-1?g.highlightIndex=0:g.highlightIndex++,d(g)):e.isKeyPressed("ArrowUp")?(g.highlightIndex<=0?g.highlightIndex=p.options.length-1:g.highlightIndex--,d(g)):e.isKeyPressed("Enter")&&g.highlightIndex>=0?a(m,p,g,g.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,p,g),e.isMouseButtonPressed(0)&&(_?.hovered||h(g)||r(m,p,g))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}}const Ur=new $r,Wr=0,Dr=0,Or=2,Lr=Ee("LayoutGroup",{direction:Wr,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Dr,reverseOrder:!1});class Hr{build(e){ze("LayoutGroup",Lr);const t=e.world;e.addSystemToSchedule(Gt.PreUpdate,Jt([],()=>{const e=t.getEntitiesWithComponents([Lr,Ri,qe]);for(const s of e){const e=t.get(s,Lr),n=t.get(s,Ri),i=t.get(s,qe);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,Ri)&&t.has(e,Le)&&o.push({entity:e,rect:t.get(e,Ri)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=ji(n,s),a=Xi(n,s),l=n.pivot.x,c=n.pivot.y,u=e.padding,d=e.direction===Wr;let h=0;for(let s=0;s<o.length;s++){const n=o[s],i=ji(n.rect,n.entity),f=Xi(n.rect,n.entity),p=n.rect.pivot.x,m=n.rect.pivot.y;let g,_;d?(g=-l*r+u.left+h+p*i,_=e.childAlignment===Dr?(1-c)*a-u.top-(1-m)*f:e.childAlignment===Or?-c*a+u.bottom+m*f:(.5-c)*a+.5*(u.bottom-u.top)+(m-.5)*f,h+=i,s<o.length-1&&(h+=e.spacing)):(g=e.childAlignment===Dr?-l*r+u.left+p*i:e.childAlignment===Or?(1-l)*r-u.right-(1-p)*i:(.5-l)*r+.5*(u.left-u.right)+(p-.5)*i,_=(1-c)*a-u.top-h-(1-m)*f,h+=f,s<o.length-1&&(h+=e.spacing));const y=t.get(n.entity,Le);y.position.x=g,y.position.y=_,t.insert(n.entity,Le,y)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}}const jr=new Hr;class Xr{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(Gt.PostUpdate,Jt([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const Yr=new Xr;async function Vr(e,t,s){const n=e.getResource(ci);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function Nr(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 Gr=at({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),qr=at(null,"PhysicsAPI");function Kr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Jr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Qr{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(Gr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Nr(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const i=function(e){const t=e.world.getEntitiesWithComponents([Ve]);for(const s of t){const t=e.world.get(s,Ve);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/i,r=e.world;r.onDespawn(e=>{t.has(e)&&(n._physics_destroyBody(e),t.delete(e),s.delete(e))}),e.addSystemToSchedule(Gt.PostUpdate,Jt([lt(ht)],a=>{const l=r.getEntitiesWithComponents([tt,Le]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,tt),l=r.get(i,Le);if(t.has(i)){const e=s.get(i);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(i,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const r=Kr(l.worldRotation);n._physics_createBody(i,a.bodyType,l.worldPosition.x*o,l.worldPosition.y*o,r,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Zr(e,n,i),t.add(i),s.set(i,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===ot.Kinematic){const e=Kr(l.worldRotation);n._physics_setBodyTransform(i,l.worldPosition.x*o,l.worldPosition.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 i=t._physics_getDynamicBodyTransforms(),o=i>>2;for(let i=0;i<n;i++){const n=o+4*i,r=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(r))continue;const u=e.world.get(r,Le);if(!u)continue;let d=a,h=l,f=c;if(e.world.has(r,Ge)){const t=e.world.get(r,Ge);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,Le)){const s=e.world.get(t.entity,Le),n=Kr(s.worldRotation),i=a-s.worldPosition.x,o=l-s.worldPosition.y,r=Math.cos(-n),u=Math.sin(-n);d=(i*r-o*u)/(0!==s.worldScale.x?s.worldScale.x:1),h=(i*u+o*r)/(0!==s.worldScale.y?s.worldScale.y:1),f=c-n}}u.position.x=d,u.position.y=h;const p=Jr(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(r,Le,u)}}(e,n,i),function(e,t,s){t._physics_collectEvents();const n=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<i;o++){const i=e+6*o;n.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*s,contactY:t.HEAPF32[i+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 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(Gr,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,i)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(qr,ea._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function Zr(e,t,s){const n=e.world;if(n.has(s,st)){const e=n.get(s,st);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,nt)){const e=n.get(s,nt);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,it)){const e=n.get(s,it);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 ea{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(ea.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}const ta={nearest:0,linear:1},sa={repeat:0,clamp:1,mirror:2};function na(e,t,s=!0,n){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),n&&(n.filterMode||n.wrapMode)&&i.createTextureEx){const e=ta[n.filterMode??"linear"]??1,a=sa[n.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,s,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,s);return e._free(o),r}function ia(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 oa(e,t,s,n){const i=e.worldScale.x*t*(s?-1:1),o=e.worldScale.y*t*(n?-1:1),r=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,u=e.worldRotation.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,v=u*h,b=u*f;return new Float32Array([(1-(_+w))*i,(m+b)*i,(g-v)*i,0,(m-b)*o,(1-(p+w))*o,(y+x)*o,0,(g+v)*r,(y-x)*r,(1-(p+_))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function ra(e){const{app:t,module:s,sceneData:n,provider:i,spineModule:o,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,u=await async function(e,t,s){const n={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=Ls(t.type);for(const r of o){if("texture"!==r.type)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===n[o])try{const t=i?.[o];n[o]=na(e,await s.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),n[o]=0}}}return n}(s,n,i);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const i=s[e];if(i&&i>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(s,n,u);let d={},h=null;if(o&&(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"])}}(o),d=await async function(e,t,s,n,i){const o={};for(const r of n.entities)for(const n of r.components){const r=Hs(n.type);if(!r||!n.data)continue;const a=n.data[r.skeletonField],l=n.data[r.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),u=i.resolvePath(l);try{const n=await i.readText(l),r="binary"===T(c)?.contentType;let d,h;if(r){const e=await i.readBinary(a);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await i.readText(a),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,r);if(t._free(d),f<0)continue;o[a]=f;const p=ia(n),m=u.substring(0,u.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=m+"/"+p[t];try{const o=i.loadPixelsRaw?await i.loadPixelsRaw(n):await i.loadPixels(n),r=na(e,o,!1),a=e.getResourceManager().getTextureGLId(r);s.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(s,o,h,n,i)),r){const e={gravity:a?.gravity??{...ae},fixedTimestep:a?.fixedTimestep??le,subStepCount:a?.subStepCount??4};new Qr("",e,()=>Promise.resolve(r)).build(t)}const f=await async function(e,t,s){const n={};for(const i of t.entities)for(const t of i.components){const i=Ls(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{let t,i;const r=T(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await s.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){n[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await s.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),u=na(e,c,!1),d=e.getResourceManager();n[o]=d.loadBitmapFont(t,u,c.width,c.height)}catch{n[o]=0}}return n}(s,n,i),p=await async function(e,t){const s={},n={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Ls(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){s[o]=0;continue}const i=e.vertexSource+e.fragmentSource;let r=n[i];r||(r=_s.createShader(e.vertexSource,e.fragmentSource),n[i]=r),s[o]=_s.createFromAsset(e,r)}catch{s[o]=0}}return s}(n,i);await async function(e,t,s){const n=new Set;for(const i of t.entities)for(const t of i.components){const i=Ls(t.type);for(const o of i){if("anim-clip"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!n.has(i)){n.add(i);try{const t=await s.readText(i),n=JSON.parse(t),o=Cs(n),r=new Map;for(const t of o)try{const n=await s.loadPixels(t);r.set(t,na(e,n))}catch{r.set(t,0)}Is(As(i,n,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(s,n,i),await async function(e){const t=[],s=new Set;for(const n of e.entities)for(const e of n.components){const n=Ls(e.type);for(const i of n){if("audio"!==i.type)continue;const n=e.data[i.field];"string"==typeof n&&n&&!s.has(n)&&(s.add(n),t.push(n))}}t.length>0&&await Us.preloadAll(t).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)})}(n),function(e,t,s,n){const i={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=Ls(e.type);if(0===t.length)continue;const s=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof s[e.field]&&(s[e.field]=t[s[e.field]]||0)}}}(n,u,f,p);const m=Gs(t.world,n);if(c&&t.hasResource(ci))for(const e of m.values())t.world.insert(e,Ze,{scene:c,persistent:!1});if(o&&h){const e=function(e,t,s,n){const i={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const r=Hs(t.type);if(!r||!t.data)continue;const a=s[t.data[r.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=n.get(o.id);void 0!==c&&(i[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return i}(h,n,d,m);!function(e,t,s,n,i){let o=0;e.setSpineRenderer((r,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=re);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,Je)?c.get(o,Je):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(r,l*d);let h=0;if(c.has(o,Le)){const e=oa(c.get(o,Le),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=n.getMeshBatchCount(r);for(let e=0;e<f;e++){const i=n.getMeshBatchVertexCount(r,e),o=n.getMeshBatchIndexCount(r,e);if(!i||!o)continue;const a=8*i*4,l=2*o,c=s._malloc(a),u=s._malloc(l),d=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(r,e,c,u,d,f);const p=s.HEAPU32[d>>2],m=s.HEAPU32[f>>2],g=new Float32Array(s.HEAPF32.buffer,c,8*i),_=new Uint16Array(s.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,i,w,o,p,m,h),t._free(y),t._free(w),s._free(c),s._free(u),s._free(d),s._free(f)}h&&t._free(h)}})}(t,s,o,h,e)}if(l){const e=t.getResource(tn);e&&e.setAddressableManifest(l)}}function aa(e,t,s){return{name:e,async setup(){await ra({...s,sceneData:t,sceneName:e})}}}async function la(e){const{app:t,firstScene:s,aspectRatio:n}=e;pi(t);const i={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},o=t.getResource(ci);for(const t of e.scenes)o.register(aa(t.name,t.data,i));s&&(o.setInitial(s),await o.load(s)),void 0!==n&&Qs(t.world,n)}class ca{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 i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Hs(e.type);if(i){const n=e.data[i.skeletonField],o=e.data[i.atlasField];n&&("binary"===T(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=Ls(e.type);for(const s of o){const i=e.data[s.field];"string"==typeof i&&i&&("font"===s.type?(n.add(i),t.add(i)):("material"===s.type||"anim-clip"===s.type)&&t.add(i))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const o=[];for(const e of n){const t=T(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(),i=await createImageBitmap(n),o=new OffscreenCanvas(i.width,i.height).getContext("2d");o.drawImage(i,0,0);const r=o.getImageData(0,0,i.width,i.height);return i.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const ua="__preview__";class da{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(ci);t.register({name:ua,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(ua),this.loadPromise_=t.load(ua).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await r(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new ca(this.baseUrl_);await s.prefetch(t);let n=null;const i=this.app_.spineInitPromise;if(i){n=(await i).controller.raw}await ra({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:s,spineModule:n,sceneName:ua})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([Ye]);for(const n of s){if(e.get(n,Ye).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([Ve]);for(const i of n){const n=e.get(i,Ve);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const i=this.app_.getResource(ci).getScene(ua),o=i?i.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,Le,r);const a={isActive:!0,projectionType:We.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:De.ColorAndDepth};e.insert(o,Ye,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(ci);await e.switchTo(ua),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 ha={create(e){const t=e.depth??!0,s="linear"===e.filter,n=(t?1:0)|(s?2:0),i=Zn.createRenderTarget(e.width,e.height,n);return{_handle:i,textureId:Zn.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:s?"linear":"nearest"}},release(e){Zn.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Zn.releaseRenderTarget(e._handle),ha.create({width:t,height:s,depth:e._depth,filter:e._filter})),begin(e,t){Zn.begin(t,e._handle)},end(){Zn.end()},getDepthTexture:e=>Zn.getTargetDepthTexture(e._handle)};var fa;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(fa||(fa={}));class pa{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${fa[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case fa.Debug:console.debug(t,s);break;case fa.Info:console.log(t,s);break;case fa.Warn:console.warn(t,s);break;case fa.Error:console.error(t,s)}}}class ma{constructor(){this.handlers_=[],this.minLevel_=fa.Info,this.addHandler(new pa)}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(fa.Debug,e,t,s)}info(e,t,s){this.log(fa.Info,e,t,s)}warn(e,t,s){this.log(fa.Warn,e,t,s)}error(e,t,s){this.log(fa.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const i={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const ga=new ma;function _a(){return ga}function ya(e){ga.setMinLevel(e)}function wa(e,t,s){ga.debug(e,t,s)}function xa(e,t,s){ga.info(e,t,s)}function va(e,t,s){ga.warn(e,t,s)}function ba(e,t,s){ga.error(e,t,s)}const Sa={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},Ma={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12},Pa={Running:0,Paused:1,Completed:2,Cancelled:3},Ta={None:0,Restart:1,PingPong:2};class Ea{constructor(e,t,s){this.module_=e,this.registry_=t,this.entity=s}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,s,n){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,s,n),this}then(e){return this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let Ca=null,Aa=null;function Ra(e,t){Ca=e,Aa=t}function Ia(){Ca=null,Aa=null}function Fa(){if(!Ca)throw new Error("Tween API not initialized");return Ca}function ka(){if(!Aa)throw new Error("Tween API not initialized");return Aa}const Ba={to(e,t,s,n,i,o){const r=Fa(),a=ka(),l=o?.easing??Sa.Linear,c=o?.delay??0,u=o?.loop??Ta.None,d=o?.loopCount??0,h=r._anim_createTween(a,e,t,s,n,i,l,c,u,d);return new Ea(r,a,h)},cancel(e){Fa()._anim_cancelTween(ka(),e.entity)},cancelAll(e){Fa()._anim_cancelAllTweens(ka(),e)},update(e){Fa()._anim_updateTweens(ka(),e)}};class za{constructor(){this.name="AnimationPlugin"}build(e){Ra(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(Gt.Update,Jt([lt(ht)],e=>{Ba.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(Gt.Update,Jt([lt(ht)],e=>{$s(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){Ia()}}const $a=new za;var Ua;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(Ua||(Ua={}));const Wa={model:Ua.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function Da(e,t=Wa){const{model:s,refDistance:n,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(s){case Ua.Linear:{const e=i-n;if(e<=0)return 1;a=1-(Math.min(Math.max(r,n),i)-n)/e;break}case Ua.Inverse:a=n/Math.max(r,n);break;case Ua.Exponential:a=Math.pow(Math.max(r,n)/n,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function Oa(e,t,s,n,i){const o=e-s;return Math.max(-1,Math.min(1,o/i))}const La=Ee("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:Ua.Inverse,rolloff:1,priority:0,enabled:!0}),Ha=Ee("AudioListener",{enabled:!0});class ja{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const s=t().createAudioBackend(),n=this.config_;s.initialize({initialPoolSize:n.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const i=s.mixer;Us.init(s,i),i&&(void 0!==n.masterVolume&&(i.master.volume=n.masterVolume),void 0!==n.musicVolume&&(i.music.volume=n.musicVolume),void 0!==n.sfxVolume&&(i.sfx.volume=n.sfxVolume));const o=new Map;this.activeSourceHandles_=o;const r=new Set;this.playedEntities_=r;const a=new Set;let l=!1,c=!1;e.addSystemToSchedule(Gt.PreUpdate,Jt([lt(ht)],t=>{if(!(!ko()||$o()))return void(c&&(l=!1,c=!1));c=!0;const n=e.world;let i=0,u=0,d=!1;const h=n.getEntitiesWithComponents([Ha,je]);for(const e of h){if(n.get(e,Ha).enabled){const t=n.get(e,je);i=t.position.x,u=t.position.y,d=!0;break}}const f=n.getEntitiesWithComponents([La]);a.clear();for(const e of f){const t=n.get(e,La);if(!t.enabled||!t.clip)continue;const c=e;if(a.add(c),t.playOnAwake&&!r.has(c)&&!o.has(c)&&s.isReady){const e=Us.getBufferHandle(t.clip);if(e){const n=s.play(e,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});o.set(c,n),r.add(c)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(c)){const s=o.get(c);if(!s.isPlaying){o.delete(c);continue}d||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=n.tryGet?.(e,je),a=r?.position.x??0,h=r?.position.y??0,f=a-i,p=h-u,m=Da(Math.sqrt(f*f+p*p),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=Oa(a,0,i,0,t.maxDistance);s.setVolume(t.volume*m),s.setPan(g)}}for(const[e,t]of o)a.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),Us.dispose()}}const Xa=new ja;function Ya(e,t){return e.toFixed(t)}function Va(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}class Na{constructor(e,t="bottom-left"){this.visible_=!0,this.disposed_=!1,this.el_=document.createElement("div"),this.el_.style.cssText="\nposition: fixed;\nz-index: 99999;\npointer-events: none;\nbackground: rgba(30, 30, 30, 0.85);\nborder: 1px solid rgba(60, 60, 60, 0.8);\nborder-radius: 4px;\npadding: 6px 10px;\nfont: 11px monospace;\ncolor: #cccccc;\nline-height: 1.6;\nmin-width: 200px;\nwhite-space: pre;\n"+function(e){switch(e){case"top-left":return"top: 12px; left: 12px;";case"top-right":return"top: 12px; right: 12px;";case"bottom-left":return"bottom: 12px; left: 12px;";case"bottom-right":return"bottom: 12px; right: 12px;"}}(t),e.appendChild(this.el_)}update(e){if(!this.visible_||this.disposed_)return;const t=[];if(t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div><div>FPS: <span style="color:#d19a66">${Ya(e.fps,1)}</span> Frame: <span style="color:#d19a66">${Ya(e.frameTimeMs,1)}ms</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div><div>DC: <span style="color:#d19a66">${e.drawCalls}</span> Tri: <span style="color:#d19a66">${e.triangles}</span></div><div>Sprites: <span style="color:#d19a66">${e.sprites}</span> Culled: <span style="color:#d19a66">${e.culled}</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div><div>Entities: <span style="color:#d19a66">${e.entityCount}</span></div>`),e.systemTimings.size>0){const s=[...e.systemTimings.entries()].sort((e,t)=>t[1]-e[1]).slice(0,5);let n='<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';for(const[e,t]of s){n+=`<div>${Va(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${Ya(t,1)}ms</span></div>`}t.push(n)}this.el_.innerHTML=t.join("")}show(){this.visible_=!0,this.el_.style.display=""}hide(){this.visible_=!1,this.el_.style.display="none"}dispose(){this.disposed_=!0,this.el_.parentElement?.removeChild(this.el_)}}function Ga(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const qa=at(Ga(),"Stats");class Ka{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,s){const n={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:s?new Map(s):new Map};this.count_<this.capacity_?(this.buffer_.push(n),this.count_++):this.buffer_[this.cursor_]=n,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}}const Ja="StatsCollect";class Qa{constructor(){this.deltas_=[],this.cursor_=0,this.count_=0,this.sum_=0}pushFrame(e){!Number.isFinite(e)||e<0||(this.count_<60?(this.deltas_.push(e),this.sum_+=e,this.count_++):(this.sum_-=this.deltas_[this.cursor_],this.deltas_[this.cursor_]=e,this.sum_+=e,this.cursor_=(this.cursor_+1)%60))}getFps(){return 0===this.count_||this.sum_<=0?0:this.count_/this.sum_}getFrameTimeMs(){return 0===this.count_||this.sum_<=0?0:this.sum_/this.count_*1e3}reset(){this.deltas_.length=0,this.cursor_=0,this.count_=0,this.sum_=0}}class Za{constructor(e){this.name="Stats",this.collector_=new Qa,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(qa,Ga());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new Na(e,this.options_.position)}const t=this.collector_,s=this.overlay_,n=Jt([lt(ht),{_type:"get_world"}],(n,i)=>{t.pushFrame(n.delta);const o=e.getResource(qa);o.fps=t.getFps(),o.frameTimeMs=t.getFrameTimeMs(),o.entityCount=i.entityCount();const r=e.getSystemTimings();if(r){const e=new Map(r);e.delete(Ja),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=Zn.getStats();o.drawCalls=l.drawCalls,o.triangles=l.triangles,o.sprites=l.sprites,o.text=l.text,o.spine=l.spine,o.meshes=l.meshes,o.culled=l.culled,s?.update(o)},{name:Ja});e.addSystemToSchedule(Gt.Last,n)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const el=new Za;class tl{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,s)=>{const n=new Image;n.onload=()=>{const e=document.createElement("canvas");e.width=n.width,e.height=n.height;const s=e.getContext("2d");s.drawImage(n,0,0);const i=s.getImageData(0,0,n.width,n.height);t({width:n.width,height:n.height,pixels:new Uint8Array(i.data.buffer)})},n.onerror=s,n.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return function(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}(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}async function sl(e,t){try{const s=function(e){const t=atob(e),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s}(t);return await e({instantiateWasm:(e,t)=>(WebAssembly.instantiate(s.buffer,e).then(e=>{t(e.instance,e.module)}),{})})}catch(e){return null}}async function nl(e){const{app:t,module:s,assets:n,sceneData:i,sceneName:o}=e,r=t.getResource(tn);r&&(r.registerEmbeddedAssets(n),r.setEmbeddedOnly(!0));const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await sl(ESSpineModule,e);return t||console.warn("Spine module not available"),t}(e.spineWasmBase64):null,l=e.physicsWasmBase64?await async function(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await sl(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new tl(n);await la({app:t,module:s,provider:c,scenes:[{name:o,data:i}],firstScene:o,spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()}const il=[ro,vo,Ao,Zo,lr,Oo,hr,_r,Sr,nr,Vo,Pr,Ar,Br,Ur,jr,Yr],ol=[...il,$a,Xa];function rl(e,t){return function(e,t){const s=fi.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),vn(e),ps(e),Wn(e),jn(e),Jn(e),ti(e);const i=new ii;s.setPipeline(i);let o=h();const r=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=wi(e,n,t,i));const r=s.getResource(as);if(o.length>0){const e=o[0],s=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(s.x*t),r.vpY=Math.round((1-s.y-s.h)*i),r.vpW=Math.round(s.w*t),r.vpH=Math.round(s.h*i),r.screenW=t,r.screenH=i,r.worldLeft=e.cameraX-e.halfW,r.worldRight=e.cameraX+e.halfW,r.worldBottom=e.cameraY-e.halfH,r.worldTop=e.cameraY+e.halfH,r.valid=!0}else r.valid=!1}s.insertResource(as,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=r();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(n);if(c>=0){const e=n.getCanvas(c).backgroundColor;Zn.setClearColor(e.x,e.y,e.z,e.w)}const u=(h()-o)/1e3;let d;if(Zn.resize(t,l),Vn.isInitialized()&&Vn.getPassCount()>0&&!Vn.isBypassed()&&Vn.resize(t,l),s.hasResource(ci)){const e=s.getResource(ci).getActiveScenes();e.length>0&&(d=new Set(e))}i.setActiveScenes(d??null);const f=wi(e,n,t,l,s.world,d);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:n},viewProjection:mi,width:t,height:l,elapsed:u});else{for(const e of f){const s=e.viewportRect,o=Math.round(s.x*t),r=Math.round((1-s.y-s.h)*l),a=Math.round(s.w*t),c=Math.round(s.h*l);i.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:u})}Zn.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(Gt.First,l),s.addSystemToSchedule(Gt.Last,c),s.addPlugin(nn),s.addPlugin(mn),s.addPlugin(rs),s.addPlugin(hi),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:ol,...t})}class al{constructor(e){this.resolvePath_=e}async loadPixels(e){return async function(e){return t().loadImagePixels(e)}(this.resolvePath_(e))}async readText(e){return l(this.resolvePath_(e))}async readBinary(e){const t=await a(this.resolvePath_(e));return new Uint8Array(t)}resolvePath(e){return this.resolvePath_(e)}}function ll(e){return(t,s)=>(u(e,t).then(e=>{s(e.instance,e.module)}),{})}async function cl(e,t){try{return await e({instantiateWasm:ll(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}async function ul(e){const t=await l("asset-manifest.json"),s=JSON.parse(t),n=function(e){const t={},s={};for(const n in e.groups){const i=e.groups[n];for(const e in i.assets){const n=i.assets[e];t[e]=n,s[n.path]=n}}return{assetIndex:t,pathIndex:s}}(s),i=function(e){const{assetIndex:t,pathIndex:s}=e;return e=>{const n=U(e),i=t[e]||t[n]||s[n]||s[e];return i?i.path:n}}(n),o=wx.createCanvas(),r=wx.getSystemInfoSync();o.width=r.windowWidth*r.pixelRatio,o.height=r.windowHeight*r.pixelRatio;const a=await e.engineFactory({canvas:o,instantiateWasm:ll("esengine.wasm")}),c=o.getContext("webgl2")||o.getContext("webgl");if(!c)return void console.error("[ESEngine] Failed to create WebGL context");const u=a.GL.registerContext(c,{majorVersion:0===c.getParameter(c.VERSION).indexOf("WebGL 2")?2:1,minorVersion:0,enableExtensionsByDefault:!0}),d=rl(a,{glContextHandle:u,getViewportSize:()=>({width:o.width,height:o.height})});e.runtimeConfig&&fe(d,e.runtimeConfig);let h=null;e.spineFactory&&(h=await cl(e.spineFactory,"spine.wasm"));let f=null;e.physicsFactory&&(f=await cl(e.physicsFactory,"physics.wasm"));const p=new al(i),m=[];for(const t of e.sceneNames){const e=await l(`scenes/${t}.json`);m.push({name:t,data:JSON.parse(e)})}await la({app:d,module:a,provider:p,scenes:m,firstScene:e.firstScene,spineModule:h,physicsModule:f,physicsConfig:e.physicsConfig,manifest:s,aspectRatio:o.width/o.height}),d.run()}q||(q=!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},i=await w(s,n);return{ok:i.ok,status:i.status,statusText:i.statusText,headers:new Headers(i.headers),json:()=>i.json(),text:()=>i.text(),arrayBuffer:()=>i.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 x(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 i=e.charCodeAt(t);i<128?s[n++]=i:i<2048?(s[n++]=192|i>>6,s[n++]=128|63&i):i>=55296&&i<=56319?(i=e.charCodeAt(++t)-56320+(i-55296<<10)+65536,s[n++]=240|i>>18,s[n++]=128|i>>12&63,s[n++]=128|i>>6&63,s[n++]=128|63&i):(s[n++]=224|i>>12,s[n++]=128|i>>6&63,s[n++]=128|63&i)}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 i=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(i>>10),56320+(1023&i)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=K;export{Ct as Added,za as AnimationPlugin,fi as App,sn as AssetPlugin,on as AssetRefCounter,en as AssetServer,tn as Assets,Ts as AsyncCache,Ua as AttenuationModel,Us as Audio,p as AudioBus,Ha as AudioListener,m as AudioMixer,ja as AudioPlugin,g as AudioPool,La as AudioSource,Ke as BitmapText,ls as BlendMode,ot as BodyType,st as BoxCollider,Po as Button,Mo as ButtonState,Ye as Camera,Ve as Canvas,it as CapsuleCollider,At as Changed,qe as Children,nt as CircleCollider,De as ClearFlags,Wt as Commands,Ot as CommandsInstance,Q as DEFAULT_DESIGN_HEIGHT,J as DEFAULT_DESIGN_WIDTH,re as DEFAULT_FALLBACK_DT,le as DEFAULT_FIXED_TIMESTEP,se as DEFAULT_FONT_FAMILY,ne as DEFAULT_FONT_SIZE,ae as DEFAULT_GRAVITY,ie as DEFAULT_LINE_HEIGHT,oe as DEFAULT_MAX_DELTA_TIME,Z as DEFAULT_PIXELS_PER_UNIT,ce as DEFAULT_SPINE_SKIN,te as DEFAULT_SPRITE_SIZE,ee as DEFAULT_TEXT_CANVAS_SIZE,kn as DataType,dr as DragPlugin,ur as DragState,cr as Draggable,Pn as Draw,zr as Dropdown,$r as DropdownPlugin,Sa as EasingType,Dt as EntityCommands,Yt as EventReader,Nt as EventReaderInstance,jt as EventRegistry,Xt as EventWriter,Vt as EventWriterInstance,Ci as FillDirection,Go as FillMethod,qo as FillOrigin,Xo as FocusManager,jo as FocusManagerState,Mr as FocusPlugin,Ho as Focusable,Ka as FrameHistory,ni as GLDebug,Ln as Geometry,qt as GetWorld,pe as INVALID_ENTITY,ge as INVALID_FONT,_e as INVALID_MATERIAL,me as INVALID_TEXTURE,Ko as Image,Qo as ImagePlugin,No as ImageType,is as Input,os as InputPlugin,ns as InputState,bo as Interactable,Hr as LayoutGroupPlugin,Rr as ListView,kr as ListViewPlugin,He as LocalTransform,fa as LogLevel,ma as Logger,Ta as LoopMode,_s as Material,Es as MaterialLoader,Tt as Mut,Qe as Name,Ge as Parent,ea as Physics,Gr as PhysicsEvents,Qr as PhysicsPlugin,Vn as PostProcess,hn as PrefabServer,fn as Prefabs,pn as PrefabsPlugin,da as PreviewPlugin,or as ProgressBar,ir as ProgressBarDirection,ar as ProgressBarPlugin,We as ProjectionType,Bt as Query,zt as QueryInstance,$t as Removed,Ut as RemovedQueryInstance,ii as RenderPipeline,Gn as RenderStage,ha as RenderTexture,Zn as Renderer,lt as Res,ct as ResMut,tt as RigidBody,ue as RuntimeConfig,Tr as SafeArea,Cr as SafeAreaPlugin,Oe as ScaleMode,ci as SceneManager,li as SceneManagerState,Ze as SceneOwner,Gt as Schedule,fr as ScrollView,gr as ScrollViewPlugin,Ps as ShaderSources,wr as Slider,yr as SliderDirection,br as SliderPlugin,Je as SpineAnimation,Xe as Sprite,zs as SpriteAnimator,qa as Stats,Qa as StatsCollector,Na as StatsOverlay,Za as StatsPlugin,ss as SystemRunner,so as Text,Zi as TextAlign,Lo as TextInput,Yo as TextInputPlugin,to as TextOverflow,oo as TextPlugin,no as TextRenderer,eo as TextVerticalAlign,ht as Time,er as Toggle,sr as TogglePlugin,Le as Transform,Ba as Tween,Ea as TweenHandle,Pa as TweenState,Ma as TweenTarget,as as UICameraInfo,To as UIEventQueue,Eo as UIEvents,So as UIInteraction,Do as UIInteractionPlugin,Co as UILayoutPlugin,co as UIMask,xo as UIMaskPlugin,Ri as UIRect,Xr as UIRenderOrderPlugin,Ne as Velocity,al as WeChatAssetProvider,ca as WebAssetProvider,Pt as World,je as WorldTransform,es as addStartupSystem,Zt as addSystem,ts as addSystemToSchedule,$a as animationPlugin,fe as applyBuildRuntimeConfig,Ui as applyDirectionalFill,de as applyRuntimeConfig,nn as assetPlugin,Xa as audioPlugin,Da as calculateAttenuation,Oa as calculatePanning,Bs as clearAnimClips,Fn as clearDrawCallbacks,Re as clearUserComponents,ve as color,Bi as computeFillAnchors,$i as computeFillSize,zi as computeHandleAnchors,Ai as computeUIRectLayout,wo as createMaskProcessor,aa as createRuntimeSceneConfig,rl as createWebApp,wa as debug,Ga as defaultFrameStats,Ee as defineComponent,Lt as defineEvent,at as defineResource,Jt as defineSystem,Ce as defineTag,hr as dragPlugin,Ur as dropdownPlugin,ba as error,Cs as extractAnimClipTexturePaths,Zs as findEntityByName,pi as flushPendingSystems,Pr as focusPlugin,C as getAddressableType,A as getAddressableTypeByEditorType,I as getAllAssetExtensions,ks as getAnimClip,z as getAssetMimeType,T as getAssetTypeEntry,$e as getComponent,Ls as getComponentAssetFieldDescriptors,Os as getComponentAssetFields,et as getComponentDefaults,Ys as getComponentEntityFields,Hs as getComponentSpineFieldDescriptor,k as getCustomExtensions,E as getEditorType,_a as getLogger,t as getPlatform,n as getPlatformType,Ae as getUserComponent,B as getWeChatPackOptions,Zo as imagePlugin,xa as info,vn as initDrawAPI,ti as initGLDebugAPI,Wn as initGeometryAPI,ps as initMaterialAPI,nl as initPlayableRuntime,jn as initPostProcessAPI,Jn as initRendererAPI,la as initRuntime,Ra as initTweenAPI,ul as initWeChatRuntime,rs as inputPlugin,an as instantiatePrefab,uo as intersectRects,ho as invertMatrix4,ke as isBuiltinComponent,$ as isCustomExtension,ko as isEditor,R as isKnownAssetExtension,s as isPlatformInitialized,$o as isPlayMode,Bo as isRuntime,cs as isTextureRef,i as isWeChat,o as isWeb,jr as layoutGroupPlugin,Br as listViewPlugin,Js as loadComponent,Nr as loadPhysicsModule,ra as loadRuntimeScene,Gs as loadSceneData,qs as loadSceneWithAssets,F as looksLikeAssetPath,As as parseAnimClipData,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,_o as pointInOBB,po as pointInWorldRect,mn as prefabsPlugin,lr as progressBarPlugin,be as quat,Is as registerAnimClip,ze as registerComponent,Ds as registerComponentAssetFields,Xs as registerComponentEntityFields,Rn as registerDrawCallback,rn as registerEmbeddedAssets,Ms as registerMaterialCallback,Vs as remapEntityFields,Ar as safeAreaPlugin,hi as sceneManagerPlugin,fo as screenToWorld,_r as scrollViewPlugin,Fo as setEditorMode,Fr as setListViewRenderer,ya as setLogLevel,zo as setPlayMode,_t as setWasmErrorHandler,bn as shutdownDrawAPI,si as shutdownGLDebugAPI,Dn as shutdownGeometryAPI,ms as shutdownMaterialAPI,Xn as shutdownPostProcessAPI,Qn as shutdownRendererAPI,Ia as shutdownTweenAPI,Sr as sliderPlugin,$s as spriteAnimatorSystemUpdate,el as statsPlugin,Yi as syncFillSpriteSize,Vo as textInputPlugin,ro as textPlugin,U as toBuildPath,nr as togglePlugin,Vr as transitionTo,Oo as uiInteractionPlugin,Ao as uiLayoutPlugin,vo as uiMaskPlugin,il as uiPlugins,Yr as uiRenderOrderPlugin,Fs as unregisterAnimClip,Ie as unregisterComponent,In as unregisterDrawCallback,Qs as updateCameraAspectRatio,ye as vec2,we as vec3,xe as vec4,va as warn,ui as wrapSceneSystem,j as wxFileExists,X as wxFileExistsSync,N as wxGetImagePixels,V as wxLoadImage,G as wxLoadImagePixels,L as wxReadFile,H as wxReadTextFile,Y as wxWriteFile};+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function i(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function r(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 h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}function f(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}class p{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,t.volume??1)),this.muted_=t.muted??!1,this.gainNode_.gain.value=this.muted_?0:this.volume_}get name(){return this.name_}get node(){return this.gainNode_}get volume(){return this.volume_}set volume(e){this.volume_=Math.max(0,Math.min(1,e)),this.muted_||this.gainNode_.gain.setTargetAtTime(this.volume_,this.gainNode_.context.currentTime,.015)}get muted(){return this.muted_}set muted(e){this.muted_=e,this.gainNode_.gain.setTargetAtTime(e?0:this.volume_,this.gainNode_.context.currentTime,.015)}connect(e){e instanceof p?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class m{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new p(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new p(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new p(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new p(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new p(e,{name:"voice",volume:t.voiceVolume??1}),this.master.addChild(this.voice),this.buses_.set("master",this.master),this.buses_.set("music",this.music),this.buses_.set("sfx",this.sfx),this.buses_.set("ui",this.ui),this.buses_.set("voice",this.voice)}getBus(e){return this.buses_.get(e)}createBus(e){const t=new p(this.context_,e),n=e.parent?this.buses_.get(e.parent):this.master;return n&&n.addChild(t),this.buses_.set(e.name,t),t}}class g{constructor(e,t=16){this.pool_=[],this.activeCount_=0,this.context_=e;for(let e=0;e<t;e++)this.pool_.push(this.createNode())}createNode(){const e=this.context_.createGain(),t=this.context_.createStereoPanner();return e.connect(t),{gain:e,panner:t,source:null,inUse:!1,startTime:0}}acquire(){let e=this.pool_.find(e=>!e.inUse);return e||(e=this.createNode(),this.pool_.push(e)),e.inUse=!0,e.startTime=this.context_.currentTime,e.gain.gain.value=1,e.panner.pan.value=0,this.activeCount_++,e}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}}class _{constructor(e,t,n){this.panWarned_=!1,this.id=e,this.ctx_=t,this.contexts_=n}stop(){this.ctx_.stop(),this.ctx_.destroy(),this.contexts_.delete(this.id)}pause(){this.ctx_.pause()}resume(){this.ctx_.play()}setVolume(e){this.ctx_.volume=e}setPan(e){this.panWarned_||(console.warn("[Audio] WeChat InnerAudioContext does not support stereo panning"),this.panWarned_=!0)}setLoop(e){this.ctx_.loop=e}setPlaybackRate(e){this.ctx_.playbackRate=e}get isPlaying(){return!this.ctx_.paused}get currentTime(){return this.ctx_.currentTime}get duration(){return this.ctx_.duration}}class y{constructor(){this.name="WeChat",this.contexts_=new Map,this.urlCache_=new Map,this.nextId_=0}get mixer(){return null}get isReady(){return!0}async initialize(e){}async ensureResumed(){}async loadBuffer(e){const t=++this.nextId_;return this.urlCache_.set(t,e),{id:t,duration:0}}unloadBuffer(e){this.urlCache_.delete(e.id)}play(e,t){const n=this.urlCache_.get(e.id);if(!n)throw new Error(`Buffer ${e.id} not found`);const s=wx.createInnerAudioContext();s.loop=t.loop??!1,s.volume=t.volume??1,s.playbackRate=t.playbackRate??1,s.startTime=t.startOffset??0,s.obeyMuteSwitch=!1;const i=++this.nextId_;this.contexts_.set(i,s);const o=new _(i,s,this.contexts_);return s.onEnded(()=>{o.onEnd?.(),s.loop||(s.destroy(),this.contexts_.delete(i))}),s.onError(e=>{console.error(`[WeChatAudio] Playback error for "${n}":`,e.errMsg)}),s.src=n,s.play(),o}suspend(){for(const e of this.contexts_.values())e.pause()}resume(){for(const e of this.contexts_.values())e.paused&&e.play()}dispose(){for(const e of this.contexts_.values())e.destroy();this.contexts_.clear(),this.urlCache_.clear()}}function w(e,t){return new Promise((n,s)=>{const i=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===i?"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 x(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 v=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],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},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0}],b={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",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",bmfont:"application/json",fnt:"text/plain"},S=new Map,M=new Set;for(const e of v)for(const t of e.extensions)S.set(t,e),M.add(t);function P(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function T(e){return S.get(P(e))}function E(e){return T(e)?.editorType??"unknown"}function C(e){return T(e)?.addressableType??null}function A(e){for(const t of v)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function R(e){return M.has(e.toLowerCase())}function I(){return M}function k(e){return"string"==typeof e&&(!!e.includes("/")&&R(P(e)))}function F(){const e=[];for(const t of v)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function B(){return F().map(e=>({type:"suffix",value:e}))}function z(e){return b[e.toLowerCase()]}function $(e){const t=T(e);return t?.wechatPackInclude??!1}function U(e){const t=T(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const n=e.lastIndexOf(".");return n>=0?e.substring(0,n)+".json":e}function W(e,t){for(const n of v)n.editorType===e&&(n.buildTransform=t)}function D(e){return T(e)?.buildTransform}let O=null;function L(){return O||(O=wx.getFileSystemManager()),O}function H(e,t){const n=t.toLowerCase();if(n.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 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 j(e){return new Promise((t,n)=>{L().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(H(e,t.errMsg)))}})})}function X(e,t="utf-8"){return new Promise((n,s)=>{L().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(H(e,t.errMsg)))}})})}function N(e){return new Promise(t=>{L().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function Y(e){const t=L();try{return t.accessSync(e),!0}catch{return!1}}function V(e,t){return new Promise((n,s)=>{L().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function q(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 G(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 i=s.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(i.data.buffer)}}async function K(e){return G(await q(e))}let J=!1;const Q=new class{constructor(){this.name="wechat",this.inputCleanup_=null}async fetch(e,t){return w(e,t)}async readFile(e){return function(e){return L().readFileSync(e)}(U(e))}async readTextFile(e){return function(e,t="utf-8"){return L().readFileSync(e,t)}(U(e))}async fileExists(e){return Y(U(e))}async loadImagePixels(e){return K(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return x(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){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t=>e.onKeyDown(t.code),s=t=>e.onKeyUp(t.code),i="function"==typeof wx.onKeyDown;i&&(wx.onKeyDown(n),wx.onKeyUp(s));const o=t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX,n.clientY)},r=t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX,n.clientY)},a=t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)};wx.onTouchStart(o),wx.onTouchMove(r),wx.onTouchEnd(a),this.inputCleanup_=()=>{i&&(wx.offKeyDown(n),wx.offKeyUp(s)),wx.offTouchStart(o),wx.offTouchMove(r),wx.offTouchEnd(a)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new y}},Z=1920,ee=1080,te=100,ne=512,se={x:100,y:100},ie="Arial",oe=24,re=1.2,ae=.5,le=1/60,ce={x:0,y:-9.81},ue=1/60,he="default",de={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function fe(e){e.Text&&(e.Text._default.fontFamily=de.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=de.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=de.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=de.canvasMatchWidthOrHeight)}const pe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function me(e,t){if(void 0!==t.maxDeltaTime&&(de.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(de.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(de.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(de.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(de.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");de.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&(de.canvasScaleMode=pe[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(de.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight)}const ge=0,_e=4294967295,ye=4294967295,we=0,xe=(e=0,t=0)=>({x:e,y:t}),ve=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),be=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),Se=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),Me=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function Pe(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(Pe);const t={};for(const n in e)t[n]=Pe(e[n]);return t}let Te=0;function Ee(e,t){const n=++Te,s=function(e){for(const t in e){const n=e[t];if(null!==n&&"object"==typeof n)return!0}return!1}(t);return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>s?e?{...Pe(t),...e}:Pe(t):e?{...t,...e}:{...t}}}function Ce(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function Ae(e,t){const n=$e.get(e)??Ce().get(e);if(n)return n;const s=Ee(e,t);return Ce().set(e,s),$e.set(e,s),Be(e,t,!1),s}function Re(e){const t=$e.get(e)??Ce().get(e);if(t)return t;const n=Ee(e,{});return Ce().set(e,n),$e.set(e,n),Be(e,{},!0),n}function Ie(e){return Ce().get(e)}function ke(){const e=Ce();for(const t of e.keys())$e.delete(t);e.clear()}function Fe(e){Ce().delete(e),$e.delete(e)}function Be(e,t,n){const s=globalThis;s.__esengine_registerComponent&&s.__esengine_registerComponent(e,t,n)}function ze(e){return!0===e._builtin}const $e=new Map;function Ue(e,t){$e.set(e,t)}function We(e){return $e.get(e)??Ie(e)}function De(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return $e.set(e,n),n}const Oe={Perspective:0,Orthographic:1},Le={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},He={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},je=De("Transform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}}),Xe=je,Ne=je,Ye=De("Sprite",{texture:_e,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),Ve=De("Camera",{projectionType:Oe.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:Le.ColorAndDepth}),qe=De("Canvas",{designResolution:{x:Z,y:ee},pixelsPerUnit:100,scaleMode:He.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Ge=De("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Ke=De("Parent",{entity:0}),Je=De("Children",{entities:[]}),Qe=De("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:ye,enabled:!0}),Ze=De("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),et=Ae("Name",{value:""}),tt=Ae("SceneOwner",{scene:"",persistent:!1});function nt(e){const t=We(e);return t?Pe(t._default):null}const st=De("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),it=De("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ot=De("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),rt=De("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),at={Static:0,Kinematic:1,Dynamic:2};let lt=0;function ct(e,t){const n=++lt;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function ut(e){return{_type:"res",_resource:e}}function ht(e){return{_type:"res_mut",_resource:e}}class dt{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class ft{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new dt(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const pt=ct({delta:0,elapsed:0,frameCount:0},"Time");function mt(e,t,n){const s=[];for(const[e,i]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const n=gt(t[e]),o=gt(i);"null"!==n&&"undefined"!==n&&(n!==o&&null!=i&&s.push({field:e,expected:n,actual:o,value:i}))}return s}function gt(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function _t(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let yt=null;function wt(e){yt=e}function xt(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),yt&&yt(e,t)}function vt(e){let t=!1;for(const n of Object.keys(e)){const s=e[n];if(null!=s&&"object"==typeof s&&!Array.isArray(s)){if("r"in s&&"g"in s&&"b"in s&&"a"in s&&!("x"in s)){t=!0;break}}}if(!t)return e;const n={};for(const t of Object.keys(e)){const s=e[t];if(null==s||"object"!=typeof s||Array.isArray(s))n[t]=s;else{const e=s;n[t]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:s}}return n}let bt=1;const St=new WeakMap;function Mt(e){let t=St.get(e);return void 0===t&&(t=bt++,St.set(e,t)),t}const Pt=[];function Tt(e,t=[],n=[]){Pt.length=0;for(const t of e)Pt.push(Mt(t));Pt.sort((e,t)=>e-t);let s=Pt.join(",");if(t.length>0){Pt.length=0;for(const e of t)Pt.push(Mt(e));Pt.sort((e,t)=>e-t),s+="|+"+Pt.join(",")}if(n.length>0){Pt.length=0;for(const e of n)Pt.push(Mt(e));Pt.sort((e,t)=>e-t),s+="|-"+Pt.join(",")}return s}class Et{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw xt(e,"spawn"),e}else e=++this.nextEntityId_;let t=0;if(this.module_&&this.cppRegistry_)try{t=this.module_.registry_getGeneration(this.cppRegistry_,e)}catch{}else t=++this.nextGeneration_;this.entities_.set(e,t),this.worldVersion_++;for(const t of this.spawnCallbacks_)try{t(e)}catch{}return e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch{}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){xt(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t){this.tsStorage_.get(n)?.delete(e),this.componentAddedTicks_.get(n)?.delete(e),this.componentChangedTicks_.get(n)?.delete(e);let t=this.componentRemovedBuffer_.get(n);t||(t=[],this.componentRemovedBuffer_.set(n,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(n){xt(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){xt(t,`removeParent(entity=${e})`)}}insert(e,t,n){return ze(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(ze(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,vt(n))}catch(n){xt(n,`set(${t._name}, entity=${e})`)}this.recordChangedTick_(t,e)}else this.getStorage(t).set(e,n),this.recordChangedTick_(t,e)}get(e,t){return ze(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return ze(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(ze(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return xt(n,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");ze(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_,s=n[`add${e}`],i=n[`get${e}`],o=n[`has${e}`],r=n[`remove${e}`];if("function"!=typeof s||"function"!=typeof i||"function"!=typeof o||"function"!=typeof r)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:s.bind(n),get:i.bind(n),has:o.bind(n),remove:r.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=mt(t._name,t._default,s);if(e.length>0)throw new Error(_t(t._name,e))}const i={...t._default,...s};let o=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);o=!n.has(e),n.add(e,vt(i))}catch(n){xt(n,`insertBuiltin(${t._name}, entity=${e})`)}return o&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let n=!1;for(const s of Object.keys(t)){const i=t[s];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){const t=e[s];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){n=!0;break}}}if(!n)return e;const s={};for(const n of Object.keys(e)){const i=e[n],o=t[n];if(null==i||"object"!=typeof i||Array.isArray(i)||null==o||"object"!=typeof o||Array.isArray(o))s[n]=i;else{const e=i,t=o;s[n]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:i}}return s}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(n){return xt(n,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(n){return xt(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){xt(n,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const i=mt(t._name,t._default,e);if(i.length>0)throw new Error(_t(t._name,i));s=e}const i=t.create(s),o=this.getStorage(t),r=!o.has(e);o.set(e,i);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.recordRemovedTick_(t,e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0}getComponentTypes(e){const t=new Set;for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.add(n)}catch{}if(this.cppRegistry_)for(const[n,s]of $e)if(ze(s)&&!t.has(n))try{this.getBuiltinMethods(s._cppName).has(e)&&t.add(n)}catch{}const n=this.entityComponents_.get(e);if(n){const e=Ce();for(const s of n)for(const[n,i]of e)if(i._id===s){t.add(n);break}}return Array.from(t)}getEntitiesWithComponents(e,t=[],n=[],s){if(0===e.length&&0===t.length&&0===n.length)return this.getAllEntities();const i=s??Tt(e,t,n),o=this.queryCache_.get(i);if(o&&o.version===this.worldVersion_)return o.result;let r=null,a=1/0;for(const t of e)if(!ze(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<a&&(a=n,r=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=r?r.keys():this.entities_.keys();for(const s of c){let i=!0;for(const t of e)if(!this.has(s,t)){i=!1;break}if(i)for(const e of t)if(!this.has(s,e)){i=!1;break}if(i)for(const e of n)if(this.has(s,e)){i=!1;break}i&&l.push(s)}return this.queryCache_.set(i,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,n){const s=this.componentAddedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}isChangedSince(e,t,n){const s=this.componentChangedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}getRemovedEntitiesSince(e,t){const n=this.componentRemovedBuffer_.get(e._id);if(!n)return[];const s=[];for(const e of n)e.tick>t&&s.push(e.entity);return s}cleanRemovedBuffer(e){for(const[t,n]of this.componentRemovedBuffer_){let s=0;for(let t=0;t<n.length;t++)n[t].tick>=e&&(n[s++]=n[t]);n.length=s,0===s&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let n=this.componentAddedTicks_.get(e._id);n||(n=new Map,this.componentAddedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordChangedTick_(e,t){let n=this.componentChangedTicks_.get(e._id);n||(n=new Map,this.componentChangedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordRemovedTick_(e,t){let n=this.componentRemovedBuffer_.get(e._id);n||(n=[],this.componentRemovedBuffer_.set(e._id,n)),n.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function Ct(e){return{_type:"mut",_component:e}}function At(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Rt(e){return{_filterType:"added",_component:e}}function It(e){return{_filterType:"changed",_component:e}}function kt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Ft(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Bt(e){return At(e)||kt(e)||Ft(e)?e._component:e}function zt(e,t=[],n=[]){const s=[],i=[],o=[];return e.forEach((e,t)=>{At(e)&&s.push(t),kt(e)?i.push({index:t,component:e._component}):Ft(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:o,with:(...s)=>zt(e,[...t,...s],n),without:(...s)=>zt(e,t,[...n,...s])}}function $t(...e){return zt(e)}class Ut{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(Bt),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=Tt(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:n}=this.descriptor_;if(0===t.length&&0===n.length)return!0;const s=this.lastRunTick_;for(const n of t)if(!this.world_.isAddedSince(e,n.component,s))return!1;for(const t of n)if(!this.world_.isChangedSince(e,t.component,s))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=t.length,i=e.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const u of n)if(!o||this.passesChangeFilters_(u)){if(null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}r[0]=u;for(let e=0;e<s;e++)r[e+1]=this.world_.get(u,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];c=u}yield r}}finally{if(this.world_.endIteration(),null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function Wt(e){return{_type:"removed",_component:e}}class Dt{constructor(e,t,n){this.world_=e,this.component_=t,this.lastRunTick_=n}*[Symbol.iterator](){yield*this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}isEmpty(){return 0===this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_).length}toArray(){return this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}}function Ot(){return{_type:"commands"}}class Lt{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=ze(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 Ht{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Lt(this,null);return this.spawned_.push(e),e}entity(e){return new Lt(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"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}function jt(e){return{_id:Symbol(`Event_${e}`),_name:e}}class Xt{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(e){this.writeBuffer_.push(e)}getReadBuffer(){return this.readBuffer_}swap(){const e=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=e,this.writeBuffer_.length=0}}class Nt{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Xt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Xt,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function Yt(e){return{_type:"event_writer",_event:e}}function Vt(e){return{_type:"event_reader",_event:e}}class qt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class Gt{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var Kt;function Jt(){return{_type:"get_world"}}!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(Kt||(Kt={}));let Qt=0;function Zt(e,t,n){const s=++Qt;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function en(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function tn(e){en().push({schedule:Kt.Update,system:e})}function nn(e){en().push({schedule:Kt.Startup,system:e})}function sn(e,t){en().push({schedule:e,system:t})}class on{constructor(e,t,n){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=n??null}setTimingEnabled(e){this.timings_=e?new Map:null}getTimings(){return this.timings_}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);const n=this.timings_?performance.now():0;try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Ht&&t[e].flush()}finally{this.timings_&&this.timings_.set(e._name,performance.now()-n),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new Ut(this.world_,e,this.currentLastRunTick_);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Ht(this.world_,this.resources_);case"event_writer":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new qt(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Gt(n)}case"removed":{const t=e;return new Dt(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class rn{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 an=ct(new rn,"Input");class ln{constructor(e){this.target_=e??null}build(e){const n=new rn;e.insertResource(an,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(Kt.Last,Zt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const cn=new ln,un=ct({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var hn;function dn(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"}(hn||(hn={}));let fn=null,pn=null,mn=1;const gn=new Map;function _n(e){fn=e,pn=e.getResourceManager(),En()}function yn(){0!==bn&&fn&&(fn._free(bn),bn=0),gn.clear(),mn=1,vn=!1,Mn.clear(),Pn=null,pn=null,fn=null}function wn(){if(!pn)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return pn}const xn={createShader:(e,t)=>wn().createShader(e,t),releaseShader(e){e>0&&wn().releaseShader(e)},create(e){const t=mn++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??hn.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 gn.set(t,n),t},get:e=>gn.get(e),setUniform(e,t,n){const s=gn.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,fn?.invalidateMaterialCache(e))},getUniform(e,t){const n=gn.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=gn.get(e);n&&(n.blendMode=t,fn?.invalidateMaterialCache(e))},getBlendMode(e){const t=gn.get(e);return t?.blendMode??hn.Normal},setDepthTest(e,t){const n=gn.get(e);n&&(n.depthTest=t,fn?.invalidateMaterialCache(e))},getShader(e){const t=gn.get(e);return t?.shader??0},release(e){gn.delete(e),fn?.invalidateMaterialCache(e)},isValid:e=>gn.has(e),releaseAll(){gn.clear(),fn?.clearMaterialCache()},createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??hn.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=gn.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=mn++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return gn.set(n,s),n},toAssetData(e,t){const n=gn.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=gn.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let vn=!1,bn=0;const Sn=16384,Mn=new Map;let Pn=null;function Tn(e){const t=(0===bn&&fn&&(bn=fn._malloc(Sn)),bn);if(0===t||!fn)return{ptr:0,count:0};let n=0,s=0;const i=fn.HEAPU8,o=fn.HEAPU32,r=fn.HEAPF32;for(const[a,l]of e){if(dn(l))continue;let e=Mn.get(a);e||(Pn||(Pn=new TextEncoder),e=Pn.encode(a),Mn.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(n+(4+u+4+16)>Sn){console.warn(`[ESEngine] Material uniform buffer full (${n}/${Sn} bytes), skipping remaining uniforms`);break}o[t+n>>2]=c,n+=4,i.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)r[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function En(){if(!fn||vn)return;fn.materialDataProvider=(e,t,n,s,i)=>{const o=gn.get(e);if(!o)return fn.HEAPU32[t>>2]=0,fn.HEAPU32[n>>2]=0,fn.HEAPU32[s>>2]=0,void(fn.HEAPU32[i>>2]=0);fn.HEAPU32[t>>2]=o.shader,fn.HEAPU32[n>>2]=o.blendMode;const{ptr:r,count:a}=Tn(o.uniforms);fn.HEAPU32[s>>2]=r,fn.HEAPU32[i>>2]=a},vn=!0}const Cn={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 An{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.pending_.get(e);if(i&&!i.aborted)return i.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const s=t(),i=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,i),this.pending_.delete(e),i})(),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 Rn{constructor(e,t=""){this.cache_=new An,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&&(xn.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())xn.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(i);return{handle:xn.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}}function In(e){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function kn(e,t,n){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>{const t={texture:n.get(e.texture)??0};if(e.atlasFrame){const n=e.atlasFrame;t.uvOffset={x:n.x/n.pageWidth,y:1-(n.y+n.height)/n.pageHeight},t.uvScale={x:n.width/n.pageWidth,y:n.height/n.pageHeight}}return t})}}const Fn=new Map;function Bn(e){Fn.set(e.name,e)}function zn(e){Fn.delete(e)}function $n(e){return Fn.get(e)}function Un(){Fn.clear()}const Wn=Ae("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function Dn(e,t){const n=e.getEntitiesWithComponents([Wn]);for(const s of n){const n=e.get(s,Wn);if(!n.enabled||!n.playing||!n.clip)continue;const i=Fn.get(n.clip);if(!i||0===i.frames.length)continue;const o=1/(i.fps*n.speed),r=0===n.frameTimer&&0===n.currentFrame;n.frameTimer+=t;let a=r;if(n.frameTimer>=o&&(n.frameTimer-=o,n.currentFrame++,n.currentFrame>=i.frames.length&&(n.loop&&i.loop?n.currentFrame=0:(n.currentFrame=i.frames.length-1,n.playing=!1)),a=!0),a&&e.has(s,Ye)){const t=i.frames[n.currentFrame],o=e.get(s,Ye);o.texture=t.texture,t.uvOffset&&(o.uvOffset=t.uvOffset,o.uvScale=t.uvScale),e.insert(s,Ye,o)}a&&e.insert(s,Wn,n)}}class On{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null,this.bgmVolume_=1,this.disposed_=!1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}static async preload(e){if(this.bufferCache_.has(e))return;const t=await this.backend_.loadBuffer(e);this.bufferCache_.set(e,t)}static async preloadAll(e){await Promise.all(e.map(e=>this.preload(e)))}static playSFX(e,t){const n={bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0},s=this.bufferCache_.get(e);if(!s){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const s=this.bufferCache_.get(e);s&&t.resolve(this.backend_.play(s,n))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(s,n)}static playBGM(e,t){const n=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const n=t?.volume??1,s=this.bgmVolume_;this.bgmVolume_=n,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,s):this.bgmHandle_&&this.bgmHandle_.stop();const i=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:i?0:n,loop:!0}),i&&this.fadeIn(this.bgmHandle_,i,n)},s=this.bufferCache_.get(e);s?n(s):this.preload(e).then(()=>{if(this.disposed_)return;const t=this.bufferCache_.get(e);t&&n(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else this.bgmHandle_.stop(),this.bgmHandle_=null}static setMasterVolume(e){this.mixer_&&(this.mixer_.master.volume=e)}static setMusicVolume(e){this.mixer_&&(this.mixer_.music.volume=e)}static setSFXVolume(e){this.mixer_&&(this.mixer_.sfx.volume=e)}static setUIVolume(e){this.mixer_&&(this.mixer_.ui.volume=e)}static muteBus(e,t){const n=this.mixer_?.getBus(e);n&&(n.muted=t)}static getBufferHandle(e){return this.bufferCache_.get(e)}static dispose(){this.disposed_=!0,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}static fadeIn(e,t,n){e.setVolume(0);const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(r*n),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,n){const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(n*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}static createDeferredHandle(){let e=null;return{id:-1,stop(){e?.stop()},pause(){e?.pause()},resume(){e?.resume()},setVolume(t){e?.setVolume(t)},setPan(t){e?.setPan(t)},setLoop(t){e?.setLoop(t)},setPlaybackRate(t){e?.setPlaybackRate(t)},get isPlaying(){return e?.isPlaying??!1},get currentTime(){return e?.currentTime??0},get duration(){return e?.duration??0},resolve(t){e=t}}}}On.mixer_=null,On.bufferCache_=new Map,On.bgmHandle_=null,On.bgmVolume_=1,On.fadeAnimId_=0,On.disposed_=!1;const Ln=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}],["AudioSource",{fields:[{field:"clip",type:"audio"}]}]]);function Hn(e,t){Ln.set(e,t)}function jn(e){const t=Ln.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 Xn(e){return Ln.get(e)?.fields??[]}function Nn(e){return Ln.get(e)?.spine??null}const Yn=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Vn(e,t){Yn.set(e,t)}function qn(e){return Yn.get(e)}function Gn(e,t){const n=Yn.get(e.type);if(!n)return;const s=e.data;for(const i of n){const n=s[i];if("number"==typeof n&&0!==n){const o=t.get(n);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${n} which does not exist`),s[i]=void 0!==o?o:0}}}function Kn(e,t){const n=new Map;for(const s of t.entities){if(!1===s.visible)continue;const t=e.spawn();n.set(s.id,t),e.insert(t,et,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;const t=n.get(s.id);for(const i of s.components)Gn(i,n),es(e,t,i,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),i=n.get(s.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return n}function Jn(e,t){return Kn(e,t)}async function Qn(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl??s?.baseUrl,o=new Map;s&&await async function(e,t,n,s,i){const o=new Map;for(const e of Zn.keys())o.set(e,new Set);const r=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ln.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...Zn.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,n,s);l.set(e,r)}),u=r.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});if(await Promise.all([...c,...u]),i){for(const e of s.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ln.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const s=n[e.field];if("string"!=typeof s||!s)continue;const i=t.get(s);void 0!==i&&(n[e.field]=i)}}}(t,s,i,o,n?.collectAssets);const r=Kn(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}const Zn=new Map([["texture",{async load(e,t,n,s){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),s.set(e,o)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(o),i}}],["material",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,n);s.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["font",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,n);s.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["anim-clip",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=In(i),r=new Map,a=o.map(async e=>{try{const i=n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),s.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);Bn(kn(e,i,r))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(i),new Map}}],["audio",{async load(e,t,n){const s=[...e].map(e=>n?`${n}/${e}`:`/${e}`);return await On.preloadAll(s).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}]]);function es(e,t,n,s){if("LocalTransform"!==n.type&&"WorldTransform"!==n.type||(n.type="Transform"),"UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===n.type){const e=n.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=We(n.type);if(i)e.insert(t,i,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function ts(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 ns(e,t){const n=e.getEntitiesWithComponents([et]);for(const s of n){const n=e.get(s,et);if(n&&n.value===t)return s}return null}class ss{constructor(e){this.textureCache_=new An,this.shaderCache_=new An,this.jsonCache_=new An,this.textCache_=new An,this.binaryCache_=new An,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new An,this.prefabCache_=new An,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=h(de.textCanvasSize,de.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Rn(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),i=this.textureCache_.get(s);if(!i)continue;const o=(this.textureRefCounts_.get(s)??1)-1;o<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),xn.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const i=this.resolveUrl(t,n),o=await this.fetchText(i);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=r?`${r}/${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"===T(e)?.contentType,h=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(h,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),i=l.find(e=>e.name===n);if(i){const n=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,i.info.width,i.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=T(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const i=n?`${n}/${s}`:s;return this.loadFntFile(i)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${s}`:s,r=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,r.handle,r.width,r.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,async()=>{const e=await this.fetchJson(n);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const n of e.entities){for(const e of n.components){if(!e.data)continue;for(const n of jn(e.type)){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}const n=Nn(e.type);if(n)for(const s of[n.skeletonField,n.atlasField]){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}}if(n.nestedPrefab?.prefabPath){const e=t(n.nestedPrefab.prefabPath);e&&(n.nestedPrefab.prefabPath=e)}}}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return Qn(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const i=s.metadata?.atlas;i&&n.push(this.loadSpine(s.path,i).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.loadImageFromSrc(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){return new Promise((n,s)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(i)},i.onerror=()=>s(new Error(`Failed to load image: ${e}`)),i.src=e})}createTextureFromImage(e,t){const{width:n,height:s}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,i){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const r=this.module_.GL,a=r.getNewId(r.textures);r.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 i=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(o);const r=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=r.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.getEmbedded(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:i}=this.parseEsShader(t);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return xn.createShader(s,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:o}=this.parseEsShader(s);if(!i||!o)throw new Error(`Invalid shader format: ${e}`);return xn.createShader(i,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://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(U(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(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 r(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.getEmbedded(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 r(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.getEmbedded(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 r(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let i="";for(const e of s){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const is=ct(null,"Assets");class os{build(e){const t=e.wasmModule;t?e.insertResource(is,new ss(t)):console.warn("AssetPlugin: No WASM module available")}}const rs=new os;class as{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 ls(e,t){const n=e.getResource(is);n&&n.registerEmbeddedAssets(t)}async function cs(e,t,n){const{entities:s,rootId:i}=await hs(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}))},r=await Qn(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=r.get(i);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:r}}const us=10;async function hs(e,t,n,s,i,o=0){if(o>us)throw new Error(`Prefab nesting depth exceeded ${us}. Check for deep or circular nesting in: ${e.name}`);const r=new Map;let a;if(void 0===s){a=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=s;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(i?.has(s.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${s.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await hs(e,s.nestedPrefab.overrides,n,a,i,o+1);r.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?r.get(s.parent)??null:null),l.push(...t.entities);continue}const c=r.get(s.prefabEntityId),u=s.prefabEntityId===e.rootEntityId,h={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:u?null:null!==s.parent?r.get(s.parent)??null:null,children:s.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};ds(h.components,r),fs(h,t),l.push(h)}const c=r.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function ds(e,t){for(const n of e){const e=qn(n.type);if(e)for(const s of e){const e=n.data[s];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(n.data[s]=i)}}}}function fs(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 ps{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,i=await this.assetServer_.loadPrefab(s,t?.baseUrl);return cs(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const ms=ct(null,"Prefabs");class gs{constructor(){this.name="PrefabsPlugin",this.dependencies=[is]}build(e){const t=e.getResource(is);e.insertResource(ms,new ps(e.world,t))}}const _s=new gs;let ys=null,ws=0,xs=0,vs=0;const bs=new Float32Array(256);function Ss(e){ys=e,ws=ys._malloc(64),xs=ys._malloc(64),vs=ys._malloc(1024)}function Ms(){ys&&(ws&&(ys._free(ws),ws=0),xs&&(ys._free(xs),xs=0),vs&&(ys._free(vs),vs=0)),ys=null}function Ps(){if(!ys)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return ys}const Ts={r:1,g:1,b:1,a:1},Es={begin(e){const t=Ps();try{t.HEAPF32.set(e,ws/4),t.draw_begin(ws)}catch(e){xt(e,"Draw.begin")}},end(){try{Ps().draw_end()}catch(e){xt(e,"Draw.end")}},line(e,t,n,s=1){try{Ps().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){xt(e,"Draw.line")}},rect(e,t,n,s=!0){try{Ps().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){xt(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{Ps().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){xt(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{Ps().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){xt(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{Ps().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){xt(e,"Draw.circleOutline")}},texture(e,t,n,s=Ts){try{Ps().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){xt(e,"Draw.texture")}},textureRotated(e,t,n,s,i=Ts){try{Ps().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){xt(e,"Draw.textureRotated")}},setLayer(e){Ps().draw_setLayer(e)},setDepth(e){Ps().draw_setDepth(e)},getDrawCallCount:()=>ys?ys.draw_getDrawCallCount():0,getPrimitiveCount:()=>ys?ys.draw_getPrimitiveCount():0,setBlendMode(e){Ps().draw_setBlendMode(e)},setDepthTest(e){Ps().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=Ps();s.HEAPF32.set(n,xs/4),s.draw_mesh(e,t,xs)}catch(n){xt(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=Ps(),i=xn.get(t);if(!i)return;if(Es.setBlendMode(i.blendMode),Es.setDepthTest(i.depthTest),0===i.uniforms.size)return void Es.drawMesh(e,i.shader,n);let o;if(s.HEAPF32.set(n,xs/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,n]of i.uniforms){const s=Rs(t);if(!(s<0)){if(dn(n))bs[o++]=10,bs[o++]=s,bs[o++]=n.slot??e++,bs[o++]=n.textureId;else if("number"==typeof n)bs[o++]=1,bs[o++]=s,bs[o++]=n;else if(Array.isArray(n)){bs[o++]=n.length,bs[o++]=s;for(let e=0;e<n.length;e++)bs[o++]=n[e]}else"w"in n?(bs[o++]=4,bs[o++]=s,bs[o++]=n.x,bs[o++]=n.y,bs[o++]=n.z,bs[o++]=n.w):"z"in n?(bs[o++]=3,bs[o++]=s,bs[o++]=n.x,bs[o++]=n.y,bs[o++]=n.z):(bs[o++]=2,bs[o++]=s,bs[o++]=n.x,bs[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<o)&&(i.cachedBuffer_=new Float32Array(o)),i.cachedBuffer_.set(bs.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void s.draw_mesh(e,i.shader,xs);s.HEAPF32.set(i.cachedBuffer_.subarray(0,o),vs/4),s.draw_meshWithUniforms(e,i.shader,xs,vs,o)}catch(n){xt(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Cs={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},As=new Set;function Rs(e){const t=Cs[e];return void 0!==t?t:(As.has(e)||(As.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Cs).join(", ")}`)),-1)}const Is=new Map;function ks(e,t,n){Is.set(e,{fn:t,scene:n??""})}function Fs(e){Is.delete(e)}function Bs(){Is.clear()}var zs;!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"}(zs||(zs={}));let $s=null,Us=0,Ws=0,Ds=0;function Os(e){$s=e,Us=$s._malloc(262144),Ws=$s._malloc(65536),Ds=$s._malloc(256)}function Ls(){$s&&(Us&&$s._free(Us),Ws&&$s._free(Ws),Ds&&$s._free(Ds),Us=0,Ws=0,Ds=0),$s=null}function Hs(){if(!$s)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return $s}const js={create(e){const t=Hs(),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,Us/4);const i=e.layout.length,o=new Int32Array(i);for(let t=0;t<i;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Ds,i).set(o),t.geometry_init(n,Us,s,Ds,i,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Ws,s).set(e.indices),t.geometry_setIndices16(n,Ws,s)}else{new Uint32Array(t.HEAPU8.buffer,Ws,s).set(e.indices),t.geometry_setIndices32(n,Ws,s)}}return n},updateVertices(e,t,n=0){const s=Hs(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,Us/4),s.geometry_updateVertices(e,Us,i,n)},release(e){e>0&&Hs().geometry_release(e)},isValid:e=>!(!$s||e<=0)&&$s.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return js.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:zs.Float2},{name:"a_texCoord",type:zs.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const i=s/t*Math.PI*2,o=Math.cos(i)*e,r=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;n.push(o,r,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return js.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:zs.Float2},{name:"a_texCoord",type:zs.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,i=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(s-t),a=(r.y-n)/(i-n);o.push(r.x,r.y,e,a)}const r=[];for(let t=1;t<e.length-1;t++)r.push(0,t,t+1);return js.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:zs.Float2},{name:"a_texCoord",type:zs.Float2}],indices:new Uint16Array(r)})}};let Xs=null;function Ns(e){Xs=e}function Ys(){Xs&&qs.isInitialized()&&qs.shutdown(),Xs=null}function Vs(){if(!Xs)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Xs}const qs={init(e,t){try{return Vs().postprocess_init(e,t)}catch(n){return xt(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Vs().postprocess_shutdown()}catch(e){xt(e,"PostProcess.shutdown")}},resize(e,t){try{Vs().postprocess_resize(e,t)}catch(n){xt(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Vs().postprocess_addPass(e,t)}catch(t){return xt(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Vs().postprocess_removePass(e)}catch(t){xt(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Vs().postprocess_setPassEnabled(e,t)}catch(t){xt(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Vs().postprocess_isPassEnabled(e)}catch(t){return xt(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{Vs().postprocess_setUniformFloat(e,t,n)}catch(n){xt(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{Vs().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){xt(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Vs().postprocess_begin()}catch(e){xt(e,"PostProcess.begin")}},end(){try{Vs().postprocess_end()}catch(e){xt(e,"PostProcess.end")}},getPassCount(){try{return Vs().postprocess_getPassCount()}catch(e){return xt(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Xs)return!1;try{return Xs.postprocess_isInitialized()}catch(e){return xt(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Vs().postprocess_setBypass(e)}catch(e){xt(e,"PostProcess.setBypass")}},isBypassed(){if(!Xs)return!0;try{return Xs.postprocess_isBypassed()}catch(e){return xt(e,"PostProcess.isBypassed"),!0}},createBlur:()=>xn.createShader(Gs,"#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:()=>xn.createShader(Gs,"#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:()=>xn.createShader(Gs,"#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:()=>xn.createShader(Gs,"#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")},Gs="#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 Ks;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Ks||(Ks={}));let Js=null,Qs=0;function Zs(e){Js=e,Qs=Js._malloc(64)}function ei(){Js&&Qs&&(Js._free(Qs),Qs=0),Js=null}const ti={init(e,t){Js?.renderer_init(e,t)},resize(e,t){Js?.renderer_resize(e,t)},begin(e,t){if(Js&&Qs)try{Js.HEAPF32.set(e,Qs/4),Js.renderer_begin(Qs,t??0)}catch(e){xt(e,"Renderer.begin")}},flush(){try{Js?.renderer_flush()}catch(e){xt(e,"Renderer.flush")}},end(){try{Js?.renderer_end()}catch(e){xt(e,"Renderer.end")}},submitSprites(e){if(Js)try{Js.renderer_submitSprites(e._cpp)}catch(e){xt(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Js)try{Js.renderer_submitBitmapText(e._cpp)}catch(e){xt(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Js)try{Js.renderer_submitSpine?.(e._cpp)}catch(e){xt(e,"Renderer.submitSpine")}},setStage(e){Js?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Js?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Js?.renderer_releaseTarget(e)},getTargetTexture:e=>Js?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Js?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Js?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Js?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){Js?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){Js?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Js?Js.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Js?{drawCalls:Js.renderer_getDrawCalls(),triangles:Js.renderer_getTriangles(),sprites:Js.renderer_getSprites(),text:Js.renderer_getText(),spine:Js.renderer_getSpine?.()??0,meshes:Js.renderer_getMeshes(),culled:Js.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let ni=null;function si(e){ni=e}function ii(){ni=null}const oi={enable(){ni?.gl_enableErrorCheck(!0)},disable(){ni?.gl_enableErrorCheck(!1)},check:e=>ni?.gl_checkErrors(e)??0,diagnose(){ni?.renderer_diagnose()}};class ri{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:o}=e;s===this.lastWidth_&&i===this.lastHeight_||(ti.resize(s,i),qs.isInitialized()&&qs.getPassCount()>0&&qs.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),ti.setViewport(0,0,s,i),ti.clearBuffers(3),ti.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),ti.submitSprites(t),ti.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):ti.submitSpine(t),ti.flush(),this.executeDrawCallbacks(n,o),ti.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:o}=e;ti.setViewport(s.x,s.y,s.w,s.h),ti.setScissor(s.x,s.y,s.w,s.h,!0),ti.clearBuffers(i),ti.setScissor(0,0,0,0,!1),ti.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),ti.submitSprites(t),ti.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):ti.submitSpine(t),ti.flush(),this.executeDrawCallbacks(n,o),ti.end()}executeDrawCallbacks(e,t){const n=Is;if(n.size>0){Es.begin(e);const s=[];for(const[e,i]of n.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}Es.end();for(const e of s)Fs(e)}}}const ai="__scene_transition_overlay__";class li{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class ci{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,tt,{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),ks(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=qs.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){qs.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,tt)){const n=this.app_.world.get(e,tt);n.persistent=t,this.app_.world.insert(e,tt,n)}}}class ui{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(n=>{const s=t.duration??de.sceneTransitionDuration,i=t.color??{...de.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},ks(ai,()=>{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;Es.setLayer(9999),Es.setDepth(9999),Es.rect({x:0,y:0},{x:2e4,y:2e4},{r:i.r,g:i.g,b:i.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{try{n&&n!==e&&await this.unload(n,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,Fs(ai),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Fs(ai),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new li(t);this.scenes_.set(e,n);const s=new ci(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(is)?this.app_.getResource(is):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new li(t);this.scenes_.set(e,n);const s=new ci(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(is)?this.app_.getResource(is):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const i=t?.keepPersistent??!0;for(const e of n.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,tt)){if(this.app_.world.get(e,tt).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())Fs(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{qs.removePass(e)}catch{}n.postProcessPasses.length=0,this.releaseSceneAssets_(n),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,n,s){if(s){const n={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:n};this.app_.hasResource(is)&&(i.assetServer=this.app_.getResource(is));const o=await Qn(this.app_.world,s,i);e.loadedAssets=n;for(const n of o.values())e.entities.add(n),this.app_.world.insert(n,tt,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=di(this.app_,t,s);this.app_.addSystemToSchedule(e,n)}const i=this.contexts_.get(t);n.setup&&await n.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const n=this.app_.hasResource(is)?this.app_.getResource(is):null;if(n){for(const e of t.textureUrls)n.releaseTexture(e);for(const e of t.fontPaths)n.releaseFont(e);for(const e of t.spineKeys)n.releaseSpine(e)}for(const e of t.materialHandles)xn.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s={};let i=!1;if(n.has(e,Ye)){const t=n.get(e,Ye);s.sprite=t.color.a,t.color.a=0,n.insert(e,Ye,t),i=!0}if(n.has(e,Ze)){const t=n.get(e,Ze);s.spine=t.color.a,t.color.a=0,n.insert(e,Ze,t),i=!0}if(n.has(e,Qe)){const t=n.get(e,Qe);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,Qe,t),i=!0}i&&t.savedAlphas.set(e,s)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s=t.savedAlphas.get(e);if(s){if(void 0!==s.sprite&&n.has(e,Ye)){const t=n.get(e,Ye);t.color.a=s.sprite,n.insert(e,Ye,t)}if(void 0!==s.spine&&n.has(e,Ze)){const t=n.get(e,Ze);t.color.a=s.spine,n.insert(e,Ze,t)}if(void 0!==s.bitmapText&&n.has(e,Qe)){const t=n.get(e,Qe);t.color.a=s.bitmapText,n.insert(e,Qe,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{qs.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 hi=ct(null,"SceneManager");function di(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(hi).getSceneStatus(t)&&n._fn(...s)}}}const fi=Zt([ht(hi),ut(pt)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),pi={name:"SceneManager",build(e){const t=new ui(e);e.insertResource(hi,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(hi),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Kt.Startup,n),e.addSystemToSchedule(Kt.Last,fi)}};class mi{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new Nt,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(Kt.Last);else{this.runSchedule(Kt.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Kt.FixedPreUpdate),this.runSchedule(Kt.FixedUpdate),this.runSchedule(Kt.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(Kt.PreUpdate),this.runSchedule(Kt.Update),this.runSchedule(Kt.PostUpdate),this.runSchedule(Kt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new Et,this.resources_=new ft;for(const e of Object.values(Kt))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new mi}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(Kt.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Kt.Startup,e)}removeSystem(e){let t=!1;for(const[n,s]of this.systems_){const i=s.filter(t=>t.system._id!==e);i.length!==s.length&&(this.systems_.set(n,i),this.sortedSystemsCache_.delete(n),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return wt(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}enableStats(){return this.statsEnabled_=!0,this.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}getEntityCount(){return this.world_.entityCount()}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(hi).register(e),this}setInitialScene(e){return this.getResource(hi).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new on(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(pt)||this.resources_.insert(pt,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(Kt.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(Kt.Last);else{this.runSchedule(Kt.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Kt.FixedPreUpdate),this.runSchedule(Kt.FixedUpdate),this.runSchedule(Kt.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(Kt.PreUpdate),this.runSchedule(Kt.Update),this.runSchedule(Kt.PostUpdate),this.runSchedule(Kt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new on(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(pt,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(Kt.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Bs();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[ii,ei,Ys,Ls,yn,Ms];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const i=t.get(s);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,i=new Set,o=r=>{if(s.has(r))return;if(i.has(r)){const t=e[r].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(r);const a=e[r];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&o(n)}i.delete(r),s.add(r),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));const s=this.phaseTimings_?performance.now():0;for(const e of n)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}this.phaseTimings_&&this.phaseTimings_.set(Kt[e],performance.now()-s)}updateTime(e){const t=this.resources_.get(pt);t.delta=e,t.elapsed+=e,t.frameCount++}}function gi(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const _i=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function yi(e,t,n,s,i){const o=e*t/n,r=e;switch(s){case He.FixedWidth:return o;case He.FixedHeight:return r;case He.Expand:return Math.max(o,r);case He.Shrink:return Math.min(o,r);case He.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const wi=[];function xi(e){if(e<wi.length)return wi[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return wi.push(t),t}function vi(e,t,n,s,i,o){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,tt);return!t||""===t.scene||o.has(t.scene)}):r;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*n/(i.viewportH*s);let a,u=0,h=0;if(i.projectionType===Oe.Orthographic){if(h=i.orthoSize,l){h=yi(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=h*r,a=Si(-u,u,-h,h,-i.farPlane,i.farPlane)}else a=Pi(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const d=Ei(o.position.x,o.position.y,o.position.z),f=xi(c.length);f.entity=e,f.viewProjection.set(Ai(a,d)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=u,f.halfH=h,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const bi=new Float32Array(16);function Si(e,t,n,s,i,o){const r=bi;r.fill(0);const a=t-e,l=s-n,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(s+n)/l,r[14]=-(o+i)/c,r[15]=1,r}const Mi=new Float32Array(16);function Pi(e,t,n,s){const i=Mi;i.fill(0);const o=1/Math.tan(e/2),r=n-s;return i[0]=o/t,i[5]=o,i[10]=(s+n)/r,i[11]=-1,i[14]=2*s*n/r,i}const Ti=new Float32Array(16);function Ei(e,t,n){const s=Ti;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 Ci=new Float32Array(16);function Ai(e,t){const n=Ci;for(let s=0;s<4;s++)for(let i=0;i<4;i++)n[4*i+s]=e[0+s]*t[4*i+0]+e[4+s]*t[4*i+1]+e[8+s]*t[4*i+2]+e[12+s]*t[4*i+3];return n}const Ri={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function Ii(e,t,n,s,i,o,r={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,u=o.left+t.x*a,h=o.bottom+e.y*l,d=o.bottom+t.y*l;let f,p,m,g;e.x===t.x?(f=c+n.x-i.x*r.x,m=f+i.x):(f=c+n.x,m=u+s.x),e.y===t.y?(p=h+n.y-i.y*r.y,g=p+i.y):(p=h+n.y,g=d+s.y);const _=Math.max(0,m-f),y=Math.max(0,g-p);return{originX:f+r.x*_,originY:p+r.y*y,width:_,height:y,rect:{left:f,bottom:p,right:m,top:g}}}const ki=De("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});let Fi=null,Bi=null;function zi(e,t){e.has(t,Ye)||e.insert(t,Ye,{texture:_e,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0})}function $i(e,t){switch(e){case Ri.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Ri.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Ri.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function Ui(e,t){switch(e){case Ri.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case Ri.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case Ri.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1-t}};default:return{anchorMin:{x:t,y:0},anchorMax:{x:t,y:1}}}}function Wi(e,t,n,s){switch(e){case Ri.BottomToTop:case Ri.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function Di(e,t,n,s){if(!e.has(t,ki))return;const i=e.get(t,ki),o=$i(n,s);i.anchorMin=o.anchorMin,i.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(i.size={...i.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,ki,i)}function Oi(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Li(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Hi(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),i=[];for(const t of s){if(!t){i.push("");continue}let s="";for(let o=0;o<t.length;o++){const r=t[o],a=s+r;if(e.measureText(a).width>n&&s){if(Li(r.charCodeAt(0))&&s.length>0&&Li(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!Li(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+r):(i.push(s),s=r)}else i.push(s),s=r}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function ji(e){let t=1;for(;t<e;)t*=2;return t}function Xi(e,t){let n=0,s=t;for(;e.has(s,Ke);){const t=e.get(s,Ke).entity;if(!e.valid(t))break;n++,s=t}return n}function Ni(e,t){if(Fi&&Bi){const e=Fi.getUIRectComputedWidth(Bi,t);if(e>0)return e}return e.size.x}function Yi(e,t){if(Fi&&Bi){const e=Fi.getUIRectComputedHeight(Bi,t);if(e>0)return e}return e.size.y}function Vi(e,t,n,s,i,o){if(!e.has(t,Ye))return;const r=e.get(t,Ye);let a,l;switch(n){case Ri.BottomToTop:case Ri.TopToBottom:a=i,l=o*s;break;default:a=i*s,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,Ye,r))}function qi(e,t,n){let s=t;for(;e.has(s,Ke);){const t=e.get(s,Ke).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function Gi(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function Ki(e,t,n,s,i){if(!e.has(t,ki))return;const o=e.get(t,ki),r=Ii(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,n,o.pivot),a=r.rect.right-r.rect.left,l=r.rect.top-r.rect.bottom;if(e.has(t,Ye)){const n=e.get(t,Ye);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,Ye,n))}if(e.has(t,je)){const n=e.get(t,je);n.position.x=r.originX-s,n.position.y=r.originY-i,e.insert(t,je,n)}}function Ji(e){const t=Object.keys(e),n=t.map(t=>e[t]);return{take(e){const s={};for(let i=0;i<t.length;i++)s[t[i]]=n[i](e);return s},changed(e,s){for(let i=0;i<t.length;i++)if(e[t[i]]!==n[i](s))return!0;return!1},update(e,s){for(let i=0;i<t.length;i++)e[t[i]]=n[i](s)}}}const Qi=.1,Zi=30,eo={r:.3,g:.5,b:.8,a:1},to={Left:0,Center:1,Right:2},no={Top:0,Middle:1,Bottom:2},so={Visible:0,Clip:1,Ellipsis:2},io=Ae("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:to.Left,verticalAlign:no.Top,wordWrap:!0,overflow:so.Visible,lineHeight:1.2});class oo{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(de.textCanvasSize,de.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,ji(this.frameMaxW_)),e.height=Math.max(e.height,ji(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=ji(this.frameMaxW_),e.height=ji(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,o=i?t.size.x:0,r=i?t.size.y:0,a=e.wordWrap&&i;let l=Hi(n,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=i?Math.ceil(o):h+2*u,p=i?Math.ceil(r):d+2*u;if(i&&e.overflow===so.Ellipsis&&d>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,ji(f)),s.height=Math.max(s.height,ji(p)));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})`,i&&e.overflow===so.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(i){switch(e.verticalAlign){case no.Top:x=u;break;case no.Middle:x=u+(p-2*u-w)/2;break;case no.Bottom:x=p-w-u;break;default:x=u}x<0&&(x=0)}else x=u;let v=x;for(const t of l){let s;switch(e.align){case to.Left:s=u;break;case to.Center:s=f/2;break;case to.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=c}i&&e.overflow===so.Clip&&n.restore();const b=n.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),M=this.module.getResourceManager(),P=this.module._malloc(S.length);this.module.HEAPU8.set(S,P);const T=M.createTexture(f,p,P,S.length,1,!0);return this.module._free(P),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const i=this.renderText(t,n);return this.cache.set(e,i),i}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}measureWidth(e){let t=0;for(const n of e)t=Math.max(t,this.ctx.measureText(n).width);return t}mapAlign(e){switch(e){case to.Left:return"left";case to.Center:return"center";case to.Right:return"right"}}}const ro=Ji({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?Ni(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Yi(e.uiRect,e.entity):0});class ao{build(e){Ue("Text",io);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new oo(t),s=e.world,i=new Map;e.addSystemToSchedule(Kt.PreUpdate,Zt([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,io));for(const e of i.keys())if(!s.valid(e)||!s.has(e,io)){if(s.valid(e)&&s.has(e,Ye)){const t=s.get(e,Ye);s.insert(e,Ye,{texture:_e,color:{r:t.color.r,g:t.color.g,b:t.color.b,a:t.color.a},size:{x:t.size.x,y:t.size.y},uvOffset:{x:t.uvOffset.x,y:t.uvOffset.y},uvScale:{x:t.uvScale.x,y:t.uvScale.y},layer:t.layer,flipX:t.flipX,flipY:t.flipY,material:t.material,enabled:t.enabled})}i.delete(e)}const e=s.getEntitiesWithComponents([io]);for(const t of e){const e=s.get(t,io),o=s.has(t,ki)?s.get(t,ki):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!ro.changed(a,r)){if(s.has(t,Ye)&&s.get(t,Ye).texture!==_e)continue}zi(s,t);const l=o?{size:{x:Ni(o,t),y:Yi(o,t)}}:null,c=n.renderForEntity(t,e,l),u=s.get(t,Ye);s.insert(t,Ye,{texture:c.textureHandle,color:{r:u.color.r,g:u.color.g,b:u.color.b,a:u.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:u.layer,flipX:u.flipX,flipY:u.flipY,material:u.material,enabled:u.enabled}),i.set(t,ro.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const lo=new ao,co=0,uo=1,ho=De("UIMask",{enabled:!0,mode:co});function fo(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),i=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,i-n),h:Math.max(0,o-s)}}function po(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],o=e[2],r=e[3],a=e[4],l=e[5],c=e[6],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],m=e[12],g=e[13],_=e[14],y=e[15],w=s*l-i*a,x=s*c-o*a,v=s*u-r*a,b=i*c-o*l,S=i*u-r*l,M=o*u-r*c,P=h*g-d*m,T=h*_-f*m,E=h*y-p*m,C=d*_-f*g,A=d*y-p*g,R=f*y-p*_;let I=w*R-x*A+v*C+b*E-S*T+M*P;return 0===I||(I=1/I,n[0]=(l*R-c*A+u*C)*I,n[1]=(o*A-i*R-r*C)*I,n[2]=(g*M-_*S+y*b)*I,n[3]=(f*S-d*M-p*b)*I,n[4]=(c*E-a*R-u*T)*I,n[5]=(s*R-o*E+r*T)*I,n[6]=(_*v-m*M-y*x)*I,n[7]=(h*M-f*v+p*x)*I,n[8]=(a*A-l*E+u*P)*I,n[9]=(i*E-s*A-r*P)*I,n[10]=(m*S-g*v+y*w)*I,n[11]=(d*v-h*S-p*w)*I,n[12]=(l*T-a*C-c*P)*I,n[13]=(s*C-i*T+o*P)*I,n[14]=(g*x-m*b-_*w)*I,n[15]=(h*b-d*x+f*w)*I),n}function mo(e,t,n,s,i,o,r){const a=(e-s)/o*2-1,l=(t-i)/r*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:u/h}}function go(e,t,n,s,i,o,r,a){return e>=n-i*r&&e<=n+i*(1-r)&&t>=s-o*a&&t<=s+o*(1-a)}function _o(e,t){return 2*Math.atan2(e,t)}function yo(e,t,n,s,i,o,r){const a=n[0]*e+n[4]*t+n[12],l=n[1]*e+n[5]*t+n[13],c=n[3]*e+n[7]*t+n[15];return[s+(.5*(a/c)+.5)*o,i+(.5*(l/c)+.5)*r]}function wo(e,t,n,s,i,o,r,a,l,c){const u=_o(l,c),h=Math.sin(-u),d=Math.cos(-u),f=e-n,p=t-s,m=f*d-p*h+n,g=f*h+p*d+s;return m>=n-i*r&&m<=n+i*(1-r)&&g>=s-o*a&&g<=s+o*(1-a)}function xo(e,t,n,s,i,o,r){if(!e.has(t,ki)||!e.has(t,je))return null;const a=e.get(t,ki),l=e.get(t,je),c=Ni(a,t)*l.worldScale.x,u=Yi(a,t)*l.worldScale.y,h=l.worldPosition.x,d=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,m=-c*f,g=c*(1-f),_=-u*p,y=u*(1-p),w=_o(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[h+m*x-_*v,d+m*v+_*x],[h+g*x-_*v,d+g*v+_*x],[h+g*x-y*v,d+g*v+y*x],[h+m*x-y*v,d+m*v+y*x]];let S=1/0,M=1/0,P=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=yo(e,t,n,s,i,o,r);S=Math.min(S,a),M=Math.min(M,l),P=Math.max(P,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(M),w:Math.round(P-S),h:Math.round(T-M)}}function vo(e,t){return(n,s,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([ho]);if(0===l.length)return;const c=[],u=[],h=new Set,d=new Set;for(const e of l){const n=t.get(e,ho);n.enabled&&(h.add(e),n.mode===uo?(u.push(e),d.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,i,o,r,a,l,c){const u=[];for(const e of s){let n=!0;qi(t,e,e=>{if(i.has(e)){if(t.get(e,ho).mode===co)return n=!1,!0}return!1}),n&&u.push(e)}function h(s,u){const d=e.getChildEntities(n,s);for(const n of d){let s=u;if(i.has(n)){if(t.get(n,ho).mode===co){const e=xo(t,n,o,r,a,l,c);e&&(s=fo(u,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of u){const n=xo(t,e,o,r,a,l,c);n&&h(e,n)}}(e,t,n,c,h,s,i,o,r,a),u.length>0&&function(e,t,n,s,i){e.renderer_clearStencil();const o=[];for(const e of s){let n=!0;qi(t,e,e=>!!i.has(e)&&(n=!1,!0)),n&&o.push(e)}let r=1,a=!1;function l(){return r>255?(a||console.warn("Stencil mask overflow"),a=!0,null):r++}function c(t,s){if(a)return;e.renderer_setEntityStencilMask(t,s);const o=e.getChildEntities(n,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),u(t,s)}function u(t,s){if(a)return;const o=e.getChildEntities(n,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),u(t,s)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,n,u,d)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class bo{build(e){if(Ue("UIMask",ho),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(vo(e.wasmModule,e.world))}}const So=new bo,Mo=De("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),Po=De("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),To={Normal:0,Hovered:1,Pressed:2,Disabled:3},Eo=Ae("Button",{state:To.Normal,transition:null});class Co{constructor(){this.events_=[]}emit(e,t,n){const s=n??e;this.events_.push({entity:e,type:t,target:s,currentTarget:e})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const Ao=ct(new Co,"UIEvents");class Ro{build(e){Ue("UIRect",ki);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){Fi=e,Bi=t}(n,s);e.addSystemToSchedule(Kt.PreUpdate,Zt([ut(un)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.uiFlexLayout_update(s),n.transform_update(s))},{name:"UILayoutSystem"})),e.addSystemToSchedule(Kt.PostUpdate,Zt([ut(un)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.uiFlexLayout_update(s))},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(Kt.PostUpdate,Zt([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const Io=new Ro;let ko=!1,Fo=!1;function Bo(e){ko=e}function zo(){return ko}function $o(){return!ko}function Uo(e){Fo=e}function Wo(){return Fo}const Do=function(){const e=new Float32Array(16),t=new Float32Array(16);let n=!0;return{update(e){for(let s=0;s<16;s++)if(t[s]!==e[s]){t.set(e),n=!0;break}},getInverse:t=>(n&&(po(t,e),n=!1),e)}}();function Oo(e,t,n,s){t.emit(n,s,n),qi(e,n,i=>{if(!e.has(i,Mo))return!1;const o=e.get(i,Mo);return o.enabled&&t.emit(i,s,n),o.blockRaycast})}class Lo{build(e){Ue("Interactable",Mo),Ue("Button",Eo);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new Co;e.insertResource(Ao,i);let o=null,r=null;e.addSystemToSchedule(Kt.PreUpdate,Zt([ut(an),ut(un)],(e,a)=>{if(i.drain(),zo()&&!Wo())return;const l=t.getEntitiesWithComponents([Po]);for(const e of l){const n=t.get(e,Po);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,Po,n))}if(!a.valid)return;const c=f(),u=e.mouseX*c,h=a.screenH-e.mouseY*c;Do.update(a.viewProjection);const d=mo(u,h,Do.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=d.x,a.worldMouseY=d.y;const p=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),g=e.isMouseButtonReleased(0);n.uiHitTest_update(s,d.x,d.y,p,m,g);const _=n.uiHitTest_getHitEntity(),y=4294967295===_?null:_;if(null===o||t.valid(o)||(o=null),o!==y){if(null!==o&&t.valid(o)&&t.has(o,Po)){const e=t.get(o,Po);e.hovered=!1,t.insert(o,Po,e),i.emit(o,"hover_exit")}if(null!==y){Gi(t,y,Po);const e=t.get(y,Po);e.hovered=!0,t.insert(y,Po,e),i.emit(y,"hover_enter")}o=y}if(m&&null!==y){const e=t.get(y,Po);e.pressed=!0,e.justPressed=!0,t.insert(y,Po,e),r=y,Oo(t,i,y,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,Po)){const e=t.get(r,Po);e.pressed=!1,e.justReleased=!0,t.insert(r,Po,e),Oo(t,i,r,"release"),r===o&&Oo(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(Kt.Update,Zt([],()=>{const e=t.getEntitiesWithComponents([Eo]);for(const n of e){if(Gi(t,n,Mo,{enabled:!0}),!t.has(n,Po))continue;const e=t.get(n,Po),s=t.get(n,Eo),i=t.get(n,Mo),o=!a.has(n),r=s.state;if(i.enabled?e.pressed?s.state=To.Pressed:e.hovered?s.state=To.Hovered:s.state=To.Normal:s.state=To.Disabled,o&&a.add(n),(o||r!==s.state)&&s.transition&&t.has(n,Ye)){const o=t.get(n,Ye);o.color=Oi(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,Ye,o)}}},{name:"ButtonSystem"}))}}const Ho=new Lo,jo=Ae("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}),Xo=Ae("Focusable",{tabIndex:0,isFocused:!1});class No{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Yo=ct(new No,"FocusManager");class Vo{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(Ue("TextInput",jo),zo()&&!Wo())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,i=h(de.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=0,a=0,l=!1,c=!0,u=0,d=0;const f=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!f)return;const p=f;function m(){const t=e.getResource(Yo);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,jo)?s:null}const g=()=>{l||null===m()||v()},_=()=>{l=!0},y=()=>{l=!1,v()},w=t=>{const s=m();if(null===s)return;if("Escape"===t.key)return void b();const i=n.get(s,jo);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(Ao).emit(s,"submit"),void b()}let o=i.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?o=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=i.value.length),o!==i.cursorPos&&(i.cursorPos=o,p.selectionStart=o,p.selectionEnd=o,i.dirty=!0,S())},x=()=>{const t=m();if(null!==t){const s=n.get(t,jo);s.focused=!1,s.dirty=!0;e.getResource(Yo).blur()}};function v(){const t=m();if(null===t)return;const s=n.get(t,jo);if(s.readOnly)return;let i=p.value;if(s.maxLength>0&&i.length>s.maxLength&&(i=i.substring(0,s.maxLength),p.value=i),i!==s.value){s.value=i;e.getResource(Ao).emit(t,"change")}s.cursorPos=p.selectionStart??i.length,s.dirty=!0,S()}function b(){const t=m();if(null!==t){const e=n.get(t,jo);e.focused=!1,e.dirty=!0}e.getResource(Yo).blur(),p.blur()}function S(){c=!0,u=0}p.addEventListener("input",g),p.addEventListener("compositionstart",_),p.addEventListener("compositionend",y),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",g),p.removeEventListener("compositionstart",_),p.removeEventListener("compositionend",y),p.removeEventListener("keydown",w),p.removeEventListener("blur",x),p.remove();const e=t.getResourceManager();for(const t of s.values())e.releaseTexture(t);s.clear(),0!==r&&(t._free(r),r=0,a=0)};let M=null;function P(e,l,u,h){(i.width<u||i.height<h)&&(i.width=ji(Math.max(i.width,u)),i.height=ji(Math.max(i.height,h))),o.clearRect(0,0,i.width,i.height);const d=l.backgroundColor;o.fillStyle=`rgba(${Math.round(255*d.r)}, ${Math.round(255*d.g)}, ${Math.round(255*d.b)}, ${d.a})`,o.fillRect(0,0,u,h),o.save(),o.beginPath(),o.rect(l.padding,0,u-2*l.padding,h),o.clip(),o.font=`${l.fontSize}px ${l.fontFamily}`,o.textBaseline="top",o.textAlign="left";const f=0===l.value.length,p=f?l.placeholder:l.password?"●".repeat(l.value.length):l.value,m=f?l.placeholderColor:l.color;o.fillStyle=`rgba(${Math.round(255*m.r)}, ${Math.round(255*m.g)}, ${Math.round(255*m.b)}, ${m.a})`;const g=Math.ceil(1.2*l.fontSize),_=l.padding;if(l.multiline){const e=Hi(o,p,u-2*_);let t=_;for(const n of e)o.fillText(n,_,t),t+=g}else{const e=(h-l.fontSize)/2;o.fillText(p,_,e)}if(l.focused&&c){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,n,s;if(l.multiline){const e=Hi(o,l.value,u-2*_);let i=0,r=0,a=0;for(let t=0;t<e.length;t++){const n=e[t].length;if(i+n>=l.cursorPos){r=t,a=l.cursorPos-i;break}i+=n,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,r=t+1,a=0}const c=r<e.length?e[r].substring(0,a):"";t=_+o.measureText(c).width,n=_+r*g,s=g}else t=_+o.measureText(e).width,n=(h-l.fontSize)/2,s=l.fontSize;o.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,o.fillRect(t,n,2,s)}o.restore();const y=o.getImageData(0,0,u,h),w=new Uint8Array(y.data.buffer),x=t.getResourceManager();w.length>a&&(0!==r&&t._free(r),r=t._malloc(w.length),a=w.length),t.HEAPU8.set(w,r);const v=s.get(e);void 0!==v&&x.releaseTexture(v);const b=x.createTexture(u,h,r,w.length,1,!0);s.set(e,b);const S=n.get(e,Ye);S.texture=b,S.size.x=u,S.size.y=h,S.uvOffset.x=0,S.uvOffset.y=0,S.uvScale.x=1,S.uvScale.y=1,S.color={r:1,g:1,b:1,a:1},n.insert(e,Ye,S)}e.addSystemToSchedule(Kt.Update,Zt([ut(Yo)],e=>{const t=n.getEntitiesWithComponents([jo]);for(const e of t)Gi(n,e,Xo,{tabIndex:0,isFocused:!1}),Gi(n,e,Mo,{enabled:!0,blockRaycast:!0});const s=m();if(s!==M){if(null!==M&&n.valid(M)&&n.has(M,jo)){const e=n.get(M,jo);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,jo);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),S())}(s),M=s}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(Kt.PreUpdate,Zt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===d?0:(e-d)/1e3;d=e,i=Math.min(i,.1);const o=m();if(null!==o&&(u+=i,u>=.5)){u-=.5,c=!c;n.get(o,jo).dirty=!0}const r=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,jo)||(r.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([jo,ki]);for(const e of a){const t=n.get(e,jo);if(!t.dirty)continue;const s=n.get(e,ki),i=Math.ceil(s.size.x),o=Math.ceil(s.size.y);i<=0||o<=0||(zi(n,e),P(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const qo=new Vo,Go={Simple:0,Sliced:1,Tiled:2,Filled:3},Ko={Horizontal:0,Vertical:1},Jo={Left:0,Right:1,Bottom:2,Top:3},Qo=Ae("Image",{texture:_e,color:{r:1,g:1,b:1,a:1},imageType:Go.Simple,fillMethod:Ko.Horizontal,fillOrigin:Jo.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Zo=Ji({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,layer:e=>e.image.layer,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?Ni(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Yi(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class er{build(e){Ue("Image",Qo);const t=e.world,n=new Map;e.addSystemToSchedule(Kt.PreUpdate,Zt([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,Qo)||n.delete(e);const e=t.getEntitiesWithComponents([Qo]);for(const s of e){const e=t.get(s,Qo),i=t.has(s,ki)?t.get(s,ki):null,o={image:e,uiRect:i,entity:s},r=n.get(s);if(r&&!Zo.changed(r,o))continue;zi(t,s);const a=t.get(s,Ye);if(e.enabled){if(a.texture=e.texture,a.color.r=e.color.r,a.color.g=e.color.g,a.color.b=e.color.b,a.color.a=e.color.a,a.layer=e.layer,a.material=e.material,i&&(a.size.x=Ni(i,s),a.size.y=Yi(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Go.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===Ko.Horizontal?e.fillOrigin===Jo.Left?(a.uvScale.x=t,a.size.x=n*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=n*t):e.fillOrigin===Jo.Bottom?(a.uvScale.y=t,a.size.y=s*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=s*t)}else e.imageType===Go.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale.x=a.size.x/e.tileSize.x,a.uvScale.y=a.size.y/e.tileSize.y);t.insert(s,Ye,a),n.set(s,Zo.take(o))}else a.color.a=0,t.insert(s,Ye,a),n.set(s,Zo.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const tr=new er,nr=Ae("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),sr=Ae("ToggleGroup",{allowSwitchOff:!1});class ir{build(e){Ue("Toggle",nr),Ue("ToggleGroup",sr);const t=e.world,n=new Set;e.addSystemToSchedule(Kt.Update,Zt([ut(Ao)],e=>{const s=t.getEntitiesWithComponents([nr]);if(!zo()||Wo()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,nr);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,nr,s)):i.set(s.group,e))}const o=new Map;for(const e of s){const n=t.get(e,nr);if(0!==n.group&&t.valid(n.group)){let t=o.get(n.group);t||(t=[],o.set(n.group,t)),t.push(e)}}for(const n of s){if(Gi(t,n,Mo,{enabled:!0}),!t.has(n,Po))continue;const s=t.get(n,Po),i=t.get(n,nr),r=t.get(n,Mo);if(s.justPressed&&r.enabled){const s=i.group,r=0!==s&&t.valid(s)&&t.has(s,sr);if(i.isOn&&r){if(!t.get(s,sr).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,nr,i),i.isOn&&r){const i=o.get(s);if(i)for(const s of i){if(s===n)continue;const i=t.get(s,nr);i.isOn&&(i.isOn=!1,t.insert(s,nr,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,Ye)){const e=t.get(n,Ye);e.color=Oi(i.transition,r.enabled,s.pressed,s.hovered),t.insert(n,Ye,e)}}}for(const e of s){const n=t.get(e,nr);if(n.graphicEntity&&t.valid(n.graphicEntity)&&t.has(n.graphicEntity,Ye)){const e=t.get(n.graphicEntity,Ye);e.enabled=n.isOn,t.insert(n.graphicEntity,Ye,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const or=new ir,rr=Ri,ar=Ae("ProgressBar",{value:0,fillEntity:0,direction:Ri.LeftToRight});function lr(e,t,n,s){if(!e.has(t,ki))return;const i=e.get(t,ki),o=n/2,r=s/2,a={left:-o,bottom:-r,right:o,top:r},l=Ii(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,Ye)){const n=e.get(t,Ye);n.size.x===l.width&&n.size.y===l.height||(n.size.x=l.width,n.size.y=l.height,e.insert(t,Ye,n))}if(e.has(t,je)){const n=e.get(t,je),s=n.position;s.x===l.originX&&s.y===l.originY||(n.position={x:l.originX,y:l.originY,z:s.z},e.insert(t,je,n))}}class cr{build(e){Ue("ProgressBar",ar);const t=e.world;e.addSystemToSchedule(Kt.PreUpdate,Zt([],()=>{const e=t.getEntitiesWithComponents([ar,ki]);for(const n of e){const e=t.get(n,ar);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,ki),i=Math.max(0,Math.min(1,e.value));Di(t,e.fillEntity,e.direction,i);const o=Ni(s,n),r=Yi(s,n);lr(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const ur=new cr,hr=Ae("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),dr=Ae("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});class fr{build(e){Ue("Draggable",hr),Ue("DragState",dr);const t=e.world,n=e.getResource(Ao);let s=null,i={x:0,y:0},o=null;e.addSystemToSchedule(Kt.PreUpdate,Zt([ut(an),ut(un)],(e,r)=>{if(zo()&&!Wo())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([hr,Po]);let n=null,o=-1/0,r=-1;for(const s of e){if(!t.get(s,hr).enabled)continue;if(t.get(s,Po).hovered){let e=0;t.has(s,Ye)&&(e=t.get(s,Ye).layer);const i=Xi(t,s);(e>o||e===o&&i>=r)&&(o=e,r=i,n=s)}}if(null!==n){s=n,i={x:a.x,y:a.y},t.has(n,dr)||t.insert(n,dr);const e=t.get(n,dr),o=t.get(n,je);e.startWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.currentWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,dr)){t.get(s,dr).isDragging=!1}s=null}if(null!==s&&null===o){if(!t.valid(s))return void(s=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),u=t.get(s,hr);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=s,s=null;t.get(o,dr).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,dr))return void(o=null);const s=t.get(o,dr),i=t.get(o,hr),r=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+r,u=s.startWorldPos.y+l;const h=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,o=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:i,y:o}}(i,s,c,u);c=h.x,u=h.y;const d=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-d,y:u-f},s.currentWorldPos={x:c,y:u},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:u-s.startWorldPos.y},t.has(o,je)){const e=function(e,t,n,s){if(!e.has(t,Ke))return{x:n,y:s};const i=e.get(t,Ke).entity;if(!e.valid(i)||!e.has(i,je))return{x:n,y:s};const o=e.get(i,je),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=_o(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(n*u-s*c)/r,y:(n*c+s*u)/a}}(t,o,s.deltaWorld.x,s.deltaWorld.y),n=t.get(o,je);n.position.x+=e.x,n.position.y+=e.y,t.insert(o,je,n)}n.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}}const pr=new fr,mr=Ae("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function gr(e,t,n,s){return s<=0?1:e<t?Math.max(0,1-(t-e)/s):e>n?Math.max(0,1-(e-n)/s):1}function _r(e,t,n,s,i){const o=2/(s=Math.max(1e-4,s)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(n+o*l)*i,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(n-o*c)*a}}class yr{build(e){Ue("ScrollView",mr);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(Kt.PostUpdate,Zt([ut(an),ut(un),ut(pt)],(e,i,o)=>{const r=zo()&&!Wo(),a=Math.min(o.delta,.05);for(const[e]of n)t.valid(e)||n.delete(e);i.valid&&(s.x=i.worldMouseX,s.y=i.worldMouseY);const l=t.getEntitiesWithComponents([mr,ki]);for(const o of l){Gi(t,o,ho,{enabled:!0,mode:co});const l=t.get(o,mr),c=t.get(o,ki);let u=n.get(o);u||(u={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},n.set(o,u));const h=Ni(c,o),d=Yi(c,o);let f=l.contentWidth,p=l.contentHeight;if((0===f||0===p)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,Je)){const e=t.get(l.contentEntity,Je).entities;let n=0,s=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,je))continue;const e=t.get(r,je);let a=0,l=0,c=.5,u=.5;if(t.has(r,ki)){const e=t.get(r,ki);a=Ni(e,r)||e.size.x,l=Yi(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,Ye)){const e=t.get(r,Ye);a=e.size.x,l=e.size.y}const h=e.position.x-a*c,d=e.position.x+a*(1-c),f=e.position.y-l*u,p=e.position.y+l*(1-u);h<n&&(n=h),d>s&&(s=d),f<i&&(i=f),p>o&&(o=p)}0===f&&(f=s-n),0===p&&(p=o-i)}const m=Math.max(0,f-h),g=Math.max(0,p-d);if(!r&&i.valid){Gi(t,o,Mo,{enabled:!0,blockRaycast:!0});const n=t.has(o,Po)?t.get(o,Po):null;if(n?.justPressed&&(u.isDragging=!0,u.lastWorldX=s.x,u.lastWorldY=s.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=s.x-u.lastWorldX,t=s.y-u.lastWorldY,n=Math.min(1,10*a);if(l.horizontalEnabled){const t=gr(l.scrollX,0,m,h);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const s=a>0?-e*t/a:0;u.velocityX+=(s-u.velocityX)*n}}if(l.verticalEnabled){const e=gr(l.scrollY,0,g,d);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const s=a>0?t*e/a:0;u.velocityY+=(s-u.velocityY)*n}}u.lastWorldX=s.x,u.lastWorldY=s.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*h,t=5*d;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=gr(l.scrollY,0,g,d);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=gr(l.scrollX,0,m,h);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>g;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=_r(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<Qi&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Qi?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:g,t=_r(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<Qi&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Qi?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,m)),l.scrollY=Math.max(0,Math.min(l.scrollY,g)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*h,t=.5*d;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,g+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,je)){const e=t.get(l.contentEntity,je),n=e.position.x,s=e.position.y;(isNaN(u.lastAppliedX)||Math.abs(n-u.lastAppliedX)>.01)&&(u.contentBaseX=n),(isNaN(u.lastAppliedY)||Math.abs(s-u.lastAppliedY)>.01)&&(u.contentBaseY=s),e.position.x=u.contentBaseX-l.scrollX,e.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=e.position.x,u.lastAppliedY=e.position.y,t.insert(l.contentEntity,je,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const wr=new yr,xr=Ri,vr=Ae("Slider",{value:0,minValue:0,maxValue:1,direction:Ri.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function br(e,t,n,s,i,o){const r=Ni(s,i)*n.worldScale.x,a=Yi(s,i)*n.worldScale.y,l=_o(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),h=e-n.worldPosition.x,d=t-n.worldPosition.y,f=h*u-d*c,p=h*c+d*u,m=-s.pivot.x*r,g=-s.pivot.y*a;switch(o){case Ri.LeftToRight:return r>0?(f-m)/r:0;case Ri.RightToLeft:return r>0?1-(f-m)/r:0;case Ri.BottomToTop:return a>0?(p-g)/a:0;case Ri.TopToBottom:return a>0?1-(p-g)/a:0}}function Sr(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case Ri.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case Ri.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case Ri.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case Ri.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class Mr{build(e){Ue("Slider",vr);const t=e.world;let n=null;e.addSystemToSchedule(Kt.PreUpdate,Zt([ut(an),ut(un),ut(Ao)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const o=t.getEntitiesWithComponents([vr,ki]);for(const r of o){const o=t.get(r,vr),a=t.get(r,ki);if(!zo()||Wo()){if(t.has(r,je)){Gi(t,r,Mo,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Gi(t,o.handleEntity,Mo,{enabled:!0,blockRaycast:!1});const l=t.get(r,je),c=t.has(r,Po)?t.get(r,Po):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Po)&&(u=t.get(o.handleEntity,Po).justPressed),u&&(n=r),n===r&&e.isMouseButtonDown(0)){let e=br(s.worldMouseX,s.worldMouseY,l,a,r,o.direction);e=Math.max(0,Math.min(1,e));let n=o.minValue+e*(o.maxValue-o.minValue);o.wholeNumbers&&(n=Math.round(n));const c=o.value;o.value=Math.max(o.minValue,Math.min(o.maxValue,n)),t.insert(r,vr,o),o.value!==c&&i.emit(r,"change")}n===r&&e.isMouseButtonReleased(0)&&(n=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,u=Ni(a,r),h=Yi(a,r),d={left:-u/2,bottom:-h/2,right:u/2,top:h/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(Di(t,o.fillEntity,o.direction,c),Ki(t,o.fillEntity,d,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,ki)){const e=t.get(o.handleEntity,ki);Sr(e,o.direction,c),t.insert(o.handleEntity,ki,e),Ki(t,o.handleEntity,d,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Pr=new Mr;class Tr{build(e){Ue("Focusable",Xo);const t=e.world,n=new No;e.insertResource(Yo,n),e.addSystemToSchedule(Kt.Update,Zt([ut(an),ut(Ao)],(e,s)=>{if(zo()&&!Wo())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([Xo]);for(const e of i){if(!t.has(e,Po))continue;t.get(e,Po).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){if(!t.valid(n))continue;if(t.has(n,Mo)){if(!t.get(n,Mo).enabled)continue}const s=t.get(n,Xo);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const r=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?s.length-1:0:a?(r-1+s.length)%s.length:(r+1)%s.length,o(s[l])}function o(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Xo)){t.get(i,Xo).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,Xo).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const Er=new Tr,Cr=Ae("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function Ar(){return i()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:n,screenWidth:s,screenHeight:i}=t;return{top:n.top,bottom:i-n.bottom,left:n.left,right:s-n.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}class Rr{build(e){Ue("SafeArea",Cr);const t=e.world;let n=Ar(),s=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=Ar(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=Ar(),s=!0});e.addSystemToSchedule(Kt.PreUpdate,Zt([ut(un)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===r||(o=e.screenH,r=a,s=!0),!s)return;s=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([Cr,ki]);for(const e of u){const s=t.get(e,Cr),i=t.get(e,ki),o=s.applyTop?n.top*c:0,r=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let u=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},u=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,ki,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const Ir=new Rr,kr=Ae("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Fr=null;function Br(e,t){if(!Fr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=Fr.get(e);n?n.renderer=t:Fr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}class zr{build(e){Ue("ListView",kr);const t=e.world,n=new Map;Fr=n,e.addSystemToSchedule(Kt.PostUpdate,Zt([ut(an)],e=>{const s=zo()&&!Wo();for(const[e,s]of n)if(!t.valid(e)){for(const e of s.itemEntities.values())t.valid(e)&&t.despawn(e);n.delete(e)}const i=t.getEntitiesWithComponents([kr,ki]);for(const o of i){Gi(t,o,Mo,{enabled:!0,blockRaycast:!0}),Gi(t,o,ho,{enabled:!0,mode:co});let i=n.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(o,i));const r=t.get(o,kr),a=t.get(o,ki),l=Yi(a,o),c=Ni(a,o);if(!s){const n=t.has(o,Po)?t.get(o,Po):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const u=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,u));const h=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),d=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,n]of i.itemEntities)(e<h||e>=d)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=h;e<d;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,et,{value:`ListItem_${e}`}),t.insert(n,ki,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,o),i.itemEntities.set(e,n),i.renderer&&i.renderer(e,n)),t.has(n,je)){const s=t.get(n,je);s.position.y=-(e*r.itemHeight-r.scrollY),t.insert(n,je,s)}}i.visibleStart=h,i.visibleEnd=d}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const $r=new zr,Ur=Ae("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class Wr{build(e){Ue("Dropdown",Ur);const t=e.world,n=new Map;function s(e){if(0===e||!t.valid(e))return;if(!t.has(e,je))return;const n=t.get(e,je);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,je,{position:{x:n.position.x,y:n.position.y,z:n.position.z},rotation:{x:n.rotation.x,y:n.rotation.y,z:n.rotation.z,w:n.rotation.w},scale:{x:1,y:1,z:1}})}function i(e){if(t.has(e,Ye)){const n=t.get(e,Ye);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&t.insert(e,Ye,{texture:n.texture,color:{r:.9,g:.9,b:.9,a:1},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:n.enabled})}}function o(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;u(i,!0),c(s);const o=t.get(e,Ye),r=o.size.x,a=o.size.y;s.ddWidth=r;const l=n.options.length*Zi;t.insert(i,ki,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:l},pivot:{x:.5,y:.5}}),t.insert(i,je,{position:{x:0,y:-(a+l)/2,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(i,Ye,{texture:_e,color:{r:1,g:1,b:1,a:1},size:{x:r,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<n.options.length;e++){const o=t.spawn(),a=l/2-(e+.5)*Zi;t.insert(o,et,{value:`Option_${e}`}),t.insert(o,ki,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Zi},offsetMax:{x:0,y:0},size:{x:r,y:Zi},pivot:{x:.5,y:.5}}),t.insert(o,je,{position:{x:0,y:a,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(o,Ye,{texture:_e,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:Zi},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,Mo,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),s.optionEntities.push(o);const c=t.spawn();t.insert(c,je,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(c,io,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:to.Left,verticalAlign:no.Middle,wordWrap:!1,overflow:so.Clip,lineHeight:1.2}),t.insert(c,ki,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:Zi},pivot:{x:.5,y:.5}}),t.setParent(c,o),s.textEntities.push(c)}h(s)}function r(e,t,n){t.isOpen=!1,c(n),u(t.listEntity,!1)}function a(e,t,n,s,i){t.selectedIndex=s,r(0,t,n),i.emit(e,"change")}function l(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,io))return;const s=t.get(n,io);let i={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},o=s.content,r=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},r=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,r=!0)}r&&t.insert(n,io,{content:o,fontSize:s.fontSize,fontFamily:s.fontFamily,color:i,align:s.align,verticalAlign:s.verticalAlign,wordWrap:s.wordWrap,overflow:s.overflow,lineHeight:s.lineHeight})}function c(e){for(const n of e.textEntities)t.valid(n)&&t.despawn(n);for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[],e.textEntities=[]}function u(e,n){if(0!==e&&t.valid(e)&&(t.has(e,Mo)&&t.insert(e,Mo,{enabled:n,blockRaycast:!0,raycastTarget:!0}),t.has(e,Ye))){const s=t.get(e,Ye);t.insert(e,Ye,{texture:s.texture,color:{r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},size:{x:s.size.x,y:s.size.y},uvOffset:{x:s.uvOffset.x,y:s.uvOffset.y},uvScale:{x:s.uvScale.x,y:s.uvScale.y},layer:s.layer,flipX:s.flipX,flipY:s.flipY,material:s.material,enabled:n})}}function h(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s)||!t.has(s,Ye))continue;const i=n===e.highlightIndex?{...eo}:{r:.95,g:.95,b:.95,a:1};t.insert(s,Ye,{texture:_e,color:i,size:{x:e.ddWidth,y:Zi},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function d(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,Po))continue;if(t.get(n,Po).hovered)return!0}return!1}e.addSystemToSchedule(Kt.Update,Zt([ut(an),ut(Ao)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=zo()&&!Wo(),p=t.getEntitiesWithComponents([Ur]);for(const m of p){const p=t.get(m,Ur);let g=n.get(m);if(g||(g={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(m,g)),s(p.listEntity),i(m),p.isOpen||u(p.listEntity,!1),l(p),f)continue;Gi(t,m,Mo,{enabled:!0,blockRaycast:!0});const _=t.has(m,Po)?t.get(m,Po):null;if(_?.justPressed&&(p.isOpen?r(m,p,g):o(m,p,g)),p.isOpen){for(let e=0;e<g.optionEntities.length;e++){const n=g.optionEntities[e];if(!t.valid(n)||!t.has(n,Po))continue;if(t.get(n,Po).justPressed){a(m,p,g,e,c);break}}let n=-1;for(let e=0;e<g.optionEntities.length;e++){const s=g.optionEntities[e];if(!t.valid(s)||!t.has(s,Po))continue;if(t.get(s,Po).hovered){n=e;break}}n>=0&&n!==g.highlightIndex&&(g.highlightIndex=n,h(g)),e.isKeyPressed("ArrowDown")?(g.highlightIndex>=p.options.length-1?g.highlightIndex=0:g.highlightIndex++,h(g)):e.isKeyPressed("ArrowUp")?(g.highlightIndex<=0?g.highlightIndex=p.options.length-1:g.highlightIndex--,h(g)):e.isKeyPressed("Enter")&&g.highlightIndex>=0?a(m,p,g,g.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,p,g),e.isMouseButtonPressed(0)&&(_?.hovered||d(g)||r(m,p,g))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}}const Dr=new Wr,Or=0,Lr=0,Hr=2,jr=Ae("LayoutGroup",{direction:Or,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Lr,reverseOrder:!1});class Xr{build(e){Ue("LayoutGroup",jr);const t=e.world;e.addSystemToSchedule(Kt.PreUpdate,Zt([],()=>{const e=t.getEntitiesWithComponents([jr,ki,Je]);for(const n of e){const e=t.get(n,jr),s=t.get(n,ki),i=t.get(n,Je);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,ki)&&t.has(e,je)&&o.push({entity:e,rect:t.get(e,ki)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=Ni(s,n),a=Yi(s,n),l=s.pivot.x,c=s.pivot.y,u=e.padding,h=e.direction===Or;let d=0;for(let n=0;n<o.length;n++){const s=o[n],i=Ni(s.rect,s.entity),f=Yi(s.rect,s.entity),p=s.rect.pivot.x,m=s.rect.pivot.y;let g,_;h?(g=-l*r+u.left+d+p*i,_=e.childAlignment===Lr?(1-c)*a-u.top-(1-m)*f:e.childAlignment===Hr?-c*a+u.bottom+m*f:(.5-c)*a+.5*(u.bottom-u.top)+(m-.5)*f,d+=i,n<o.length-1&&(d+=e.spacing)):(g=e.childAlignment===Lr?-l*r+u.left+p*i:e.childAlignment===Hr?(1-l)*r-u.right-(1-p)*i:(.5-l)*r+.5*(u.left-u.right)+(p-.5)*i,_=(1-c)*a-u.top-d-(1-m)*f,d+=f,n<o.length-1&&(d+=e.spacing));const y=t.get(s.entity,je);y.position.x=g,y.position.y=_,t.insert(s.entity,je,y)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}}const Nr=new Xr;class Yr{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(Kt.PostUpdate,Zt([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const Vr=new Yr;async function qr(e,t,n){const s=e.getResource(hi);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function Gr(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const Kr=ct({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Jr=ct(null,"PhysicsAPI");function Qr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Zr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class ea{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(Kr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Gr(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const i=function(e){const t=e.world.getEntitiesWithComponents([qe]);for(const n of t){const t=e.world.get(n,qe);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/i,r=e.world;r.onDespawn(e=>{t.has(e)&&(s._physics_destroyBody(e),t.delete(e),n.delete(e))}),e.addSystemToSchedule(Kt.PostUpdate,Zt([ut(pt)],a=>{const l=r.getEntitiesWithComponents([st,je]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,st),l=r.get(i,je);if(t.has(i)){const e=n.get(i);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(i,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const r=Qr(l.worldRotation);s._physics_createBody(i,a.bodyType,l.worldPosition.x*o,l.worldPosition.y*o,r,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),ta(e,s,i),t.add(i),n.set(i,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===at.Kinematic){const e=Qr(l.worldRotation);s._physics_setBodyTransform(i,l.worldPosition.x*o,l.worldPosition.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 i=t._physics_getDynamicBodyTransforms(),o=i>>2;for(let i=0;i<s;i++){const s=o+4*i,r=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(r))continue;const u=e.world.get(r,je);if(!u)continue;let h=a,d=l,f=c;if(e.world.has(r,Ke)){const t=e.world.get(r,Ke);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,je)){const n=e.world.get(t.entity,je),s=Qr(n.worldRotation),i=a-n.worldPosition.x,o=l-n.worldPosition.y,r=Math.cos(-s),u=Math.sin(-s);h=(i*r-o*u)/(0!==n.worldScale.x?n.worldScale.x:1),d=(i*u+o*r)/(0!==n.worldScale.y?n.worldScale.y:1),f=c-s}}u.position.x=h,u.position.y=d;const p=Zr(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(r,je,u)}}(e,s,i),function(e,t,n){t._physics_collectEvents();const s=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<i;o++){const i=e+6*o;s.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*n,contactY:t.HEAPF32[i+5]*n})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<r;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(Kr,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(Jr,na._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function ta(e,t,n){const s=e.world;if(s.has(n,it)){const e=s.get(n,it);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,ot)){const e=s.get(n,ot);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,rt)){const e=s.get(n,rt);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 na{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(na.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}const sa={nearest:0,linear:1},ia={repeat:0,clamp:1,mirror:2};function oa(e,t,n=!0,s){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),s&&(s.filterMode||s.wrapMode)&&i.createTextureEx){const e=sa[s.filterMode??"linear"]??1,a=ia[s.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,n,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,n);return e._free(o),r}function ra(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 aa(e,t,n,s){const i=e.worldScale.x*t*(n?-1:1),o=e.worldScale.y*t*(s?-1:1),r=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,u=e.worldRotation.w,h=a+a,d=l+l,f=c+c,p=a*h,m=a*d,g=a*f,_=l*d,y=l*f,w=c*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(_+w))*i,(m+b)*i,(g-v)*i,0,(m-b)*o,(1-(p+w))*o,(y+x)*o,0,(g+v)*r,(y-x)*r,(1-(p+_))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function la(e){const{app:t,module:n,sceneData:s,provider:i,spineModule:o,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,u=await async function(e,t,n){const s={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=Xn(t.type);for(const r of o){if("texture"!==r.type)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===s[o])try{const t=i?.[o];s[o]=oa(e,await n.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),s[o]=0}}}return s}(n,s,i);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const i=n[e];if(i&&i>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(n,s,u);let h={},d=null;if(o&&(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"])}}(o),h=await async function(e,t,n,s,i){const o={};for(const r of s.entities)for(const s of r.components){const r=Nn(s.type);if(!r||!s.data)continue;const a=s.data[r.skeletonField],l=s.data[r.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),u=i.resolvePath(l);try{const s=await i.readText(l),r="binary"===T(c)?.contentType;let h,d;if(r){const e=await i.readBinary(a);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=await i.readText(a),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,r);if(t._free(h),f<0)continue;o[a]=f;const p=ra(s),m=u.substring(0,u.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=i.loadPixelsRaw?await i.loadPixelsRaw(s):await i.loadPixels(s),r=oa(e,o,!1),a=e.getResourceManager().getTextureGLId(r);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(n,o,d,s,i)),r){const e={gravity:a?.gravity??{...ce},fixedTimestep:a?.fixedTimestep??ue,subStepCount:a?.subStepCount??4};new ea("",e,()=>Promise.resolve(r)).build(t)}const f=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=Xn(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{let t,i;const r=T(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await n.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){s[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=oa(e,c,!1),h=e.getResourceManager();s[o]=h.loadBitmapFont(t,u,c.width,c.height)}catch{s[o]=0}}return s}(n,s,i),p=await async function(e,t){const n={},s={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Xn(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){n[o]=0;continue}const i=e.vertexSource+e.fragmentSource;let r=s[i];r||(r=xn.createShader(e.vertexSource,e.fragmentSource),s[i]=r),n[o]=xn.createFromAsset(e,r)}catch{n[o]=0}}return n}(s,i);await async function(e,t,n){const s=new Set;for(const i of t.entities)for(const t of i.components){const i=Xn(t.type);for(const o of i){if("anim-clip"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!s.has(i)){s.add(i);try{const t=await n.readText(i),s=JSON.parse(t),o=In(s),r=new Map;for(const t of o)try{const s=await n.loadPixels(t);r.set(t,oa(e,s))}catch{r.set(t,0)}Bn(kn(i,s,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(n,s,i),await async function(e){const t=[],n=new Set;for(const s of e.entities)for(const e of s.components){const s=Xn(e.type);for(const i of s){if("audio"!==i.type)continue;const s=e.data[i.field];"string"==typeof s&&s&&!n.has(s)&&(n.add(s),t.push(s))}}t.length>0&&await On.preloadAll(t).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)})}(s),function(e,t,n,s){const i={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=Xn(e.type);if(0===t.length)continue;const n=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof n[e.field]&&(n[e.field]=t[n[e.field]]||0)}}}(s,u,f,p);const m=Jn(t.world,s);if(c&&t.hasResource(hi))for(const e of m.values())t.world.insert(e,tt,{scene:c,persistent:!1});if(o&&d){const e=function(e,t,n,s){const i={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const r=Nn(t.type);if(!r||!t.data)continue;const a=n[t.data[r.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=s.get(o.id);void 0!==c&&(i[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return i}(d,s,h,m);!function(e,t,n,s,i){let o=0;e.setSpineRenderer((r,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=le);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,Ze)?c.get(o,Ze):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&s.update(r,l*h);let d=0;if(c.has(o,je)){const e=aa(c.get(o,je),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=s.getMeshBatchCount(r);for(let e=0;e<f;e++){const i=s.getMeshBatchVertexCount(r,e),o=s.getMeshBatchIndexCount(r,e);if(!i||!o)continue;const a=8*i*4,l=2*o,c=n._malloc(a),u=n._malloc(l),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(r,e,c,u,h,f);const p=n.HEAPU32[h>>2],m=n.HEAPU32[f>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*i),_=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,i,w,o,p,m,d),t._free(y),t._free(w),n._free(c),n._free(u),n._free(h),n._free(f)}d&&t._free(d)}})}(t,n,o,d,e)}if(l){const e=t.getResource(is);e&&e.setAddressableManifest(l)}}function ca(e,t,n){return{name:e,async setup(){await la({...n,sceneData:t,sceneName:e})}}}async function ua(e){const{app:t,firstScene:n,aspectRatio:s}=e;gi(t);const i={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},o=t.getResource(hi);for(const t of e.scenes)o.register(ca(t.name,t.data,i));n&&(o.setInitial(n),await o.load(n)),void 0!==s&&ts(t.world,s)}class ha{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Nn(e.type);if(i){const s=e.data[i.skeletonField],o=e.data[i.atlasField];s&&("binary"===T(s)?.contentType?n.add(s):t.add(s)),o&&t.add(o)}const o=Xn(e.type);for(const n of o){const i=e.data[n.field];"string"==typeof i&&i&&("font"===n.type?(s.add(i),t.add(i)):("material"===n.type||"anim-clip"===n.type)&&t.add(i))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const o=[];for(const e of s){const t=T(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(),i=await createImageBitmap(s),o=new OffscreenCanvas(i.width,i.height).getContext("2d");o.drawImage(i,0,0);const r=o.getImageData(0,0,i.width,i.height);return i.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const da="__preview__";class fa{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(hi);t.register({name:da,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(da),this.loadPromise_=t.load(da).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await r(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new ha(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await la({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:n,spineModule:s,sceneName:da})}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([qe]);for(const i of s){const s=e.get(i,qe);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const i=this.app_.getResource(hi).getScene(da),o=i?i.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,je,r);const a={isActive:!0,projectionType:Oe.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Le.ColorAndDepth};e.insert(o,Ve,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(hi);await e.switchTo(da),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 pa={create(e){const t=e.depth??!0,n="linear"===e.filter,s=(t?1:0)|(n?2:0),i=ti.createRenderTarget(e.width,e.height,s);return{_handle:i,textureId:ti.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:n?"linear":"nearest"}},release(e){ti.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(ti.releaseRenderTarget(e._handle),pa.create({width:t,height:n,depth:e._depth,filter:e._filter})),begin(e,t){ti.begin(t,e._handle)},end(){ti.end()},getDepthTexture:e=>ti.getTargetDepthTexture(e._handle)};var ma;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(ma||(ma={}));class ga{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${ma[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case ma.Debug:console.debug(t,n);break;case ma.Info:console.log(t,n);break;case ma.Warn:console.warn(t,n);break;case ma.Error:console.error(t,n)}}}class _a{constructor(){this.handlers_=[],this.minLevel_=ma.Info,this.addHandler(new ga)}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(ma.Debug,e,t,n)}info(e,t,n){this.log(ma.Info,e,t,n)}warn(e,t,n){this.log(ma.Warn,e,t,n)}error(e,t,n){this.log(ma.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const i={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const ya=new _a;function wa(){return ya}function xa(e){ya.setMinLevel(e)}function va(e,t,n){ya.debug(e,t,n)}function ba(e,t,n){ya.info(e,t,n)}function Sa(e,t,n){ya.warn(e,t,n)}function Ma(e,t,n){ya.error(e,t,n)}const Pa={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},Ta={Running:0,Paused:1,Completed:2,Cancelled:3},Ea={None:0,Restart:1,PingPong:2};const Ca=1.70158,Aa=2.70158,Ra=2.5949095;const Ia=2*Math.PI/3,ka=2*Math.PI/4.5;const Fa=7.5625,Ba=2.75;const za=1e-6;function $a(e,t,n){switch(e){case Pa.Linear:return t;case Pa.EaseInQuad:return function(e){return e*e}(t);case Pa.EaseOutQuad:return function(e){return e*(2-e)}(t);case Pa.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case Pa.EaseInCubic:return function(e){return e*e*e}(t);case Pa.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case Pa.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case Pa.EaseInBack:return function(e){return Aa*e*e*e-Ca*e*e}(t);case Pa.EaseOutBack:return function(e){const t=e-1;return 1+Aa*t*t*t+Ca*t*t}(t);case Pa.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-Ra)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+Ra)+2)/2}(t);case Pa.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*Ia)}(t);case Pa.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*Ia)+1}(t);case Pa.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*ka)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*ka)/2+1}(t);case Pa.EaseOutBounce:return function(e){return e<1/Ba?Fa*e*e:e<2/Ba?Fa*(e-=1.5/Ba)*e+.75:e<2.5/Ba?Fa*(e-=2.25/Ba)*e+.9375:Fa*(e-=2.625/Ba)*e+.984375}(t);case Pa.CubicBezier:return n?function(e,t,n,s,i){let o=e;for(let n=0;n<8;n++){const n=1-o,i=3*t*n*n*o+3*s*n*o*o+o*o*o-e;if(Math.abs(i)<za)break;const r=3*t*(1-2*o)*(1-o)+6*s*o*(1-o)-3*s*o*o+3*o*o;if(Math.abs(r)<za)break;o-=i/r}const r=1-o;return 3*n*r*r*o+3*i*r*o*o+o*o*o}(t,n.p1x,n.p1y,n.p2x,n.p2y):t;case Pa.Step:return function(e){return e<1?0:1}(t);default:return t}}const Ua=new class{constructor(){this.entries_=new Map,this.nextId_=1,this.cppSequences_=new Map,this.module_=null,this.registry_=null}init(e,t){this.module_=e,this.registry_=t}create(e,t,n,s,i){const o=this.nextId_++;return this.entries_.set(o,{id:o,from:e,to:t,duration:n,elapsed:0,delay:i?.delay??0,easing:i?.easing??Pa.Linear,bezierPoints:null,state:Ta.Running,loop:i?.loop??Ea.None,loopCount:i?.loopCount??0,loopsRemaining:i?.loopCount??0,callback:s,sequenceNext:null,sequenceNextExternal:null}),o}update(e){if(this.module_&&this.registry_)for(const[e,t]of this.cppSequences_){this.module_._anim_getTweenState(this.registry_,e)===Ta.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==Ta.Running)continue;if(t.delay>0){if(t.delay-=e,t.delay>0)continue;e=-t.delay,t.delay=0}t.elapsed+=e;const n=Math.min(t.elapsed/t.duration,1),s=$a(t.easing,n,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*s),n>=1){if(t.loop!==Ea.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===Ea.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=Ta.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===Ta.Running&&(t.state=Ta.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===Ta.Paused&&(t.state=Ta.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=Ta.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:Ta.Cancelled}setBezier(e,t,n,s,i){const o=this.entries_.get(e);o&&(o.bezierPoints={p1x:t,p1y:n,p2x:s,p2y:i})}setSequenceNext(e,t){const n=this.entries_.get(e);n&&(n.sequenceNext=t,this.pause(t))}setSequenceNextExternal(e,t){const n=this.entries_.get(e);n&&(n.sequenceNextExternal=t,t.pause())}registerCppSequence(e,t){this.cppSequences_.set(e,t),this.pause(t)}shutdown(){this.entries_.clear(),this.cppSequences_.clear(),this.module_=null,this.registry_=null,this.nextId_=1}};class Wa{constructor(e){this.id=e}get state(){return Ua.getState(this.id)}bezier(e,t,n,s){return Ua.setBezier(this.id,e,t,n,s),this}then(e){return e instanceof Wa?Ua.setSequenceNext(this.id,e.id):Ua.setSequenceNextExternal(this.id,e),this}pause(){Ua.pause(this.id)}resume(){Ua.resume(this.id)}cancel(){Ua.cancel(this.id)}}const Da={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12};class Oa{constructor(e,t,n){this.module_=e,this.registry_=t,this.entity=n}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,n,s){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,n,s),this}then(e){return e instanceof Wa?(Ua.registerCppSequence(this.entity,e.id),this):(this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this)}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let La=null,Ha=null;function ja(e,t){La=e,Ha=t,Ua.init(e,t)}function Xa(){Ua.shutdown(),La=null,Ha=null}function Na(){if(!La)throw new Error("Tween API not initialized");return La}function Ya(){if(!Ha)throw new Error("Tween API not initialized");return Ha}const Va={to(e,t,n,s,i,o){const r=Na(),a=Ya(),l=o?.easing??Pa.Linear,c=o?.delay??0,u=o?.loop??Ea.None,h=o?.loopCount??0,d=r._anim_createTween(a,e,t,n,s,i,l,c,u,h);return new Oa(r,a,d)},value(e,t,n,s,i){const o=Ua.create(e,t,n,s,i);return new Wa(o)},cancel(e){Na()._anim_cancelTween(Ya(),e.entity)},cancelAll(e){Na()._anim_cancelAllTweens(Ya(),e)},update(e){Na()._anim_updateTweens(Ya(),e),Ua.update(e)}};class qa{constructor(){this.name="AnimationPlugin"}build(e){ja(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(Kt.Update,Zt([ut(pt)],e=>{Va.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(Kt.Update,Zt([ut(pt)],e=>{Dn(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){Xa()}}const Ga=new qa;var Ka;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(Ka||(Ka={}));const Ja={model:Ka.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function Qa(e,t=Ja){const{model:n,refDistance:s,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(n){case Ka.Linear:{const e=i-s;if(e<=0)return 1;a=1-(Math.min(Math.max(r,s),i)-s)/e;break}case Ka.Inverse:a=s/Math.max(r,s);break;case Ka.Exponential:a=Math.pow(Math.max(r,s)/s,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function Za(e,t,n,s,i){const o=e-n;return Math.max(-1,Math.min(1,o/i))}const el=Ae("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:Ka.Inverse,rolloff:1,priority:0,enabled:!0}),tl=Ae("AudioListener",{enabled:!0});class nl{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const n=t().createAudioBackend(),s=this.config_;n.initialize({initialPoolSize:s.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const i=n.mixer;On.init(n,i),i&&(void 0!==s.masterVolume&&(i.master.volume=s.masterVolume),void 0!==s.musicVolume&&(i.music.volume=s.musicVolume),void 0!==s.sfxVolume&&(i.sfx.volume=s.sfxVolume));const o=new Map;this.activeSourceHandles_=o;const r=new Set;this.playedEntities_=r;const a=new Set;let l=!1,c=!1;e.addSystemToSchedule(Kt.PreUpdate,Zt([ut(pt)],t=>{if(!(!zo()||Wo()))return void(c&&(l=!1,c=!1));c=!0;const s=e.world;let i=0,u=0,h=!1;const d=s.getEntitiesWithComponents([tl,Ne]);for(const e of d){if(s.get(e,tl).enabled){const t=s.get(e,Ne);i=t.position.x,u=t.position.y,h=!0;break}}const f=s.getEntitiesWithComponents([el]);a.clear();for(const e of f){const t=s.get(e,el);if(!t.enabled||!t.clip)continue;const c=e;if(a.add(c),t.playOnAwake&&!r.has(c)&&!o.has(c)&&n.isReady){const e=On.getBufferHandle(t.clip);if(e){const s=n.play(e,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});o.set(c,s),r.add(c)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(c)){const n=o.get(c);if(!n.isPlaying){o.delete(c);continue}h||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=s.tryGet?.(e,Ne),a=r?.position.x??0,d=r?.position.y??0,f=a-i,p=d-u,m=Qa(Math.sqrt(f*f+p*p),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=Za(a,0,i,0,t.maxDistance);n.setVolume(t.volume*m),n.setPan(g)}}for(const[e,t]of o)a.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),On.dispose()}}const sl=new nl;function il(e,t){return e.toFixed(t)}function ol(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}class rl{constructor(e,t="bottom-left"){this.visible_=!0,this.disposed_=!1,this.el_=document.createElement("div"),this.el_.style.cssText="\nposition: fixed;\nz-index: 99999;\npointer-events: none;\nbackground: rgba(30, 30, 30, 0.85);\nborder: 1px solid rgba(60, 60, 60, 0.8);\nborder-radius: 4px;\npadding: 6px 10px;\nfont: 11px monospace;\ncolor: #cccccc;\nline-height: 1.6;\nmin-width: 200px;\nwhite-space: pre;\n"+function(e){switch(e){case"top-left":return"top: 12px; left: 12px;";case"top-right":return"top: 12px; right: 12px;";case"bottom-left":return"bottom: 12px; left: 12px;";case"bottom-right":return"bottom: 12px; right: 12px;"}}(t),e.appendChild(this.el_)}update(e){if(!this.visible_||this.disposed_)return;const t=[];if(t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div><div>FPS: <span style="color:#d19a66">${il(e.fps,1)}</span> Frame: <span style="color:#d19a66">${il(e.frameTimeMs,1)}ms</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div><div>DC: <span style="color:#d19a66">${e.drawCalls}</span> Tri: <span style="color:#d19a66">${e.triangles}</span></div><div>Sprites: <span style="color:#d19a66">${e.sprites}</span> Culled: <span style="color:#d19a66">${e.culled}</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div><div>Entities: <span style="color:#d19a66">${e.entityCount}</span></div>`),e.systemTimings.size>0){const n=[...e.systemTimings.entries()].sort((e,t)=>t[1]-e[1]).slice(0,5);let s='<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';for(const[e,t]of n){s+=`<div>${ol(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${il(t,1)}ms</span></div>`}t.push(s)}this.el_.innerHTML=t.join("")}show(){this.visible_=!0,this.el_.style.display=""}hide(){this.visible_=!1,this.el_.style.display="none"}dispose(){this.disposed_=!0,this.el_.parentElement?.removeChild(this.el_)}}function al(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const ll=ct(al(),"Stats");class cl{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,n){const s={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:n?new Map(n):new Map};this.count_<this.capacity_?(this.buffer_.push(s),this.count_++):this.buffer_[this.cursor_]=s,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}}const ul="StatsCollect";class hl{constructor(){this.deltas_=[],this.cursor_=0,this.count_=0,this.sum_=0}pushFrame(e){!Number.isFinite(e)||e<0||(this.count_<60?(this.deltas_.push(e),this.sum_+=e,this.count_++):(this.sum_-=this.deltas_[this.cursor_],this.deltas_[this.cursor_]=e,this.sum_+=e,this.cursor_=(this.cursor_+1)%60))}getFps(){return 0===this.count_||this.sum_<=0?0:this.count_/this.sum_}getFrameTimeMs(){return 0===this.count_||this.sum_<=0?0:this.sum_/this.count_*1e3}reset(){this.deltas_.length=0,this.cursor_=0,this.count_=0,this.sum_=0}}class dl{constructor(e){this.name="Stats",this.collector_=new hl,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(ll,al());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new rl(e,this.options_.position)}const t=this.collector_,n=this.overlay_,s=Zt([ut(pt),{_type:"get_world"}],(s,i)=>{t.pushFrame(s.delta);const o=e.getResource(ll);o.fps=t.getFps(),o.frameTimeMs=t.getFrameTimeMs(),o.entityCount=i.entityCount();const r=e.getSystemTimings();if(r){const e=new Map(r);e.delete(ul),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=ti.getStats();o.drawCalls=l.drawCalls,o.triangles=l.triangles,o.sprites=l.sprites,o.text=l.text,o.spine=l.spine,o.meshes=l.meshes,o.culled=l.culled,n?.update(o)},{name:ul});e.addSystemToSchedule(Kt.Last,s)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const fl=new dl;class pl{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,n)=>{const s=new Image;s.onload=()=>{const e=document.createElement("canvas");e.width=s.width,e.height=s.height;const n=e.getContext("2d");n.drawImage(s,0,0);const i=n.getImageData(0,0,s.width,s.height);t({width:s.width,height:s.height,pixels:new Uint8Array(i.data.buffer)})},s.onerror=n,s.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return function(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}(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}async function ml(e,t){try{const n=function(e){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}(t);return await e({instantiateWasm:(e,t)=>(WebAssembly.instantiate(n.buffer,e).then(e=>{t(e.instance,e.module)}),{})})}catch(e){return null}}async function gl(e){const{app:t,module:n,assets:s,sceneData:i,sceneName:o}=e,r=t.getResource(is);r&&(r.registerEmbeddedAssets(s),r.setEmbeddedOnly(!0));const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await ml(ESSpineModule,e);return t||console.warn("Spine module not available"),t}(e.spineWasmBase64):null,l=e.physicsWasmBase64?await async function(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await ml(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new pl(s);await ua({app:t,module:n,provider:c,scenes:[{name:o,data:i}],firstScene:o,spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()}const _l=[lo,So,Io,tr,ur,Ho,pr,wr,Pr,or,qo,Er,Ir,$r,Dr,Nr,Vr],yl=[..._l,Ga,sl];function wl(e,t){return function(e,t){const n=mi.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ss(e),_n(e),Os(e),Ns(e),Zs(e),si(e);const i=new ri;n.setPipeline(i);let o=d();const r=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=vi(e,s,t,i));const r=n.getResource(un);if(o.length>0){const e=o[0],n=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(n.x*t),r.vpY=Math.round((1-n.y-n.h)*i),r.vpW=Math.round(n.w*t),r.vpH=Math.round(n.h*i),r.screenW=t,r.screenH=i,r.worldLeft=e.cameraX-e.halfW,r.worldRight=e.cameraX+e.halfW,r.worldBottom=e.cameraY-e.halfH,r.worldTop=e.cameraY+e.halfH,r.valid=!0}else r.valid=!1}n.insertResource(un,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=r();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;ti.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-o)/1e3;let h;if(ti.resize(t,l),qs.isInitialized()&&qs.getPassCount()>0&&!qs.isBypassed()&&qs.resize(t,l),n.hasResource(hi)){const e=n.getResource(hi).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=vi(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:_i,width:t,height:l,elapsed:u});else{for(const e of f){const n=e.viewportRect,o=Math.round(n.x*t),r=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);i.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:u})}ti.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(Kt.First,l),n.addSystemToSchedule(Kt.Last,c),n.addPlugin(rs),n.addPlugin(_s),n.addPlugin(cn),n.addPlugin(pi),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:yl,...t})}class xl{constructor(e){this.resolvePath_=e}async loadPixels(e){return async function(e){return t().loadImagePixels(e)}(this.resolvePath_(e))}async readText(e){return l(this.resolvePath_(e))}async readBinary(e){const t=await a(this.resolvePath_(e));return new Uint8Array(t)}resolvePath(e){return this.resolvePath_(e)}}function vl(e){return(t,n)=>(u(e,t).then(e=>{n(e.instance,e.module)}),{})}async function bl(e,t){try{return await e({instantiateWasm:vl(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}async function Sl(e){const t=await l("asset-manifest.json"),n=JSON.parse(t),s=function(e){const t={},n={};for(const s in e.groups){const i=e.groups[s];for(const e in i.assets){const s=i.assets[e];t[e]=s,n[s.path]=s}}return{assetIndex:t,pathIndex:n}}(n),i=function(e){const{assetIndex:t,pathIndex:n}=e;return e=>{const s=U(e),i=t[e]||t[s]||n[s]||n[e];return i?i.path:s}}(s),o=wx.createCanvas(),r=wx.getSystemInfoSync();o.width=r.windowWidth*r.pixelRatio,o.height=r.windowHeight*r.pixelRatio;const a=await e.engineFactory({canvas:o,instantiateWasm:vl("esengine.wasm")}),c=o.getContext("webgl2")||o.getContext("webgl");if(!c)return void console.error("[ESEngine] Failed to create WebGL context");const u=a.GL.registerContext(c,{majorVersion:0===c.getParameter(c.VERSION).indexOf("WebGL 2")?2:1,minorVersion:0,enableExtensionsByDefault:!0}),h=wl(a,{glContextHandle:u,getViewportSize:()=>({width:o.width,height:o.height})});e.runtimeConfig&&me(h,e.runtimeConfig);let d=null;e.spineFactory&&(d=await bl(e.spineFactory,"spine.wasm"));let f=null;e.physicsFactory&&(f=await bl(e.physicsFactory,"physics.wasm"));const p=new xl(i),m=[];for(const t of e.sceneNames){const e=await l(`scenes/${t}.json`);m.push({name:t,data:JSON.parse(e)})}await ua({app:h,module:a,provider:p,scenes:m,firstScene:e.firstScene,spineModule:d,physicsModule:f,physicsConfig:e.physicsConfig,manifest:n,aspectRatio:o.width/o.height}),h.run()}J||(J=!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},i=await w(n,s);return{ok:i.ok,status:i.status,statusText:i.statusText,headers:new Headers(i.headers),json:()=>i.json(),text:()=>i.text(),arrayBuffer:()=>i.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 x(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 i=e.charCodeAt(t);i<128?n[s++]=i:i<2048?(n[s++]=192|i>>6,n[s++]=128|63&i):i>=55296&&i<=56319?(i=e.charCodeAt(++t)-56320+(i-55296<<10)+65536,n[s++]=240|i>>18,n[s++]=128|i>>12&63,n[s++]=128|i>>6&63,n[s++]=128|63&i):(n[s++]=224|i>>12,n[s++]=128|i>>6&63,n[s++]=128|63&i)}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 i=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(i>>10),56320+(1023&i)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=Q;export{Rt as Added,qa as AnimationPlugin,mi as App,os as AssetPlugin,as as AssetRefCounter,ss as AssetServer,is as Assets,An as AsyncCache,Ka as AttenuationModel,On as Audio,p as AudioBus,tl as AudioListener,m as AudioMixer,nl as AudioPlugin,g as AudioPool,el as AudioSource,Qe as BitmapText,hn as BlendMode,at as BodyType,it as BoxCollider,Eo as Button,To as ButtonState,Ve as Camera,qe as Canvas,rt as CapsuleCollider,It as Changed,Je as Children,ot as CircleCollider,Le as ClearFlags,Ot as Commands,Ht as CommandsInstance,ee as DEFAULT_DESIGN_HEIGHT,Z as DEFAULT_DESIGN_WIDTH,le as DEFAULT_FALLBACK_DT,ue as DEFAULT_FIXED_TIMESTEP,ie as DEFAULT_FONT_FAMILY,oe as DEFAULT_FONT_SIZE,ce as DEFAULT_GRAVITY,re as DEFAULT_LINE_HEIGHT,ae as DEFAULT_MAX_DELTA_TIME,te as DEFAULT_PIXELS_PER_UNIT,he as DEFAULT_SPINE_SKIN,se as DEFAULT_SPRITE_SIZE,ne as DEFAULT_TEXT_CANVAS_SIZE,zs as DataType,fr as DragPlugin,dr as DragState,hr as Draggable,Es as Draw,Ur as Dropdown,Wr as DropdownPlugin,Pa as EasingType,Lt as EntityCommands,Vt as EventReader,Gt as EventReaderInstance,Nt as EventRegistry,Yt as EventWriter,qt as EventWriterInstance,Ri as FillDirection,Ko as FillMethod,Jo as FillOrigin,Yo as FocusManager,No as FocusManagerState,Tr as FocusPlugin,Xo as Focusable,cl as FrameHistory,oi as GLDebug,js as Geometry,Jt as GetWorld,ge as INVALID_ENTITY,ye as INVALID_FONT,we as INVALID_MATERIAL,_e as INVALID_TEXTURE,Qo as Image,er as ImagePlugin,Go as ImageType,an as Input,ln as InputPlugin,rn as InputState,Mo as Interactable,Xr as LayoutGroupPlugin,kr as ListView,zr as ListViewPlugin,Xe as LocalTransform,ma as LogLevel,_a as Logger,Ea as LoopMode,xn as Material,Rn as MaterialLoader,Ct as Mut,et as Name,Ke as Parent,na as Physics,Kr as PhysicsEvents,ea as PhysicsPlugin,qs as PostProcess,ps as PrefabServer,ms as Prefabs,gs as PrefabsPlugin,fa as PreviewPlugin,ar as ProgressBar,rr as ProgressBarDirection,cr as ProgressBarPlugin,Oe as ProjectionType,$t as Query,Ut as QueryInstance,Wt as Removed,Dt as RemovedQueryInstance,ri as RenderPipeline,Ks as RenderStage,pa as RenderTexture,ti as Renderer,ut as Res,ht as ResMut,st as RigidBody,de as RuntimeConfig,Cr as SafeArea,Rr as SafeAreaPlugin,He as ScaleMode,hi as SceneManager,ui as SceneManagerState,tt as SceneOwner,Kt as Schedule,mr as ScrollView,yr as ScrollViewPlugin,Cn as ShaderSources,vr as Slider,xr as SliderDirection,Mr as SliderPlugin,Ze as SpineAnimation,Ye as Sprite,Wn as SpriteAnimator,ll as Stats,hl as StatsCollector,rl as StatsOverlay,dl as StatsPlugin,on as SystemRunner,io as Text,to as TextAlign,jo as TextInput,Vo as TextInputPlugin,so as TextOverflow,ao as TextPlugin,oo as TextRenderer,no as TextVerticalAlign,pt as Time,nr as Toggle,ir as TogglePlugin,je as Transform,Va as Tween,Oa as TweenHandle,Ta as TweenState,Da as TweenTarget,un as UICameraInfo,Co as UIEventQueue,Ao as UIEvents,Po as UIInteraction,Lo as UIInteractionPlugin,Ro as UILayoutPlugin,ho as UIMask,bo as UIMaskPlugin,ki as UIRect,Yr as UIRenderOrderPlugin,Ge as Velocity,xl as WeChatAssetProvider,ha as WebAssetProvider,Et as World,Ne as WorldTransform,nn as addStartupSystem,tn as addSystem,sn as addSystemToSchedule,Ga as animationPlugin,me as applyBuildRuntimeConfig,Di as applyDirectionalFill,fe as applyRuntimeConfig,rs as assetPlugin,sl as audioPlugin,Qa as calculateAttenuation,Za as calculatePanning,Un as clearAnimClips,Bs as clearDrawCallbacks,ke as clearUserComponents,Se as color,$i as computeFillAnchors,Wi as computeFillSize,Ui as computeHandleAnchors,Ii as computeUIRectLayout,vo as createMaskProcessor,ca as createRuntimeSceneConfig,wl as createWebApp,va as debug,al as defaultFrameStats,Ae as defineComponent,jt as defineEvent,ct as defineResource,Zt as defineSystem,Re as defineTag,pr as dragPlugin,Dr as dropdownPlugin,Ma as error,In as extractAnimClipTexturePaths,ns as findEntityByName,gi as flushPendingSystems,Er as focusPlugin,C as getAddressableType,A as getAddressableTypeByEditorType,I as getAllAssetExtensions,$n as getAnimClip,D as getAssetBuildTransform,z as getAssetMimeType,T as getAssetTypeEntry,We as getComponent,Xn as getComponentAssetFieldDescriptors,jn as getComponentAssetFields,nt as getComponentDefaults,qn as getComponentEntityFields,Nn as getComponentSpineFieldDescriptor,F as getCustomExtensions,E as getEditorType,wa as getLogger,t as getPlatform,s as getPlatformType,Ie as getUserComponent,B as getWeChatPackOptions,tr as imagePlugin,ba as info,Ss as initDrawAPI,si as initGLDebugAPI,Os as initGeometryAPI,_n as initMaterialAPI,gl as initPlayableRuntime,Ns as initPostProcessAPI,Zs as initRendererAPI,ua as initRuntime,ja as initTweenAPI,Sl as initWeChatRuntime,cn as inputPlugin,cs as instantiatePrefab,fo as intersectRects,po as invertMatrix4,ze as isBuiltinComponent,$ as isCustomExtension,zo as isEditor,R as isKnownAssetExtension,n as isPlatformInitialized,Wo as isPlayMode,$o as isRuntime,dn as isTextureRef,i as isWeChat,o as isWeb,Nr as layoutGroupPlugin,$r as listViewPlugin,es as loadComponent,Gr as loadPhysicsModule,la as loadRuntimeScene,Jn as loadSceneData,Qn as loadSceneWithAssets,k as looksLikeAssetPath,kn as parseAnimClipData,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,wo as pointInOBB,go as pointInWorldRect,_s as prefabsPlugin,ur as progressBarPlugin,Me as quat,Bn as registerAnimClip,W as registerAssetBuildTransform,Ue as registerComponent,Hn as registerComponentAssetFields,Vn as registerComponentEntityFields,ks as registerDrawCallback,ls as registerEmbeddedAssets,En as registerMaterialCallback,Gn as remapEntityFields,Ir as safeAreaPlugin,pi as sceneManagerPlugin,mo as screenToWorld,wr as scrollViewPlugin,Bo as setEditorMode,Br as setListViewRenderer,xa as setLogLevel,Uo as setPlayMode,wt as setWasmErrorHandler,Ms as shutdownDrawAPI,ii as shutdownGLDebugAPI,Ls as shutdownGeometryAPI,yn as shutdownMaterialAPI,Ys as shutdownPostProcessAPI,ei as shutdownRendererAPI,Xa as shutdownTweenAPI,Pr as sliderPlugin,Dn as spriteAnimatorSystemUpdate,fl as statsPlugin,Vi as syncFillSpriteSize,qo as textInputPlugin,lo as textPlugin,U as toBuildPath,or as togglePlugin,qr as transitionTo,Ho as uiInteractionPlugin,Io as uiLayoutPlugin,So as uiMaskPlugin,_l as uiPlugins,Vr as uiRenderOrderPlugin,zn as unregisterAnimClip,Fe as unregisterComponent,Fs as unregisterDrawCallback,ts as updateCameraAspectRatio,xe as vec2,ve as vec3,be as vec4,Sa as warn,di as wrapSceneSystem,N as wxFileExists,Y as wxFileExistsSync,G as wxGetImagePixels,q as wxLoadImage,K as wxLoadImagePixels,j as wxReadFile,X as wxReadTextFile,V as wxWriteFile};//# sourceMappingURL=index.wechat.js.mapdiff --git a/desktop/public/sdk/esm/esengine.d.ts b/desktop/public/sdk/esm/esengine.d.tsindex ca19e4a64..f9866f842 100644--- a/desktop/public/sdk/esm/esengine.d.ts+++ b/desktop/public/sdk/esm/esengine.d.ts@@ -1491,6 +1491,7 @@ declare class SpineModuleController {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' | 'anim-clip' | 'unknown';+type AssetBuildTransform = (content: string, context: unknown) => string;interface AssetTypeEntry {extensions: string[];contentType: AssetContentType;@@ -1498,6 +1499,7 @@ interface AssetTypeEntry {addressableType: AddressableAssetType | null;wechatPackInclude: boolean;hasTransitiveDeps: boolean;+ buildTransform?: AssetBuildTransform;}declare function getAssetTypeEntry(extensionOrPath: string): AssetTypeEntry | undefined;declare function getEditorType(path: string): EditorAssetType;@@ -1514,6 +1516,8 @@ declare function getWeChatPackOptions(): Array<{declare function getAssetMimeType(ext: string): string | undefined;declare function isCustomExtension(path: string): boolean;declare function toBuildPath(path: string): string;+declare function registerAssetBuildTransform(editorType: EditorAssetType, transform: AssetBuildTransform): void;+declare function getAssetBuildTransform(extensionOrPath: string): AssetBuildTransform | undefined;/*** @file AssetServer.ts@@ -3464,8 +3468,8 @@ type WasmErrorHandler = (error: unknown, context: string) => void;declare function setWasmErrorHandler(handler: WasmErrorHandler | null): void;/**- * @file Tween.ts- * @brief Property tween API wrapping C++ TweenSystem+ * @file ValueTween.ts+ * @brief JS-side value tweening with easing functions ported from C++*/declare const EasingType: {@@ -3487,22 +3491,6 @@ declare const EasingType: {readonly Step: 15;};type EasingType = (typeof EasingType)[keyof typeof EasingType];-declare const TweenTarget: {- readonly PositionX: 0;- readonly PositionY: 1;- readonly PositionZ: 2;- readonly ScaleX: 3;- readonly ScaleY: 4;- readonly RotationZ: 5;- readonly ColorR: 6;- readonly ColorG: 7;- readonly ColorB: 8;- readonly ColorA: 9;- readonly SizeX: 10;- readonly SizeY: 11;- readonly CameraOrthoSize: 12;-};-type TweenTarget = (typeof TweenTarget)[keyof typeof TweenTarget];declare const TweenState: {readonly Running: 0;readonly Paused: 1;@@ -3528,6 +3516,42 @@ interface BezierPoints {p2x: number;p2y: number;}+declare class ValueTweenHandle {+ readonly id: number;+ constructor(id: number);+ get state(): TweenState;+ bezier(p1x: number, p1y: number, p2x: number, p2y: number): this;+ then(next: ValueTweenHandle): this;+ then(next: {+ pause(): void;+ resume(): void;+ }): this;+ pause(): void;+ resume(): void;+ cancel(): void;+}++/**+ * @file Tween.ts+ * @brief Property tween API wrapping C++ TweenSystem+ */++declare const TweenTarget: {+ readonly PositionX: 0;+ readonly PositionY: 1;+ readonly PositionZ: 2;+ readonly ScaleX: 3;+ readonly ScaleY: 4;+ readonly RotationZ: 5;+ readonly ColorR: 6;+ readonly ColorG: 7;+ readonly ColorB: 8;+ readonly ColorA: 9;+ readonly SizeX: 10;+ readonly SizeY: 11;+ readonly CameraOrthoSize: 12;+};+type TweenTarget = (typeof TweenTarget)[keyof typeof TweenTarget];declare class TweenHandle {private readonly module_;private readonly registry_;@@ -3535,7 +3559,7 @@ declare class TweenHandle {constructor(module: ESEngineModule, registry: CppRegistry, entity: Entity);get state(): TweenState;bezier(p1x: number, p1y: number, p2x: number, p2y: number): this;- then(next: TweenHandle): this;+ then(next: TweenHandle | ValueTweenHandle): this;pause(): void;resume(): void;cancel(): void;@@ -3543,10 +3567,11 @@ declare class TweenHandle {declare function initTweenAPI(module: ESEngineModule, registry: CppRegistry): void;declare function shutdownTweenAPI(): void;declare const Tween: {- readonly to: (entity: Entity, target: TweenTarget, from: number, to: number, duration: number, options?: TweenOptions) => TweenHandle;- readonly cancel: (tweenHandle: TweenHandle) => void;- readonly cancelAll: (entity: Entity) => void;- readonly update: (deltaTime: number) => void;+ to(entity: Entity, target: TweenTarget, from: number, to: number, duration: number, options?: TweenOptions): TweenHandle;+ value(from: number, to: number, duration: number, callback: (value: number) => void, options?: TweenOptions): ValueTweenHandle;+ cancel(tweenHandle: TweenHandle): void;+ cancelAll(entity: Entity): void;+ update(deltaTime: number): void;};/**@@ -3557,6 +3582,14 @@ declare const Tween: {interface SpriteAnimFrame {texture: TextureHandle;duration?: number;+ uvOffset?: {+ x: number;+ y: number;+ };+ uvScale?: {+ x: number;+ y: number;+ };}interface SpriteAnimClip {name: string;@@ -3597,14 +3630,23 @@ declare const animationPlugin: AnimationPlugin;* @brief .esanim asset loading and parsing*/+interface AnimClipFrameData {+ texture: string;+ atlasFrame?: {+ x: number;+ y: number;+ width: number;+ height: number;+ pageWidth: number;+ pageHeight: number;+ };+}interface AnimClipAssetData {version: string;type: 'animation-clip';fps?: number;loop?: boolean;- frames: {- texture: string;- }[];+ frames: AnimClipFrameData[];}declare function extractAnimClipTexturePaths(data: AnimClipAssetData): string[];declare function parseAnimClipData(clipPath: string, data: AnimClipAssetData, textureHandles: Map<string, number>): SpriteAnimClip;@@ -3815,5 +3857,5 @@ declare const uiPlugins: Plugin[];declare function createWebApp(module: ESEngineModule, options?: WebAppOptions): App;-export { Added, AnimationPlugin, App, AssetPlugin, AssetRefCounter, AssetServer, Assets, AsyncCache, AttenuationModel, Audio, AudioBus, AudioListener, AudioMixer, AudioPlugin, AudioPool, AudioSource, BitmapText$1 as BitmapText, BlendMode, BodyType, BoxCollider$1 as BoxCollider, Button, ButtonState, Camera$1 as Camera, Canvas$1 as Canvas, CapsuleCollider$1 as CapsuleCollider, Changed, Children$1 as Children, CircleCollider$1 as CircleCollider, ClearFlags, Commands, CommandsInstance, DEFAULT_DESIGN_HEIGHT, DEFAULT_DESIGN_WIDTH, DEFAULT_FALLBACK_DT, DEFAULT_FIXED_TIMESTEP, DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE, DEFAULT_GRAVITY, DEFAULT_LINE_HEIGHT, DEFAULT_MAX_DELTA_TIME, DEFAULT_PIXELS_PER_UNIT, DEFAULT_SPINE_SKIN, DEFAULT_SPRITE_SIZE, DEFAULT_TEXT_CANVAS_SIZE, DataType, DragPlugin, DragState, Draggable, Draw, Dropdown, DropdownPlugin, EasingType, EntityCommands, EventReader, EventReaderInstance, EventRegistry, EventWriter, EventWriterInstance, FillDirection, FillMethod, FillOrigin, FocusManager, FocusManagerState, FocusPlugin, Focusable, FrameHistory, GLDebug, Geometry, GetWorld, INVALID_ENTITY, INVALID_FONT, INVALID_MATERIAL, INVALID_TEXTURE, Image, ImagePlugin, ImageType, Input, InputPlugin, InputState, Interactable, LayoutGroupPlugin, ListView, ListViewPlugin, LocalTransform, LogLevel, Logger, LoopMode, MaskMode, Material, MaterialLoader, Mut, Name, Parent$1 as Parent, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PrefabServer, Prefabs, PrefabsPlugin, PreviewPlugin, ProgressBar, ProgressBarDirection, ProgressBarPlugin, ProjectionType, Query, QueryInstance, Removed, RemovedQueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, RigidBody$1 as RigidBody, RuntimeConfig, SafeArea, SafeAreaPlugin, ScaleMode, SceneManager, SceneManagerState, SceneOwner, Schedule, ScrollView, ScrollViewPlugin, ShaderSources, Slider, SliderDirection, SliderPlugin, SpineAnimation$1 as SpineAnimation, Sprite$1 as Sprite, SpriteAnimator, Stats, StatsCollector, StatsOverlay, StatsPlugin, SystemRunner, Text, TextAlign, TextInput, TextInputPlugin, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, Toggle, TogglePlugin, Transform$1 as Transform, Tween, TweenHandle, TweenState, TweenTarget, UICameraInfo, UIEventQueue, UIEvents, UIInteraction, UIInteractionPlugin, UILayoutPlugin, UIMask, UIMaskPlugin, UIRect, UIRenderOrderPlugin, Velocity$1 as Velocity, WebAssetProvider, World, WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, animationPlugin, applyBuildRuntimeConfig, applyDirectionalFill, applyRuntimeConfig, assetPlugin, audioPlugin, calculateAttenuation, calculatePanning, clearAnimClips, clearDrawCallbacks, clearUserComponents, color, computeFillAnchors, computeFillSize, computeHandleAnchors, computeUIRectLayout, createMaskProcessor, createRuntimeSceneConfig, createWebApp, debug, defaultFrameStats, defineComponent, defineEvent, defineResource, defineSystem, defineTag, dragPlugin, dropdownPlugin, error, extractAnimClipTexturePaths, findEntityByName, flushPendingSystems, focusPlugin, getAddressableType, getAddressableTypeByEditorType, getAllAssetExtensions, getAnimClip, getAssetMimeType, getAssetTypeEntry, getComponent, getComponentAssetFieldDescriptors, getComponentAssetFields, getComponentDefaults, getComponentEntityFields, getComponentSpineFieldDescriptor, getCustomExtensions, getEditorType, getLogger, getPlatform, getPlatformType, getUserComponent, getWeChatPackOptions, imagePlugin, info, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPlayableRuntime, initPostProcessAPI, initRendererAPI, initRuntime, initTweenAPI, inputPlugin, instantiatePrefab, intersectRects, invertMatrix4, isBuiltinComponent, isCustomExtension, isEditor, isKnownAssetExtension, isPlatformInitialized, isPlayMode, isRuntime, isTextureRef, isWeChat, isWeb, layoutGroupPlugin, listViewPlugin, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, looksLikeAssetPath, parseAnimClipData, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInOBB, pointInWorldRect, prefabsPlugin, progressBarPlugin, quat, registerAnimClip, registerComponent, registerComponentAssetFields, registerComponentEntityFields, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, remapEntityFields, safeAreaPlugin, sceneManagerPlugin, screenToWorld, scrollViewPlugin, setEditorMode, setListViewRenderer, setLogLevel, setPlayMode, setWasmErrorHandler, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, shutdownTweenAPI, sliderPlugin, spriteAnimatorSystemUpdate, statsPlugin, syncFillSpriteSize, textInputPlugin, textPlugin, toBuildPath, togglePlugin, transitionTo, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, uiPlugins, uiRenderOrderPlugin, unregisterAnimClip, unregisterComponent, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, warn, wrapSceneSystem };-export type { AddedWrapper, AddressableAssetType, AddressableManifest, AddressableManifestAsset, AddressableManifestGroup, AddressableResultMap, AnimClipAssetData, AnyComponentDef, AssetBundle, AssetContentType, AssetFieldType, AssetRefInfo, AssetTypeEntry, AssetsData, AudioBackendInitOptions, AudioBufferHandle, AudioBusConfig, AudioHandle, AudioListenerData, AudioMixerConfig, AudioPluginConfig, AudioSourceData, BezierPoints, BitmapTextData, BoxColliderData, BuiltinComponentDef, ButtonData, ButtonTransition, CameraData, CameraRenderParams, CanvasData, CapsuleColliderData, ChangedWrapper, ChildrenData, CircleColliderData, CollisionEnterEvent, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DragStateData, DraggableData, DrawAPI, DrawCallback, DropdownData, ESEngineModule, EditorAssetType, Entity, EventDef, EventReaderDescriptor, EventWriterDescriptor, FileLoadOptions, FocusableData, FontHandle, FrameSnapshot, FrameStats, GeometryHandle, GeometryOptions, GetWorldDescriptor, ImageData, InferParam, InferParams, InstantiatePrefabOptions, InstantiatePrefabResult, InteractableData, LayoutRect, LayoutResult, ListViewData, ListViewItemRenderer, LoadRuntimeSceneOptions, LoadedMaterial, LocalTransformData, LogEntry, LogHandler, MaskProcessorFn, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, NameData, ParentData, PhysicsEventsData, PhysicsModuleFactory, PhysicsPluginConfig, PhysicsWasmModule, PlatformAdapter, PlatformAudioBackend, PlatformRequestOptions, PlatformResponse, PlatformType, PlayConfig, PlayableRuntimeConfig, Plugin, PluginDependency, PooledAudioNode, PrefabData, PrefabEntityData, PrefabOverride, ProgressBarData, Quat, QueryBuilder, QueryDescriptor, QueryResult, RemovedQueryDescriptor, RenderParams, RenderStats, RenderTargetHandle, RenderTextureHandle, RenderTextureOptions, ResDescriptor, ResMutDescriptor, ResourceDef, RigidBodyData, RuntimeAssetProvider, RuntimeBuildConfig, RuntimeInitConfig, SafeAreaData, SceneComponentData, SceneConfig, SceneContext, SceneData, SceneEntityData, SceneLoadOptions, SceneOwnerData, SceneStatus, ScreenRect, ScrollViewData, SensorEvent, ShaderHandle, ShaderLoader, SliceBorder$1 as SliceBorder, SliderData, SpatialAudioConfig, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteAnimClip, SpriteAnimFrame, SpriteAnimatorData, SpriteData, StatsPluginOptions, StatsPosition, SystemDef, SystemOptions, SystemParam, TextData, TextInputData, TextRenderResult, TextureHandle, TextureInfo, TextureRef, TimeData, ToggleData, ToggleTransition, TransformData, TransitionConfig, TransitionOptions, TweenOptions, UICameraData, UIEvent, UIEventType, UIInteractionData, UIMaskData, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WorldTransformData };+export { Added, AnimationPlugin, App, AssetPlugin, AssetRefCounter, AssetServer, Assets, AsyncCache, AttenuationModel, Audio, AudioBus, AudioListener, AudioMixer, AudioPlugin, AudioPool, AudioSource, BitmapText$1 as BitmapText, BlendMode, BodyType, BoxCollider$1 as BoxCollider, Button, ButtonState, Camera$1 as Camera, Canvas$1 as Canvas, CapsuleCollider$1 as CapsuleCollider, Changed, Children$1 as Children, CircleCollider$1 as CircleCollider, ClearFlags, Commands, CommandsInstance, DEFAULT_DESIGN_HEIGHT, DEFAULT_DESIGN_WIDTH, DEFAULT_FALLBACK_DT, DEFAULT_FIXED_TIMESTEP, DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE, DEFAULT_GRAVITY, DEFAULT_LINE_HEIGHT, DEFAULT_MAX_DELTA_TIME, DEFAULT_PIXELS_PER_UNIT, DEFAULT_SPINE_SKIN, DEFAULT_SPRITE_SIZE, DEFAULT_TEXT_CANVAS_SIZE, DataType, DragPlugin, DragState, Draggable, Draw, Dropdown, DropdownPlugin, EasingType, EntityCommands, EventReader, EventReaderInstance, EventRegistry, EventWriter, EventWriterInstance, FillDirection, FillMethod, FillOrigin, FocusManager, FocusManagerState, FocusPlugin, Focusable, FrameHistory, GLDebug, Geometry, GetWorld, INVALID_ENTITY, INVALID_FONT, INVALID_MATERIAL, INVALID_TEXTURE, Image, ImagePlugin, ImageType, Input, InputPlugin, InputState, Interactable, LayoutGroupPlugin, ListView, ListViewPlugin, LocalTransform, LogLevel, Logger, LoopMode, MaskMode, Material, MaterialLoader, Mut, Name, Parent$1 as Parent, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PrefabServer, Prefabs, PrefabsPlugin, PreviewPlugin, ProgressBar, ProgressBarDirection, ProgressBarPlugin, ProjectionType, Query, QueryInstance, Removed, RemovedQueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, RigidBody$1 as RigidBody, RuntimeConfig, SafeArea, SafeAreaPlugin, ScaleMode, SceneManager, SceneManagerState, SceneOwner, Schedule, ScrollView, ScrollViewPlugin, ShaderSources, Slider, SliderDirection, SliderPlugin, SpineAnimation$1 as SpineAnimation, Sprite$1 as Sprite, SpriteAnimator, Stats, StatsCollector, StatsOverlay, StatsPlugin, SystemRunner, Text, TextAlign, TextInput, TextInputPlugin, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, Toggle, TogglePlugin, Transform$1 as Transform, Tween, TweenHandle, TweenState, TweenTarget, UICameraInfo, UIEventQueue, UIEvents, UIInteraction, UIInteractionPlugin, UILayoutPlugin, UIMask, UIMaskPlugin, UIRect, UIRenderOrderPlugin, Velocity$1 as Velocity, WebAssetProvider, World, WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, animationPlugin, applyBuildRuntimeConfig, applyDirectionalFill, applyRuntimeConfig, assetPlugin, audioPlugin, calculateAttenuation, calculatePanning, clearAnimClips, clearDrawCallbacks, clearUserComponents, color, computeFillAnchors, computeFillSize, computeHandleAnchors, computeUIRectLayout, createMaskProcessor, createRuntimeSceneConfig, createWebApp, debug, defaultFrameStats, defineComponent, defineEvent, defineResource, defineSystem, defineTag, dragPlugin, dropdownPlugin, error, extractAnimClipTexturePaths, findEntityByName, flushPendingSystems, focusPlugin, getAddressableType, getAddressableTypeByEditorType, getAllAssetExtensions, getAnimClip, getAssetBuildTransform, getAssetMimeType, getAssetTypeEntry, getComponent, getComponentAssetFieldDescriptors, getComponentAssetFields, getComponentDefaults, getComponentEntityFields, getComponentSpineFieldDescriptor, getCustomExtensions, getEditorType, getLogger, getPlatform, getPlatformType, getUserComponent, getWeChatPackOptions, imagePlugin, info, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPlayableRuntime, initPostProcessAPI, initRendererAPI, initRuntime, initTweenAPI, inputPlugin, instantiatePrefab, intersectRects, invertMatrix4, isBuiltinComponent, isCustomExtension, isEditor, isKnownAssetExtension, isPlatformInitialized, isPlayMode, isRuntime, isTextureRef, isWeChat, isWeb, layoutGroupPlugin, listViewPlugin, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, looksLikeAssetPath, parseAnimClipData, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInOBB, pointInWorldRect, prefabsPlugin, progressBarPlugin, quat, registerAnimClip, registerAssetBuildTransform, registerComponent, registerComponentAssetFields, registerComponentEntityFields, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, remapEntityFields, safeAreaPlugin, sceneManagerPlugin, screenToWorld, scrollViewPlugin, setEditorMode, setListViewRenderer, setLogLevel, setPlayMode, setWasmErrorHandler, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, shutdownTweenAPI, sliderPlugin, spriteAnimatorSystemUpdate, statsPlugin, syncFillSpriteSize, textInputPlugin, textPlugin, toBuildPath, togglePlugin, transitionTo, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, uiPlugins, uiRenderOrderPlugin, unregisterAnimClip, unregisterComponent, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, warn, wrapSceneSystem };+export type { AddedWrapper, AddressableAssetType, AddressableManifest, AddressableManifestAsset, AddressableManifestGroup, AddressableResultMap, AnimClipAssetData, AnyComponentDef, AssetBuildTransform, AssetBundle, AssetContentType, AssetFieldType, AssetRefInfo, AssetTypeEntry, AssetsData, AudioBackendInitOptions, AudioBufferHandle, AudioBusConfig, AudioHandle, AudioListenerData, AudioMixerConfig, AudioPluginConfig, AudioSourceData, BezierPoints, BitmapTextData, BoxColliderData, BuiltinComponentDef, ButtonData, ButtonTransition, CameraData, CameraRenderParams, CanvasData, CapsuleColliderData, ChangedWrapper, ChildrenData, CircleColliderData, CollisionEnterEvent, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DragStateData, DraggableData, DrawAPI, DrawCallback, DropdownData, ESEngineModule, EditorAssetType, Entity, EventDef, EventReaderDescriptor, EventWriterDescriptor, FileLoadOptions, FocusableData, FontHandle, FrameSnapshot, FrameStats, GeometryHandle, GeometryOptions, GetWorldDescriptor, ImageData, InferParam, InferParams, InstantiatePrefabOptions, InstantiatePrefabResult, InteractableData, LayoutRect, LayoutResult, ListViewData, ListViewItemRenderer, LoadRuntimeSceneOptions, LoadedMaterial, LocalTransformData, LogEntry, LogHandler, MaskProcessorFn, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, NameData, ParentData, PhysicsEventsData, PhysicsModuleFactory, PhysicsPluginConfig, PhysicsWasmModule, PlatformAdapter, PlatformAudioBackend, PlatformRequestOptions, PlatformResponse, PlatformType, PlayConfig, PlayableRuntimeConfig, Plugin, PluginDependency, PooledAudioNode, PrefabData, PrefabEntityData, PrefabOverride, ProgressBarData, Quat, QueryBuilder, QueryDescriptor, QueryResult, RemovedQueryDescriptor, RenderParams, RenderStats, RenderTargetHandle, RenderTextureHandle, RenderTextureOptions, ResDescriptor, ResMutDescriptor, ResourceDef, RigidBodyData, RuntimeAssetProvider, RuntimeBuildConfig, RuntimeInitConfig, SafeAreaData, SceneComponentData, SceneConfig, SceneContext, SceneData, SceneEntityData, SceneLoadOptions, SceneOwnerData, SceneStatus, ScreenRect, ScrollViewData, SensorEvent, ShaderHandle, ShaderLoader, SliceBorder$1 as SliceBorder, SliderData, SpatialAudioConfig, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteAnimClip, SpriteAnimFrame, SpriteAnimatorData, SpriteData, StatsPluginOptions, StatsPosition, SystemDef, SystemOptions, SystemParam, TextData, TextInputData, TextRenderResult, TextureHandle, TextureInfo, TextureRef, TimeData, ToggleData, ToggleTransition, TransformData, TransitionConfig, TransitionOptions, TweenOptions, 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 b0a13bb93..3a19421b3 100644--- a/desktop/public/sdk/esm/esengine.js+++ b/desktop/public/sdk/esm/esengine.js@@ -1,2 +1,2 @@-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function s(){return null!==e}function n(){return e?.name??null}function i(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function r(e,s){return t().fetch(e,s)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function d(e,s){return t().instantiateWasm(e,s)}function h(e,s){return t().createCanvas(e,s)}function u(){return t().now()}function f(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}class p{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,t.volume??1)),this.muted_=t.muted??!1,this.gainNode_.gain.value=this.muted_?0:this.volume_}get name(){return this.name_}get node(){return this.gainNode_}get volume(){return this.volume_}set volume(e){this.volume_=Math.max(0,Math.min(1,e)),this.muted_||this.gainNode_.gain.setTargetAtTime(this.volume_,this.gainNode_.context.currentTime,.015)}get muted(){return this.muted_}set muted(e){this.muted_=e,this.gainNode_.gain.setTargetAtTime(e?0:this.volume_,this.gainNode_.context.currentTime,.015)}connect(e){e instanceof p?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class m{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new p(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new p(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new p(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new p(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new p(e,{name:"voice",volume:t.voiceVolume??1}),this.master.addChild(this.voice),this.buses_.set("master",this.master),this.buses_.set("music",this.music),this.buses_.set("sfx",this.sfx),this.buses_.set("ui",this.ui),this.buses_.set("voice",this.voice)}getBus(e){return this.buses_.get(e)}createBus(e){const t=new p(this.context_,e),s=e.parent?this.buses_.get(e.parent):this.master;return s&&s.addChild(t),this.buses_.set(e.name,t),t}}class _{constructor(e,t=16){this.pool_=[],this.activeCount_=0,this.context_=e;for(let e=0;e<t;e++)this.pool_.push(this.createNode())}createNode(){const e=this.context_.createGain(),t=this.context_.createStereoPanner();return e.connect(t),{gain:e,panner:t,source:null,inUse:!1,startTime:0}}acquire(){let e=this.pool_.find(e=>!e.inUse);return e||(e=this.createNode(),this.pool_.push(e)),e.inUse=!0,e.startTime=this.context_.currentTime,e.gain.gain.value=1,e.panner.pan.value=0,this.activeCount_++,e}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}}class g{constructor(e,t,s,n,i,o,r){this.playing_=!0,this.stopped_=!1,this.pausedAt_=0,this.id=e,this.source_=t,this.buffer_=s,this.poolNode_=n,this.pool_=i,this.context_=o,this.startOffset_=r,this.startedAt_=o.currentTime,this.playbackRate_=t.playbackRate.value,this.loop_=t.loop,this.bindOnEnded_(t)}bindOnEnded_(e){e.onended=()=>{this.stopped_||this.loop_||(this.playing_=!1,this.stopped_=!0,this.pool_.release(this.poolNode_),this.onEnd?.())}}stop(){this.stopped_||(this.stopped_=!0,this.playing_=!1,this.source_.onended=null,this.pool_.release(this.poolNode_))}pause(){if(!this.playing_||this.stopped_)return;this.playing_=!1;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;this.pausedAt_=this.startOffset_+e,this.loop_&&this.buffer_.duration>0&&(this.pausedAt_=this.pausedAt_%this.buffer_.duration),this.source_.onended=null;try{this.source_.stop()}catch(e){}this.source_.disconnect()}resume(){if(this.playing_||this.stopped_)return;this.playing_=!0;const e=this.context_.createBufferSource();e.buffer=this.buffer_,e.loop=this.loop_,e.playbackRate.value=this.playbackRate_,e.connect(this.poolNode_.gain),this.source_=e,this.poolNode_.source=e,this.startOffset_=this.pausedAt_,this.startedAt_=this.context_.currentTime,this.bindOnEnded_(e),e.start(0,this.pausedAt_)}setVolume(e){this.poolNode_.gain.gain.value=e}setPan(e){this.poolNode_.panner.pan.value=e}setLoop(e){this.loop_=e,this.source_.loop=e}setPlaybackRate(e){this.playbackRate_=e,this.playing_&&(this.source_.playbackRate.value=e)}get isPlaying(){return this.playing_}get currentTime(){if(this.stopped_)return 0;if(!this.playing_)return this.pausedAt_;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;return this.startOffset_+e}get duration(){return this.buffer_.duration}}class y{constructor(){this.name="WebAudio",this.context_=null,this.mixer_=null,this.pool_=null,this.buffers_=new Map,this.urlToId_=new Map,this.loadingUrls_=new Map,this.nextBufferId_=0,this.nextHandleId_=0,this.resumeHandler_=null}get mixer(){return this.mixer_}get isReady(){return"running"===this.context_?.state}async initialize(e={}){if(this.context_=new AudioContext,this.mixer_=new m(this.context_,e.mixerConfig),this.pool_=new _(this.context_,e.initialPoolSize),"suspended"===this.context_.state){const e=()=>{this.context_.resume(),document.removeEventListener("touchstart",e),document.removeEventListener("mousedown",e),document.removeEventListener("keydown",e),this.resumeHandler_=null};document.addEventListener("touchstart",e),document.addEventListener("mousedown",e),document.addEventListener("keydown",e),this.resumeHandler_=e}}async ensureResumed(){this.context_&&"suspended"===this.context_.state&&await this.context_.resume()}async loadBuffer(e){if(!this.context_)throw new Error("AudioContext not initialized");const t=this.urlToId_.get(e);if(void 0!==t&&this.buffers_.has(t)){return{id:t,duration:this.buffers_.get(t).duration}}const s=this.loadingUrls_.get(e);if(s)return s;const n=this.doLoadBuffer_(e);this.loadingUrls_.set(e,n);try{return await n}finally{this.loadingUrls_.delete(e)}}async doLoadBuffer_(e){const s=await t().readFile(e);let n;try{n=await this.context_.decodeAudioData(s)}catch(t){throw new Error(`Failed to decode audio ${e}: ${t.message}`)}const i=++this.nextBufferId_;return this.buffers_.set(i,n),this.urlToId_.set(e,i),{id:i,duration:n.duration}}unloadBuffer(e){this.buffers_.delete(e.id)}play(e,t){if(!this.context_||!this.pool_||!this.mixer_)throw new Error("Audio system not initialized");const s=this.buffers_.get(e.id);if(!s)throw new Error(`Buffer ${e.id} not found`);const n=this.pool_.acquire(),i=this.context_.createBufferSource();i.buffer=s,i.loop=t.loop??!1,i.playbackRate.value=t.playbackRate??1,i.connect(n.gain),n.source=i,n.gain.gain.value=t.volume??1,n.panner.pan.value=t.pan??0;const o=t.bus??"sfx",r=this.mixer_.getBus(o)??this.mixer_.sfx;n.panner.connect(r.node);const a=t.startOffset??0;i.start(0,a);const l=++this.nextHandleId_;return new g(l,i,s,n,this.pool_,this.context_,a)}suspend(){this.context_?.suspend()}resume(){this.context_?.resume()}dispose(){this.resumeHandler_&&(document.removeEventListener("touchstart",this.resumeHandler_),document.removeEventListener("mousedown",this.resumeHandler_),document.removeEventListener("keydown",this.resumeHandler_),this.resumeHandler_=null),this.pool_=null,this.mixer_=null,this.buffers_.clear(),this.urlToId_.clear(),this.loadingUrls_.clear(),this.context_?.close(),this.context_=null}}const w=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const s=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),n={};return s.headers.forEach((e,t)=>{n[t]=e}),{ok:s.ok,status:s.status,statusText:s.statusText,headers:n,json:()=>s.json(),text:()=>s.text(),arrayBuffer:()=>s.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async loadImagePixels(e){const t=this.createImage();await new Promise((s,n)=>{t.crossOrigin="anonymous",t.onload=()=>s(),t.onerror=()=>n(new Error(`Failed to load image: ${e}`)),t.src=e});const s=this.createCanvas(t.width,t.height).getContext("2d");s.drawImage(t,0,0);const n=s.getImageData(0,0,t.width,t.height);return{width:t.width,height:t.height,pixels:new Uint8Array(n.data.buffer)}}async instantiateWasm(e,t){let s;s="string"==typeof e?await this.readFile(e):e;const n=await WebAssembly.instantiate(s,t);return{instance:n.instance,module:n.module}}createImage(){return new Image}createCanvas(e,t){let s;return s="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),s.width=e,s.height=t,s}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const s=t??document.querySelector("canvas")??document.body,n=t=>e.onKeyDown(t.code),i=t=>e.onKeyUp(t.code),o=t=>{const s=t;e.onPointerMove(s.offsetX,s.offsetY)},r=t=>{const s=t;e.onPointerDown(s.button,s.offsetX,s.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerDown(0,n.clientX-t.left,n.clientY-t.top)}},c=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerMove(n.clientX-t.left,n.clientY-t.top)}},d=()=>{e.onPointerUp(0)},h=t=>{const s=t;let n=s.deltaX,i=s.deltaY;1===s.deltaMode?(n*=16,i*=16):2===s.deltaMode&&(n*=window.innerWidth,i*=window.innerHeight),e.onWheel(n,i)};document.addEventListener("keydown",n),document.addEventListener("keyup",i),s.addEventListener("mousemove",o),s.addEventListener("mousedown",r),document.addEventListener("mouseup",a),s.addEventListener("touchstart",l),s.addEventListener("touchmove",c),s.addEventListener("touchend",d),s.addEventListener("wheel",h),this.inputCleanup_=()=>{document.removeEventListener("keydown",n),document.removeEventListener("keyup",i),s.removeEventListener("mousemove",o),s.removeEventListener("mousedown",r),document.removeEventListener("mouseup",a),s.removeEventListener("touchstart",l),s.removeEventListener("touchmove",c),s.removeEventListener("touchend",d),s.removeEventListener("wheel",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new y}},x=1920,v=1080,b=100,S=512,M={x:100,y:100},P="Arial",T=24,E=1.2,C=.5,A=1/60,R={x:0,y:-9.81},I=1/60,k="default",F={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function B(e){e.Text&&(e.Text._default.fontFamily=F.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=F.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=F.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=F.canvasMatchWidthOrHeight)}const z={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function U(e,t){if(void 0!==t.maxDeltaTime&&(F.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(F.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(F.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(F.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(F.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");F.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&(F.canvasScaleMode=z[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(F.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight)}const $=0,D=4294967295,L=4294967295,O=0,W=(e=0,t=0)=>({x:e,y:t}),H=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),X=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),j=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),Y=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});function N(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(N);const t={};for(const s in e)t[s]=N(e[s]);return t}let V=0;function q(e,t){const s=++V,n=function(e){for(const t in e){const s=e[t];if(null!==s&&"object"==typeof s)return!0}return!1}(t);return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>n?e?{...N(t),...e}:N(t):e?{...t,...e}:{...t}}}function G(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function K(e,t){const s=ne.get(e)??G().get(e);if(s)return s;const n=q(e,t);return G().set(e,n),ne.set(e,n),te(e,t,!1),n}function J(e){const t=ne.get(e)??G().get(e);if(t)return t;const s=q(e,{});return G().set(e,s),ne.set(e,s),te(e,{},!0),s}function Q(e){return G().get(e)}function Z(){const e=G();for(const t of e.keys())ne.delete(t);e.clear()}function ee(e){G().delete(e),ne.delete(e)}function te(e,t,s){const n=globalThis;n.__esengine_registerComponent&&n.__esengine_registerComponent(e,t,s)}function se(e){return!0===e._builtin}const ne=new Map;function ie(e,t){ne.set(e,t)}function oe(e){return ne.get(e)??Q(e)}function re(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return ne.set(e,s),s}const ae={Perspective:0,Orthographic:1},le={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ce={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},de=re("Transform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}}),he=de,ue=de,fe=re("Sprite",{texture:D,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),pe=re("Camera",{projectionType:ae.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:le.ColorAndDepth}),me=re("Canvas",{designResolution:{x:x,y:v},pixelsPerUnit:100,scaleMode:ce.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),_e=re("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),ge=re("Parent",{entity:0}),ye=re("Children",{entities:[]}),we=re("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:L,enabled:!0}),xe=re("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),ve=K("Name",{value:""}),be=K("SceneOwner",{scene:"",persistent:!1});function Se(e){const t=oe(e);return t?N(t._default):null}const Me=re("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Pe=re("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Te=re("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ee=re("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ce={Static:0,Kinematic:1,Dynamic:2};let Ae=0;function Re(e,t){const s=++Ae;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function Ie(e){return{_type:"res",_resource:e}}function ke(e){return{_type:"res_mut",_resource:e}}class Fe{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class Be{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new Fe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const ze=Re({delta:0,elapsed:0,frameCount:0},"Time");function Ue(e,t,s){const n=[];for(const[e,i]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const s=$e(t[e]),o=$e(i);"null"!==s&&"undefined"!==s&&(s!==o&&null!=i&&n.push({field:e,expected:s,actual:o,value:i}))}return n}function $e(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function De(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}let Le=null;function Oe(e){Le=e}function We(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Le&&Le(e,t)}function He(e){let t=!1;for(const s of Object.keys(e)){const n=e[s];if(null!=n&&"object"==typeof n&&!Array.isArray(n)){if("r"in n&&"g"in n&&"b"in n&&"a"in n&&!("x"in n)){t=!0;break}}}if(!t)return e;const s={};for(const t of Object.keys(e)){const n=e[t];if(null==n||"object"!=typeof n||Array.isArray(n))s[t]=n;else{const e=n;s[t]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:n}}return s}let Xe=1;const je=new WeakMap;function Ye(e){let t=je.get(e);return void 0===t&&(t=Xe++,je.set(e,t)),t}const Ne=[];function Ve(e,t=[],s=[]){Ne.length=0;for(const t of e)Ne.push(Ye(t));Ne.sort((e,t)=>e-t);let n=Ne.join(",");if(t.length>0){Ne.length=0;for(const e of t)Ne.push(Ye(e));Ne.sort((e,t)=>e-t),n+="|+"+Ne.join(",")}if(s.length>0){Ne.length=0;for(const e of s)Ne.push(Ye(e));Ne.sort((e,t)=>e-t),n+="|-"+Ne.join(",")}return n}class qe{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw We(e,"spawn"),e}else e=++this.nextEntityId_;let t=0;if(this.module_&&this.cppRegistry_)try{t=this.module_.registry_getGeneration(this.cppRegistry_,e)}catch{}else t=++this.nextGeneration_;this.entities_.set(e,t),this.worldVersion_++;for(const t of this.spawnCallbacks_)try{t(e)}catch{}return e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch{}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){We(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t){this.tsStorage_.get(s)?.delete(e),this.componentAddedTicks_.get(s)?.delete(e),this.componentChangedTicks_.get(s)?.delete(e);let t=this.componentRemovedBuffer_.get(s);t||(t=[],this.componentRemovedBuffer_.set(s,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){We(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){We(t,`removeParent(entity=${e})`)}}insert(e,t,s){return se(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}set(e,t,s){if(se(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,He(s))}catch(s){We(s,`set(${t._name}, entity=${e})`)}this.recordChangedTick_(t,e)}else this.getStorage(t).set(e,s),this.recordChangedTick_(t,e)}get(e,t){return se(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return se(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(se(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return We(s,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");se(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_,n=s[`add${e}`],i=s[`get${e}`],o=s[`has${e}`],r=s[`remove${e}`];if("function"!=typeof n||"function"!=typeof i||"function"!=typeof o||"function"!=typeof r)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:n.bind(s),get:i.bind(s),has:o.bind(s),remove:r.bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Ue(t._name,t._default,n);if(e.length>0)throw new Error(De(t._name,e))}const i={...t._default,...n};let o=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(t._cppName);o=!s.has(e),s.add(e,He(i))}catch(s){We(s,`insertBuiltin(${t._name}, entity=${e})`)}return o&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let s=!1;for(const n of Object.keys(t)){const i=t[n];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){const t=e[n];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){s=!0;break}}}if(!s)return e;const n={};for(const s of Object.keys(e)){const i=e[s],o=t[s];if(null==i||"object"!=typeof i||Array.isArray(i)||null==o||"object"!=typeof o||Array.isArray(o))n[s]=i;else{const e=i,t=o;n[s]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:i}}return n}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(s){return We(s,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(s){return We(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){We(s,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++}}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 i=Ue(t._name,t._default,e);if(i.length>0)throw new Error(De(t._name,i));n=e}const i=t.create(n),o=this.getStorage(t),r=!o.has(e);o.set(e,i);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}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.recordRemovedTick_(t,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}getComponentTypes(e){const t=new Set;for(const[s,n]of this.builtinMethodCache_)try{n.has(e)&&t.add(s)}catch{}if(this.cppRegistry_)for(const[s,n]of ne)if(se(n)&&!t.has(s))try{this.getBuiltinMethods(n._cppName).has(e)&&t.add(s)}catch{}const s=this.entityComponents_.get(e);if(s){const e=G();for(const n of s)for(const[s,i]of e)if(i._id===n){t.add(s);break}}return Array.from(t)}getEntitiesWithComponents(e,t=[],s=[],n){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();const i=n??Ve(e,t,s),o=this.queryCache_.get(i);if(o&&o.version===this.worldVersion_)return o.result;let r=null,a=1/0;for(const t of e)if(!se(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<a&&(a=s,r=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=r?r.keys():this.entities_.keys();for(const n of c){let i=!0;for(const t of e)if(!this.has(n,t)){i=!1;break}if(i)for(const e of t)if(!this.has(n,e)){i=!1;break}if(i)for(const e of s)if(this.has(n,e)){i=!1;break}i&&l.push(n)}return this.queryCache_.set(i,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,s){const n=this.componentAddedTicks_.get(t._id);if(!n)return!1;const i=n.get(e);return void 0!==i&&i>s}isChangedSince(e,t,s){const n=this.componentChangedTicks_.get(t._id);if(!n)return!1;const i=n.get(e);return void 0!==i&&i>s}getRemovedEntitiesSince(e,t){const s=this.componentRemovedBuffer_.get(e._id);if(!s)return[];const n=[];for(const e of s)e.tick>t&&n.push(e.entity);return n}cleanRemovedBuffer(e){for(const[t,s]of this.componentRemovedBuffer_){let n=0;for(let t=0;t<s.length;t++)s[t].tick>=e&&(s[n++]=s[t]);s.length=n,0===n&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let s=this.componentAddedTicks_.get(e._id);s||(s=new Map,this.componentAddedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordChangedTick_(e,t){let s=this.componentChangedTicks_.get(e._id);s||(s=new Map,this.componentChangedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordRemovedTick_(e,t){let s=this.componentRemovedBuffer_.get(e._id);s||(s=[],this.componentRemovedBuffer_.set(e._id,s)),s.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function Ge(e){return{_type:"mut",_component:e}}function Ke(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Je(e){return{_filterType:"added",_component:e}}function Qe(e){return{_filterType:"changed",_component:e}}function Ze(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function et(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function tt(e){return Ke(e)||Ze(e)||et(e)?e._component:e}function st(e,t=[],s=[]){const n=[],i=[],o=[];return e.forEach((e,t)=>{Ke(e)&&n.push(t),Ze(e)?i.push({index:t,component:e._component}):et(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s,_addedFilters:i,_changedFilters:o,with:(...n)=>st(e,[...t,...n],s),without:(...n)=>st(e,t,[...s,...n])}}function nt(...e){return st(e)}class it{constructor(e,t,s=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=s,this.actualComponents_=t._components.map(tt),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=Ve(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:s}=this.descriptor_;if(0===t.length&&0===s.length)return!0;const n=this.lastRunTick_;for(const s of t)if(!this.world_.isAddedSince(e,s.component,n))return!1;for(const t of s)if(!this.world_.isChangedSince(e,t.component,n))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),n=t.length,i=e.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const d of s)if(!o||this.passesChangeFilters_(d)){if(null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}r[0]=d;for(let e=0;e<n;e++)r[e+1]=this.world_.get(d,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];c=d}yield r}}finally{if(this.world_.endIteration(),null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function ot(e){return{_type:"removed",_component:e}}class rt{constructor(e,t,s){this.world_=e,this.component_=t,this.lastRunTick_=s}*[Symbol.iterator](){yield*this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}isEmpty(){return 0===this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_).length}toArray(){return this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}}function at(){return{_type:"commands"}}class lt{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=se(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 ct{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new lt(this,null);return this.spawned_.push(e),e}entity(e){return new lt(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"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}function dt(e){return{_id:Symbol(`Event_${e}`),_name:e}}class ht{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(e){this.writeBuffer_.push(e)}getReadBuffer(){return this.readBuffer_}swap(){const e=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=e,this.writeBuffer_.length=0}}class ut{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new ht)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new ht,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function ft(e){return{_type:"event_writer",_event:e}}function pt(e){return{_type:"event_reader",_event:e}}class mt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class _t{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var gt;function yt(){return{_type:"get_world"}}!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(gt||(gt={}));let wt=0;function xt(e,t,s){const n=++wt;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function vt(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function bt(e){vt().push({schedule:gt.Update,system:e})}function St(e){vt().push({schedule:gt.Startup,system:e})}function Mt(e,t){vt().push({schedule:e,system:t})}class Pt{constructor(e,t,s){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=s??null}setTimingEnabled(e){this.timings_=e?new Map:null}getTimings(){return this.timings_}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);const s=this.timings_?performance.now():0;try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof ct&&t[e].flush()}finally{this.timings_&&this.timings_.set(e._name,performance.now()-s),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new it(this.world_,e,this.currentLastRunTick_);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new ct(this.world_,this.resources_);case"event_writer":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new mt(s)}case"event_reader":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new _t(s)}case"removed":{const t=e;return new rt(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class Tt{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 Et=Re(new Tt,"Input");class Ct{constructor(e){this.target_=e??null}build(e){const s=new Tt;e.insertResource(Et,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(gt.Last,xt([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const At=new Ct,Rt=Re({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var It;function kt(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"}(It||(It={}));let Ft=null,Bt=null,zt=1;const Ut=new Map;function $t(e){Ft=e,Bt=e.getResourceManager(),Vt()}function Dt(){0!==Ht&&Ft&&(Ft._free(Ht),Ht=0),Ut.clear(),zt=1,Wt=!1,jt.clear(),Yt=null,Bt=null,Ft=null}function Lt(){if(!Bt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Bt}const Ot={createShader:(e,t)=>Lt().createShader(e,t),releaseShader(e){e>0&&Lt().releaseShader(e)},create(e){const t=zt++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??It.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 Ut.set(t,s),t},get:e=>Ut.get(e),setUniform(e,t,s){const n=Ut.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0,Ft?.invalidateMaterialCache(e))},getUniform(e,t){const s=Ut.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ut.get(e);s&&(s.blendMode=t,Ft?.invalidateMaterialCache(e))},getBlendMode(e){const t=Ut.get(e);return t?.blendMode??It.Normal},setDepthTest(e,t){const s=Ut.get(e);s&&(s.depthTest=t,Ft?.invalidateMaterialCache(e))},getShader(e){const t=Ut.get(e);return t?.shader??0},release(e){Ut.delete(e),Ft?.invalidateMaterialCache(e)},isValid:e=>Ut.has(e),releaseAll(){Ut.clear(),Ft?.clearMaterialCache()},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??It.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ut.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=zt++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ut.set(s,n),s},toAssetData(e,t){const s=Ut.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=Ut.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Wt=!1,Ht=0;const Xt=16384,jt=new Map;let Yt=null;function Nt(e){const t=(0===Ht&&Ft&&(Ht=Ft._malloc(Xt)),Ht);if(0===t||!Ft)return{ptr:0,count:0};let s=0,n=0;const i=Ft.HEAPU8,o=Ft.HEAPU32,r=Ft.HEAPF32;for(const[a,l]of e){if(kt(l))continue;let e=jt.get(a);e||(Yt||(Yt=new TextEncoder),e=Yt.encode(a),jt.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(s+(4+d+4+16)>Xt){console.warn(`[ESEngine] Material uniform buffer full (${s}/${Xt} bytes), skipping remaining uniforms`);break}o[t+s>>2]=c,s+=4,i.set(e,t+s),s+=d;let h=0,u=[0,0,0,0];if("number"==typeof l)h=0,u[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)u[e]=l[e]}else"w"in l?(h=3,u=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,u=[l.x,l.y,l.z,0]):"y"in l&&(h=1,u=[l.x,l.y,0,0]);o[t+s>>2]=h,s+=4;for(let e=0;e<4;e++)r[t+s>>2]=u[e],s+=4;n++}return{ptr:t,count:n}}function Vt(){if(!Ft||Wt)return;Ft.materialDataProvider=(e,t,s,n,i)=>{const o=Ut.get(e);if(!o)return Ft.HEAPU32[t>>2]=0,Ft.HEAPU32[s>>2]=0,Ft.HEAPU32[n>>2]=0,void(Ft.HEAPU32[i>>2]=0);Ft.HEAPU32[t>>2]=o.shader,Ft.HEAPU32[s>>2]=o.blendMode;const{ptr:r,count:a}=Nt(o.uniforms);Ft.HEAPU32[n>>2]=r,Ft.HEAPU32[i>>2]=a},Wt=!0}const qt={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 Gt{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 i=this.pending_.get(e);if(i&&!i.aborted)return i.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),i=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,i),this.pending_.delete(e),i})(),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 Kt{constructor(e,t=""){this.cache_=new Gt,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&&(Ot.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ot.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const s=await l(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const i=this.resolveShaderPath(e,n.shader),o=await this.shaderLoader_.load(i);return{handle:Ot.createFromAsset(n,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 s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}function Jt(e){const t=new Set;for(const s of e.frames)s.texture&&t.add(s.texture);return Array.from(t)}function Qt(e,t,s){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>({texture:s.get(e.texture)??0}))}}const Zt=new Map;function es(e){Zt.set(e.name,e)}function ts(e){Zt.delete(e)}function ss(e){return Zt.get(e)}function ns(){Zt.clear()}const is=K("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function os(e,t){const s=e.getEntitiesWithComponents([is]);for(const n of s){const s=e.get(n,is);if(!s.enabled||!s.playing||!s.clip)continue;const i=Zt.get(s.clip);if(!i||0===i.frames.length)continue;const o=1/(i.fps*s.speed),r=0===s.frameTimer&&0===s.currentFrame;s.frameTimer+=t;let a=r;if(s.frameTimer>=o&&(s.frameTimer-=o,s.currentFrame++,s.currentFrame>=i.frames.length&&(s.loop&&i.loop?s.currentFrame=0:(s.currentFrame=i.frames.length-1,s.playing=!1)),a=!0),a&&e.has(n,fe)){const t=i.frames[s.currentFrame],o=e.get(n,fe);o.texture=t.texture,e.insert(n,fe,o)}a&&e.insert(n,is,s)}}class rs{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null,this.bgmVolume_=1,this.disposed_=!1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}static async preload(e){if(this.bufferCache_.has(e))return;const t=await this.backend_.loadBuffer(e);this.bufferCache_.set(e,t)}static async preloadAll(e){await Promise.all(e.map(e=>this.preload(e)))}static playSFX(e,t){const s={bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0},n=this.bufferCache_.get(e);if(!n){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const n=this.bufferCache_.get(e);n&&t.resolve(this.backend_.play(n,s))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(n,s)}static playBGM(e,t){const s=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const s=t?.volume??1,n=this.bgmVolume_;this.bgmVolume_=s,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,n):this.bgmHandle_&&this.bgmHandle_.stop();const i=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:i?0:s,loop:!0}),i&&this.fadeIn(this.bgmHandle_,i,s)},n=this.bufferCache_.get(e);n?s(n):this.preload(e).then(()=>{if(this.disposed_)return;const t=this.bufferCache_.get(e);t&&s(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else this.bgmHandle_.stop(),this.bgmHandle_=null}static setMasterVolume(e){this.mixer_&&(this.mixer_.master.volume=e)}static setMusicVolume(e){this.mixer_&&(this.mixer_.music.volume=e)}static setSFXVolume(e){this.mixer_&&(this.mixer_.sfx.volume=e)}static setUIVolume(e){this.mixer_&&(this.mixer_.ui.volume=e)}static muteBus(e,t){const s=this.mixer_?.getBus(e);s&&(s.muted=t)}static getBufferHandle(e){return this.bufferCache_.get(e)}static dispose(){this.disposed_=!0,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}static fadeIn(e,t,s){e.setVolume(0);const n=performance.now(),i=()=>{const o=(performance.now()-n)/1e3,r=Math.min(o/t,1);e.setVolume(r*s),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,s){const n=performance.now(),i=()=>{const o=(performance.now()-n)/1e3,r=Math.min(o/t,1);e.setVolume(s*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}static createDeferredHandle(){let e=null;return{id:-1,stop(){e?.stop()},pause(){e?.pause()},resume(){e?.resume()},setVolume(t){e?.setVolume(t)},setPan(t){e?.setPan(t)},setLoop(t){e?.setLoop(t)},setPlaybackRate(t){e?.setPlaybackRate(t)},get isPlaying(){return e?.isPlaying??!1},get currentTime(){return e?.currentTime??0},get duration(){return e?.duration??0},resolve(t){e=t}}}}rs.mixer_=null,rs.bufferCache_=new Map,rs.bgmHandle_=null,rs.bgmVolume_=1,rs.fadeAnimId_=0,rs.disposed_=!1;const as=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}],["AudioSource",{fields:[{field:"clip",type:"audio"}]}]]);function ls(e,t){as.set(e,t)}function cs(e){const t=as.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 ds(e){return as.get(e)?.fields??[]}function hs(e){return as.get(e)?.spine??null}const us=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function fs(e,t){us.set(e,t)}function ps(e){return us.get(e)}function ms(e,t){const s=us.get(e.type);if(!s)return;const n=e.data;for(const i of s){const s=n[i];if("number"==typeof s&&0!==s){const o=t.get(s);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${s} which does not exist`),n[i]=void 0!==o?o:0}}}function _s(e,t){const s=new Map;for(const n of t.entities){if(!1===n.visible)continue;const t=e.spawn();s.set(n.id,t),e.insert(t,ve,{value:n.name})}for(const n of t.entities){if(!1===n.visible)continue;const t=s.get(n.id);for(const i of n.components)ms(i,s),xs(e,t,i,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),i=s.get(n.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return s}function gs(e,t){return _s(e,t)}async function ys(e,t,s){const n=s?.assetServer,i=s?.assetBaseUrl??n?.baseUrl,o=new Map;n&&await async function(e,t,s,n,i){const o=new Map;for(const e of ws.keys())o.set(e,new Set);const r=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=as.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}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...ws.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,s,n);l.set(e,r)}),d=r.map(async e=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)});if(await Promise.all([...c,...d]),i){for(const e of n.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=as.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const n=s[e.field];if("string"!=typeof n||!n)continue;const i=t.get(n);void 0!==i&&(s[e.field]=i)}}}(t,n,i,o,s?.collectAssets);const r=_s(e,t);if(n&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&n.setTextureMetadataByPath(t,s.sliceBorder)}return r}const ws=new Map([["texture",{async load(e,t,s,n){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),n.set(e,o)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(o),i}}],["material",{async load(e,t,s){const n=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,s);n.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),n.set(e,0)}});return await Promise.all(i),n}}],["font",{async load(e,t,s){const n=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,s);n.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),n.set(e,0)}});return await Promise.all(i),n}}],["anim-clip",{async load(e,t,s,n){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=Jt(i),r=new Map,a=o.map(async e=>{try{const i=s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),n.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);es(Qt(e,i,r))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(i),new Map}}],["audio",{async load(e,t,s){const n=[...e].map(e=>s?`${s}/${e}`:`/${e}`);return await rs.preloadAll(n).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}]]);function xs(e,t,s,n){if("LocalTransform"!==s.type&&"WorldTransform"!==s.type||(s.type="Transform"),"UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===s.type){const e=s.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=oe(s.type);if(i)e.insert(t,i,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function vs(e,t){const s=e.getEntitiesWithComponents([pe]);for(const n of s){const s=e.get(n,pe);s&&(s.aspectRatio=t,e.insert(n,pe,s))}}function bs(e,t){const s=e.getEntitiesWithComponents([ve]);for(const n of s){const s=e.get(n,ve);if(s&&s.value===t)return n}return null}const Ss=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],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},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0}],Ms={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",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",bmfont:"application/json",fnt:"text/plain"},Ps=new Map,Ts=new Set;for(const e of Ss)for(const t of e.extensions)Ps.set(t,e),Ts.add(t);function Es(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function Cs(e){return Ps.get(Es(e))}function As(e){return Cs(e)?.editorType??"unknown"}function Rs(e){return Cs(e)?.addressableType??null}function Is(e){for(const t of Ss)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function ks(e){return Ts.has(e.toLowerCase())}function Fs(){return Ts}function Bs(e){return"string"==typeof e&&(!!e.includes("/")&&ks(Es(e)))}function zs(){const e=[];for(const t of Ss)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function Us(){return zs().map(e=>({type:"suffix",value:e}))}function $s(e){return Ms[e.toLowerCase()]}function Ds(e){const t=Cs(e);return t?.wechatPackInclude??!1}function Ls(e){const t=Cs(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const s=e.lastIndexOf(".");return s>=0?e.substring(0,s)+".json":e}class Os{constructor(e){this.textureCache_=new Gt,this.shaderCache_=new Gt,this.jsonCache_=new Gt,this.textCache_=new Gt,this.binaryCache_=new Gt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Gt,this.prefabCache_=new Gt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=h(F.textCanvasSize,F.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Kt(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),i=this.textureCache_.get(n);if(!i)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),Ot.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const i=this.resolveUrl(t,s),o=await this.fetchText(i);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=r?`${r}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),d="binary"===Cs(e)?.contentType,h=d?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(h,o,d);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),i=l.find(e=>e.name===s);if(i){const s=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,i.info.width,i.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}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=Cs(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 i=s?`${s}/${n}`:n;return this.loadFntFile(i)}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],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${n}`:n,r=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,r.handle,r.width,r.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,async()=>{const e=await this.fetchJson(s);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const s of e.entities){for(const e of s.components){if(!e.data)continue;for(const s of cs(e.type)){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}const s=hs(e.type);if(s)for(const n of[s.skeletonField,s.atlasField]){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}}if(s.nestedPrefab?.prefabPath){const e=t(s.nestedPrefab.prefabPath);e&&(s.nestedPrefab.prefabPath=e)}}}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const 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 ys(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 i=n.metadata?.atlas;i&&s.push(this.loadSpine(n.path,i).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return this.loadImageFromSrc(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){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=e})}createTextureFromImage(e,t){const{width:s,height:n}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,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,i){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const r=this.module_.GL,a=r.getNewId(r.textures);r.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 i=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(o);const r=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=r.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.getEmbedded(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:i}=this.parseEsShader(t);if(!n||!i)throw new Error(`Invalid shader format: ${e}`);return Ot.createShader(n,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const n=await l(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:o}=this.parseEsShader(n);if(!i||!o)throw new Error(`Invalid shader format: ${e}`);return Ot.createShader(i,o)}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://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(Ls(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await l(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await r(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.getEmbedded(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await r(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.getEmbedded(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 r(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 i="";for(const e of n){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const 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 Ws=Re(null,"Assets");class Hs{build(e){const t=e.wasmModule;t?e.insertResource(Ws,new Os(t)):console.warn("AssetPlugin: No WASM module available")}}const Xs=new Hs;class js{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 Ys(e,t){const s=e.getResource(Ws);s&&s.registerEmbeddedAssets(t)}async function Ns(e,t,s){const{entities:n,rootId:i}=await qs(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}))},r=await ys(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=r.get(i);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:r}}const Vs=10;async function qs(e,t,s,n,i,o=0){if(o>Vs)throw new Error(`Prefab nesting depth exceeded ${Vs}. Check for deep or circular nesting in: ${e.name}`);const r=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,a++)}const l=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(i?.has(n.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${n.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await qs(e,n.nestedPrefab.overrides,s,a,i,o+1);r.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?r.get(n.parent)??null:null),l.push(...t.entities);continue}const c=r.get(n.prefabEntityId),d=n.prefabEntityId===e.rootEntityId,h={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:d?null:null!==n.parent?r.get(n.parent)??null:null,children:n.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};Gs(h.components,r),Ks(h,t),l.push(h)}const c=r.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function Gs(e,t){for(const s of e){const e=ps(s.type);if(e)for(const n of e){const e=s.data[n];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(s.data[n]=i)}}}}function Ks(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 Js{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,i=await this.assetServer_.loadPrefab(n,t?.baseUrl);return Ns(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Qs=Re(null,"Prefabs");class Zs{constructor(){this.name="PrefabsPlugin",this.dependencies=[Ws]}build(e){const t=e.getResource(Ws);e.insertResource(Qs,new Js(e.world,t))}}const en=new Zs;let tn=null,sn=0,nn=0,on=0;const rn=new Float32Array(256);function an(e){tn=e,sn=tn._malloc(64),nn=tn._malloc(64),on=tn._malloc(1024)}function ln(){tn&&(sn&&(tn._free(sn),sn=0),nn&&(tn._free(nn),nn=0),on&&(tn._free(on),on=0)),tn=null}function cn(){if(!tn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return tn}const dn={r:1,g:1,b:1,a:1},hn={begin(e){const t=cn();try{t.HEAPF32.set(e,sn/4),t.draw_begin(sn)}catch(e){We(e,"Draw.begin")}},end(){try{cn().draw_end()}catch(e){We(e,"Draw.end")}},line(e,t,s,n=1){try{cn().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){We(e,"Draw.line")}},rect(e,t,s,n=!0){try{cn().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){We(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{cn().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){We(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,i=32){try{cn().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){We(e,"Draw.circle")}},circleOutline(e,t,s,n=1,i=32){try{cn().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){We(e,"Draw.circleOutline")}},texture(e,t,s,n=dn){try{cn().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){We(e,"Draw.texture")}},textureRotated(e,t,s,n,i=dn){try{cn().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,i.r,i.g,i.b,i.a)}catch(e){We(e,"Draw.textureRotated")}},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,s){try{const n=cn();n.HEAPF32.set(s,nn/4),n.draw_mesh(e,t,nn)}catch(s){We(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=cn(),i=Ot.get(t);if(!i)return;if(hn.setBlendMode(i.blendMode),hn.setDepthTest(i.depthTest),0===i.uniforms.size)return void hn.drawMesh(e,i.shader,s);let o;if(n.HEAPF32.set(s,nn/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,s]of i.uniforms){const n=pn(t);if(!(n<0)){if(kt(s))rn[o++]=10,rn[o++]=n,rn[o++]=s.slot??e++,rn[o++]=s.textureId;else if("number"==typeof s)rn[o++]=1,rn[o++]=n,rn[o++]=s;else if(Array.isArray(s)){rn[o++]=s.length,rn[o++]=n;for(let e=0;e<s.length;e++)rn[o++]=s[e]}else"w"in s?(rn[o++]=4,rn[o++]=n,rn[o++]=s.x,rn[o++]=s.y,rn[o++]=s.z,rn[o++]=s.w):"z"in s?(rn[o++]=3,rn[o++]=n,rn[o++]=s.x,rn[o++]=s.y,rn[o++]=s.z):(rn[o++]=2,rn[o++]=n,rn[o++]=s.x,rn[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<o)&&(i.cachedBuffer_=new Float32Array(o)),i.cachedBuffer_.set(rn.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void n.draw_mesh(e,i.shader,nn);n.HEAPF32.set(i.cachedBuffer_.subarray(0,o),on/4),n.draw_meshWithUniforms(e,i.shader,nn,on,o)}catch(s){We(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},un={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},fn=new Set;function pn(e){const t=un[e];return void 0!==t?t:(fn.has(e)||(fn.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(un).join(", ")}`)),-1)}const mn=new Map;function _n(e,t,s){mn.set(e,{fn:t,scene:s??""})}function gn(e){mn.delete(e)}function yn(){mn.clear()}var wn;!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"}(wn||(wn={}));let xn=null,vn=0,bn=0,Sn=0;function Mn(e){xn=e,vn=xn._malloc(262144),bn=xn._malloc(65536),Sn=xn._malloc(256)}function Pn(){xn&&(vn&&xn._free(vn),bn&&xn._free(bn),Sn&&xn._free(Sn),vn=0,bn=0,Sn=0),xn=null}function Tn(){if(!xn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return xn}const En={create(e){const t=Tn(),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,vn/4);const i=e.layout.length,o=new Int32Array(i);for(let t=0;t<i;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Sn,i).set(o),t.geometry_init(s,vn,n,Sn,i,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,bn,n).set(e.indices),t.geometry_setIndices16(s,bn,n)}else{new Uint32Array(t.HEAPU8.buffer,bn,n).set(e.indices),t.geometry_setIndices32(s,bn,n)}}return s},updateVertices(e,t,s=0){const n=Tn(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);n.HEAPF32.set(t,vn/4),n.geometry_updateVertices(e,vn,i,s)},release(e){e>0&&Tn().geometry_release(e)},isValid:e=>!(!xn||e<=0)&&xn.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return En.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:wn.Float2},{name:"a_texCoord",type:wn.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 i=n/t*Math.PI*2,o=Math.cos(i)*e,r=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;s.push(o,r,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return En.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:wn.Float2},{name:"a_texCoord",type:wn.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,i=-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),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(n-t),a=(r.y-s)/(i-s);o.push(r.x,r.y,e,a)}const r=[];for(let t=1;t<e.length-1;t++)r.push(0,t,t+1);return En.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:wn.Float2},{name:"a_texCoord",type:wn.Float2}],indices:new Uint16Array(r)})}};let Cn=null;function An(e){Cn=e}function Rn(){Cn&&kn.isInitialized()&&kn.shutdown(),Cn=null}function In(){if(!Cn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Cn}const kn={init(e,t){try{return In().postprocess_init(e,t)}catch(s){return We(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{In().postprocess_shutdown()}catch(e){We(e,"PostProcess.shutdown")}},resize(e,t){try{In().postprocess_resize(e,t)}catch(s){We(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return In().postprocess_addPass(e,t)}catch(t){return We(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{In().postprocess_removePass(e)}catch(t){We(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{In().postprocess_setPassEnabled(e,t)}catch(t){We(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return In().postprocess_isPassEnabled(e)}catch(t){return We(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{In().postprocess_setUniformFloat(e,t,s)}catch(s){We(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{In().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){We(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{In().postprocess_begin()}catch(e){We(e,"PostProcess.begin")}},end(){try{In().postprocess_end()}catch(e){We(e,"PostProcess.end")}},getPassCount(){try{return In().postprocess_getPassCount()}catch(e){return We(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Cn)return!1;try{return Cn.postprocess_isInitialized()}catch(e){return We(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{In().postprocess_setBypass(e)}catch(e){We(e,"PostProcess.setBypass")}},isBypassed(){if(!Cn)return!0;try{return Cn.postprocess_isBypassed()}catch(e){return We(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Ot.createShader(Fn,"#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:()=>Ot.createShader(Fn,"#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:()=>Ot.createShader(Fn,"#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:()=>Ot.createShader(Fn,"#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")},Fn="#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 Bn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Bn||(Bn={}));let zn=null,Un=0;function $n(e){zn=e,Un=zn._malloc(64)}function Dn(){zn&&Un&&(zn._free(Un),Un=0),zn=null}const Ln={init(e,t){zn?.renderer_init(e,t)},resize(e,t){zn?.renderer_resize(e,t)},begin(e,t){if(zn&&Un)try{zn.HEAPF32.set(e,Un/4),zn.renderer_begin(Un,t??0)}catch(e){We(e,"Renderer.begin")}},flush(){try{zn?.renderer_flush()}catch(e){We(e,"Renderer.flush")}},end(){try{zn?.renderer_end()}catch(e){We(e,"Renderer.end")}},submitSprites(e){if(zn)try{zn.renderer_submitSprites(e._cpp)}catch(e){We(e,"Renderer.submitSprites")}},submitBitmapText(e){if(zn)try{zn.renderer_submitBitmapText(e._cpp)}catch(e){We(e,"Renderer.submitBitmapText")}},submitSpine(e){if(zn)try{zn.renderer_submitSpine?.(e._cpp)}catch(e){We(e,"Renderer.submitSpine")}},setStage(e){zn?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>zn?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){zn?.renderer_releaseTarget(e)},getTargetTexture:e=>zn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>zn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){zn?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){zn?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,i){zn?.renderer_setScissor(e,t,s,n,i)},clearBuffers(e){zn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>zn?zn.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>zn?{drawCalls:zn.renderer_getDrawCalls(),triangles:zn.renderer_getTriangles(),sprites:zn.renderer_getSprites(),text:zn.renderer_getText(),spine:zn.renderer_getSpine?.()??0,meshes:zn.renderer_getMeshes(),culled:zn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let On=null;function Wn(e){On=e}function Hn(){On=null}const Xn={enable(){On?.gl_enableErrorCheck(!0)},disable(){On?.gl_enableErrorCheck(!1)},check:e=>On?.gl_checkErrors(e)??0,diagnose(){On?.renderer_diagnose()}};class jn{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:i,elapsed:o}=e;n===this.lastWidth_&&i===this.lastHeight_||(Ln.resize(n,i),kn.isInitialized()&&kn.getPassCount()>0&&kn.resize(n,i),this.lastWidth_=n,this.lastHeight_=i),Ln.setViewport(0,0,n,i),Ln.clearBuffers(3),Ln.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,i),Ln.submitSprites(t),Ln.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ln.submitSpine(t),Ln.flush(),this.executeDrawCallbacks(s,o),Ln.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:i,elapsed:o}=e;Ln.setViewport(n.x,n.y,n.w,n.h),Ln.setScissor(n.x,n.y,n.w,n.h,!0),Ln.clearBuffers(i),Ln.setScissor(0,0,0,0,!1),Ln.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Ln.submitSprites(t),Ln.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ln.submitSpine(t),Ln.flush(),this.executeDrawCallbacks(s,o),Ln.end()}executeDrawCallbacks(e,t){const s=mn;if(s.size>0){hn.begin(e);const n=[];for(const[e,i]of s.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}hn.end();for(const e of n)gn(e)}}}const Yn="__scene_transition_overlay__";class Nn{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class Vn{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,be,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),_n(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=kn.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){kn.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,be)){const s=this.app_.world.get(e,be);s.persistent=t,this.app_.world.insert(e,be,s)}}}class qn{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??F.sceneTransitionDuration,i=t.color??{...F.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:i,targetScene:e,options:t,resolve:s},_n(Yn,()=>{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;hn.setLayer(9999),hn.setDepth(9999),hn.rect({x:0,y:0},{x:2e4,y:2e4},{r:i.r,g:i.g,b:i.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()=>{try{s&&s!==e&&await this.unload(s,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,gn(Yn),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,gn(Yn),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new Nn(t);this.scenes_.set(e,s);const n=new Vn(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Ws)?this.app_.getResource(Ws):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(s,e,t,i),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new Nn(t);this.scenes_.set(e,s);const n=new Vn(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Ws)?this.app_.getResource(Ws):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(s,e,t,i),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const i=t?.keepPersistent??!0;for(const e of s.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,be)){if(this.app_.world.get(e,be).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())gn(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{kn.removePass(e)}catch{}s.postProcessPasses.length=0,this.releaseSceneAssets_(s),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)}async loadSceneData_(e,t,s,n){if(n){const s={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:s};this.app_.hasResource(Ws)&&(i.assetServer=this.app_.getResource(Ws));const o=await ys(this.app_.world,n,i);e.loadedAssets=s;for(const s of o.values())e.entities.add(s),this.app_.world.insert(s,be,{scene:t,persistent:!1})}if(s.systems)for(const{schedule:e,system:n}of s.systems){const s=Kn(this.app_,t,n);this.app_.addSystemToSchedule(e,s)}const i=this.contexts_.get(t);s.setup&&await s.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const s=this.app_.hasResource(Ws)?this.app_.getResource(Ws):null;if(s){for(const e of t.textureUrls)s.releaseTexture(e);for(const e of t.fontPaths)s.releaseFont(e);for(const e of t.spineKeys)s.releaseSpine(e)}for(const e of t.materialHandles)Ot.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n={};let i=!1;if(s.has(e,fe)){const t=s.get(e,fe);n.sprite=t.color.a,t.color.a=0,s.insert(e,fe,t),i=!0}if(s.has(e,xe)){const t=s.get(e,xe);n.spine=t.color.a,t.color.a=0,s.insert(e,xe,t),i=!0}if(s.has(e,we)){const t=s.get(e,we);n.bitmapText=t.color.a,t.color.a=0,s.insert(e,we,t),i=!0}i&&t.savedAlphas.set(e,n)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n=t.savedAlphas.get(e);if(n){if(void 0!==n.sprite&&s.has(e,fe)){const t=s.get(e,fe);t.color.a=n.sprite,s.insert(e,fe,t)}if(void 0!==n.spine&&s.has(e,xe)){const t=s.get(e,xe);t.color.a=n.spine,s.insert(e,xe,t)}if(void 0!==n.bitmapText&&s.has(e,we)){const t=s.get(e,we);t.color.a=n.bitmapText,s.insert(e,we,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{kn.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 Gn=Re(null,"SceneManager");function Kn(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Gn).getSceneStatus(t)&&s._fn(...n)}}}const Jn=xt([ke(Gn),Ie(ze)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Qn={name:"SceneManager",build(e){const t=new qn(e);e.insertResource(Gn,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Gn),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(gt.Startup,s),e.addSystemToSchedule(gt.Last,Jn)}};class Zn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new ut,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=u(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(gt.Last);else{this.runSchedule(gt.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(gt.FixedPreUpdate),this.runSchedule(gt.FixedUpdate),this.runSchedule(gt.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(gt.PreUpdate),this.runSchedule(gt.Update),this.runSchedule(gt.PostUpdate),this.runSchedule(gt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new qe,this.resources_=new Be;for(const e of Object.values(gt))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Zn}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(gt.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(gt.Startup,e)}removeSystem(e){let t=!1;for(const[s,n]of this.systems_){const i=n.filter(t=>t.system._id!==e);i.length!==n.length&&(this.systems_.set(s,i),this.sortedSystemsCache_.delete(s),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return Oe(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}enableStats(){return this.statsEnabled_=!0,this.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}getEntityCount(){return this.world_.entityCount()}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(Gn).register(e),this}setInitialScene(e){return this.getResource(Gn).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new Pt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(ze)||this.resources_.insert(ze,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(gt.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(gt.Last);else{this.runSchedule(gt.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(gt.FixedPreUpdate),this.runSchedule(gt.FixedUpdate),this.runSchedule(gt.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(gt.PreUpdate),this.runSchedule(gt.Update),this.runSchedule(gt.PostUpdate),this.runSchedule(gt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new Pt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(ze,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(gt.Startup),this.lastTime_=u(),this.mainLoop())}quit(){this.running_=!1,yn();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[Hn,Dn,Rn,Pn,Dt,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}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let 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 i=t.get(n);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,i=new Set,o=r=>{if(n.has(r))return;if(i.has(r)){const t=e[r].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(r);const a=e[r];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}i.delete(r),n.add(r),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));const n=this.phaseTimings_?performance.now():0;for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}this.phaseTimings_&&this.phaseTimings_.set(gt[e],performance.now()-n)}updateTime(e){const t=this.resources_.get(ze);t.delta=e,t.elapsed+=e,t.frameCount++}}function ei(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const ti=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function si(e,t,s,n,i){const o=e*t/s,r=e;switch(n){case ce.FixedWidth:return o;case ce.FixedHeight:return r;case ce.Expand:return Math.max(o,r);case ce.Shrink:return Math.min(o,r);case ce.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const ni=[];function ii(e){if(e<ni.length)return ni[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return ni.push(t),t}function oi(e,t,s,n,i,o){if(0===s||0===n)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,be);return!t||""===t.scene||o.has(t.scene)}):r;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 i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*s/(i.viewportH*n);let a,d=0,h=0;if(i.projectionType===ae.Orthographic){if(h=i.orthoSize,l){h=si(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}d=h*r,a=ai(-d,d,-h,h,-i.farPlane,i.farPlane)}else a=ci(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const u=hi(o.position.x,o.position.y,o.position.z),f=ii(c.length);f.entity=e,f.viewProjection.set(fi(a,u)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=d,f.halfH=h,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const ri=new Float32Array(16);function ai(e,t,s,n,i,o){const r=ri;r.fill(0);const a=t-e,l=n-s,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(n+s)/l,r[14]=-(o+i)/c,r[15]=1,r}const li=new Float32Array(16);function ci(e,t,s,n){const i=li;i.fill(0);const o=1/Math.tan(e/2),r=s-n;return i[0]=o/t,i[5]=o,i[10]=(n+s)/r,i[11]=-1,i[14]=2*n*s/r,i}const di=new Float32Array(16);function hi(e,t,s){const n=di;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 ui=new Float32Array(16);function fi(e,t){const s=ui;for(let n=0;n<4;n++)for(let i=0;i<4;i++)s[4*i+n]=e[0+n]*t[4*i+0]+e[4+n]*t[4*i+1]+e[8+n]*t[4*i+2]+e[12+n]*t[4*i+3];return s}const pi={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function mi(e,t,s,n,i,o,r={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,d=o.left+t.x*a,h=o.bottom+e.y*l,u=o.bottom+t.y*l;let f,p,m,_;e.x===t.x?(f=c+s.x-i.x*r.x,m=f+i.x):(f=c+s.x,m=d+n.x),e.y===t.y?(p=h+s.y-i.y*r.y,_=p+i.y):(p=h+s.y,_=u+n.y);const g=Math.max(0,m-f),y=Math.max(0,_-p);return{originX:f+r.x*g,originY:p+r.y*y,width:g,height:y,rect:{left:f,bottom:p,right:m,top:_}}}const _i=re("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});let gi=null,yi=null;function wi(e,t){e.has(t,fe)||e.insert(t,fe,{texture:D,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0})}function xi(e,t){switch(e){case pi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case pi.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case pi.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function vi(e,t){switch(e){case pi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case pi.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case pi.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1-t}};default:return{anchorMin:{x:t,y:0},anchorMax:{x:t,y:1}}}}function bi(e,t,s,n){switch(e){case pi.BottomToTop:case pi.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}}function Si(e,t,s,n){if(!e.has(t,_i))return;const i=e.get(t,_i),o=xi(s,n);i.anchorMin=o.anchorMin,i.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(i.size={...i.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,_i,i)}function Mi(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Pi(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Ti(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),i=[];for(const t of n){if(!t){i.push("");continue}let n="";for(let o=0;o<t.length;o++){const r=t[o],a=n+r;if(e.measureText(a).width>s&&n){if(Pi(r.charCodeAt(0))&&n.length>0&&Pi(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!Pi(n.charCodeAt(t))){e=t;break}e>=0?(i.push(n.substring(0,e+1)),n=n.substring(e+1)+r):(i.push(n),n=r)}else i.push(n),n=r}else n=a}n&&i.push(n)}return i.length>0?i:[""]}function Ei(e){let t=1;for(;t<e;)t*=2;return t}function Ci(e,t){let s=0,n=t;for(;e.has(n,ge);){const t=e.get(n,ge).entity;if(!e.valid(t))break;s++,n=t}return s}function Ai(e,t){if(gi&&yi){const e=gi.getUIRectComputedWidth(yi,t);if(e>0)return e}return e.size.x}function Ri(e,t){if(gi&&yi){const e=gi.getUIRectComputedHeight(yi,t);if(e>0)return e}return e.size.y}function Ii(e,t,s,n,i,o){if(!e.has(t,fe))return;const r=e.get(t,fe);let a,l;switch(s){case pi.BottomToTop:case pi.TopToBottom:a=i,l=o*n;break;default:a=i*n,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,fe,r))}function ki(e,t,s){let n=t;for(;e.has(n,ge);){const t=e.get(n,ge).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function Fi(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function Bi(e,t,s,n,i){if(!e.has(t,_i))return;const o=e.get(t,_i),r=mi(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s,o.pivot),a=r.rect.right-r.rect.left,l=r.rect.top-r.rect.bottom;if(e.has(t,fe)){const s=e.get(t,fe);s.size.x===a&&s.size.y===l||(s.size.x=a,s.size.y=l,e.insert(t,fe,s))}if(e.has(t,de)){const s=e.get(t,de);s.position.x=r.originX-n,s.position.y=r.originY-i,e.insert(t,de,s)}}function zi(e){const t=Object.keys(e),s=t.map(t=>e[t]);return{take(e){const n={};for(let i=0;i<t.length;i++)n[t[i]]=s[i](e);return n},changed(e,n){for(let i=0;i<t.length;i++)if(e[t[i]]!==s[i](n))return!0;return!1},update(e,n){for(let i=0;i<t.length;i++)e[t[i]]=s[i](n)}}}const Ui=.1,$i=30,Di={r:.3,g:.5,b:.8,a:1},Li={Left:0,Center:1,Right:2},Oi={Top:0,Middle:1,Bottom:2},Wi={Visible:0,Clip:1,Ellipsis:2},Hi=K("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Li.Left,verticalAlign:Oi.Top,wordWrap:!0,overflow:Wi.Visible,lineHeight:1.2});class Xi{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(F.textCanvasSize,F.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,Ei(this.frameMaxW_)),e.height=Math.max(e.height,Ei(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Ei(this.frameMaxW_),e.height=Ei(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,o=i?t.size.x:0,r=i?t.size.y:0,a=e.wordWrap&&i;let l=Ti(s,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),d=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),u=Math.ceil(l.length*c),f=i?Math.ceil(o):h+2*d,p=i?Math.ceil(r):u+2*d;if(i&&e.overflow===Wi.Ellipsis&&u>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(n.width<f||n.height<p)&&(n.width=Math.max(n.width,Ei(f)),n.height=Math.max(n.height,Ei(p)));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;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${m}, ${_}, ${g}, ${y})`,i&&e.overflow===Wi.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const w=l.length*c;let x;if(i){switch(e.verticalAlign){case Oi.Top:x=d;break;case Oi.Middle:x=d+(p-2*d-w)/2;break;case Oi.Bottom:x=p-w-d;break;default:x=d}x<0&&(x=0)}else x=d;let v=x;for(const t of l){let n;switch(e.align){case Li.Left:n=d;break;case Li.Center:n=f/2;break;case Li.Right:n=f-d;break;default:n=d}s.fillText(t,n,v),v+=c}i&&e.overflow===Wi.Clip&&s.restore();const b=s.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),M=this.module.getResourceManager(),P=this.module._malloc(S.length);this.module.HEAPU8.set(S,P);const T=M.createTexture(f,p,P,S.length,1,!0);return this.module._free(P),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let 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 i=this.renderText(t,s);return this.cache.set(e,i),i}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}measureWidth(e){let t=0;for(const s of e)t=Math.max(t,this.ctx.measureText(s).width);return t}mapAlign(e){switch(e){case Li.Left:return"left";case Li.Center:return"center";case Li.Right:return"right"}}}const ji=zi({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?Ai(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Ri(e.uiRect,e.entity):0});class Yi{build(e){ie("Text",Hi);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Xi(t),n=e.world,i=new Map;e.addSystemToSchedule(gt.PreUpdate,xt([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Hi));for(const e of i.keys())if(!n.valid(e)||!n.has(e,Hi)){if(n.valid(e)&&n.has(e,fe)){const t=n.get(e,fe);n.insert(e,fe,{texture:D,color:{r:t.color.r,g:t.color.g,b:t.color.b,a:t.color.a},size:{x:t.size.x,y:t.size.y},uvOffset:{x:t.uvOffset.x,y:t.uvOffset.y},uvScale:{x:t.uvScale.x,y:t.uvScale.y},layer:t.layer,flipX:t.flipX,flipY:t.flipY,material:t.material,enabled:t.enabled})}i.delete(e)}const e=n.getEntitiesWithComponents([Hi]);for(const t of e){const e=n.get(t,Hi),o=n.has(t,_i)?n.get(t,_i):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!ji.changed(a,r)){if(n.has(t,fe)&&n.get(t,fe).texture!==D)continue}wi(n,t);const l=o?{size:{x:Ai(o,t),y:Ri(o,t)}}:null,c=s.renderForEntity(t,e,l),d=n.get(t,fe);n.insert(t,fe,{texture:c.textureHandle,color:{r:d.color.r,g:d.color.g,b:d.color.b,a:d.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:d.layer,flipX:d.flipX,flipY:d.flipY,material:d.material,enabled:d.enabled}),i.set(t,ji.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Ni=new Yi,Vi=0,qi=1,Gi=re("UIMask",{enabled:!0,mode:Vi});function Ki(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),i=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,i-s),h:Math.max(0,o-n)}}function Ji(e,t){const s=t??new Float32Array(16),n=e[0],i=e[1],o=e[2],r=e[3],a=e[4],l=e[5],c=e[6],d=e[7],h=e[8],u=e[9],f=e[10],p=e[11],m=e[12],_=e[13],g=e[14],y=e[15],w=n*l-i*a,x=n*c-o*a,v=n*d-r*a,b=i*c-o*l,S=i*d-r*l,M=o*d-r*c,P=h*_-u*m,T=h*g-f*m,E=h*y-p*m,C=u*g-f*_,A=u*y-p*_,R=f*y-p*g;let I=w*R-x*A+v*C+b*E-S*T+M*P;return 0===I||(I=1/I,s[0]=(l*R-c*A+d*C)*I,s[1]=(o*A-i*R-r*C)*I,s[2]=(_*M-g*S+y*b)*I,s[3]=(f*S-u*M-p*b)*I,s[4]=(c*E-a*R-d*T)*I,s[5]=(n*R-o*E+r*T)*I,s[6]=(g*v-m*M-y*x)*I,s[7]=(h*M-f*v+p*x)*I,s[8]=(a*A-l*E+d*P)*I,s[9]=(i*E-n*A-r*P)*I,s[10]=(m*S-_*v+y*w)*I,s[11]=(u*v-h*S-p*w)*I,s[12]=(l*T-a*C-c*P)*I,s[13]=(n*C-i*T+o*P)*I,s[14]=(_*x-m*b-g*w)*I,s[15]=(h*b-u*x+f*w)*I),s}function Qi(e,t,s,n,i,o,r){const a=(e-n)/o*2-1,l=(t-i)/r*2-1,c=s[0]*a+s[4]*l+s[12],d=s[1]*a+s[5]*l+s[13],h=s[3]*a+s[7]*l+s[15];return{x:c/h,y:d/h}}function Zi(e,t,s,n,i,o,r,a){return e>=s-i*r&&e<=s+i*(1-r)&&t>=n-o*a&&t<=n+o*(1-a)}function eo(e,t){return 2*Math.atan2(e,t)}function to(e,t,s,n,i,o,r){const a=s[0]*e+s[4]*t+s[12],l=s[1]*e+s[5]*t+s[13],c=s[3]*e+s[7]*t+s[15];return[n+(.5*(a/c)+.5)*o,i+(.5*(l/c)+.5)*r]}function so(e,t,s,n,i,o,r,a,l,c){const d=eo(l,c),h=Math.sin(-d),u=Math.cos(-d),f=e-s,p=t-n,m=f*u-p*h+s,_=f*h+p*u+n;return m>=s-i*r&&m<=s+i*(1-r)&&_>=n-o*a&&_<=n+o*(1-a)}function no(e,t,s,n,i,o,r){if(!e.has(t,_i)||!e.has(t,de))return null;const a=e.get(t,_i),l=e.get(t,de),c=Ai(a,t)*l.worldScale.x,d=Ri(a,t)*l.worldScale.y,h=l.worldPosition.x,u=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,m=-c*f,_=c*(1-f),g=-d*p,y=d*(1-p),w=eo(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[h+m*x-g*v,u+m*v+g*x],[h+_*x-g*v,u+_*v+g*x],[h+_*x-y*v,u+_*v+y*x],[h+m*x-y*v,u+m*v+y*x]];let S=1/0,M=1/0,P=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=to(e,t,s,n,i,o,r);S=Math.min(S,a),M=Math.min(M,l),P=Math.max(P,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(M),w:Math.round(P-S),h:Math.round(T-M)}}function io(e,t){return(s,n,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Gi]);if(0===l.length)return;const c=[],d=[],h=new Set,u=new Set;for(const e of l){const s=t.get(e,Gi);s.enabled&&(h.add(e),s.mode===qi?(d.push(e),u.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,i,o,r,a,l,c){const d=[];for(const e of n){let s=!0;ki(t,e,e=>{if(i.has(e)){if(t.get(e,Gi).mode===Vi)return s=!1,!0}return!1}),s&&d.push(e)}function h(n,d){const u=e.getChildEntities(s,n);for(const s of u){let n=d;if(i.has(s)){if(t.get(s,Gi).mode===Vi){const e=no(t,s,o,r,a,l,c);e&&(n=Ki(d,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),h(s,n)}}for(const e of d){const s=no(t,e,o,r,a,l,c);s&&h(e,s)}}(e,t,s,c,h,n,i,o,r,a),d.length>0&&function(e,t,s,n,i){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0;ki(t,e,e=>!!i.has(e)&&(s=!1,!0)),s&&o.push(e)}let r=1,a=!1;function l(){return r>255?(a||console.warn("Stencil mask overflow"),a=!0,null):r++}function c(t,n){if(a)return;e.renderer_setEntityStencilMask(t,n);const o=e.getChildEntities(s,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),d(t,n)}function d(t,n){if(a)return;const o=e.getChildEntities(s,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),d(t,n)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,s,d,u)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class oo{build(e){if(ie("UIMask",Gi),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(io(e.wasmModule,e.world))}}const ro=new oo,ao=re("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),lo=re("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),co={Normal:0,Hovered:1,Pressed:2,Disabled:3},ho=K("Button",{state:co.Normal,transition:null});class uo{constructor(){this.events_=[]}emit(e,t,s){const n=s??e;this.events_.push({entity:e,type:t,target:n,currentTarget:e})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const fo=Re(new uo,"UIEvents");class po{build(e){ie("UIRect",_i);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){gi=e,yi=t}(s,n);e.addSystemToSchedule(gt.PreUpdate,xt([Ie(Rt)],e=>{e.valid&&(s.uiLayout_update(n,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),s.uiFlexLayout_update(n),s.transform_update(n))},{name:"UILayoutSystem"})),e.addSystemToSchedule(gt.PostUpdate,xt([Ie(Rt)],e=>{e.valid&&(s.uiLayout_update(n,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),s.uiFlexLayout_update(n))},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(gt.PostUpdate,xt([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const mo=new po;let _o=!1,go=!1;function yo(e){_o=e}function wo(){return _o}function xo(){return!_o}function vo(e){go=e}function bo(){return go}const So=function(){const e=new Float32Array(16),t=new Float32Array(16);let s=!0;return{update(e){for(let n=0;n<16;n++)if(t[n]!==e[n]){t.set(e),s=!0;break}},getInverse:t=>(s&&(Ji(t,e),s=!1),e)}}();function Mo(e,t,s,n){t.emit(s,n,s),ki(e,s,i=>{if(!e.has(i,ao))return!1;const o=e.get(i,ao);return o.enabled&&t.emit(i,n,s),o.blockRaycast})}class Po{build(e){ie("Interactable",ao),ie("Button",ho);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),i=new uo;e.insertResource(fo,i);let o=null,r=null;e.addSystemToSchedule(gt.PreUpdate,xt([Ie(Et),Ie(Rt)],(e,a)=>{if(i.drain(),wo()&&!bo())return;const l=t.getEntitiesWithComponents([lo]);for(const e of l){const s=t.get(e,lo);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,lo,s))}if(!a.valid)return;const c=f(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;So.update(a.viewProjection);const u=Qi(d,h,So.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=u.x,a.worldMouseY=u.y;const p=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),_=e.isMouseButtonReleased(0);s.uiHitTest_update(n,u.x,u.y,p,m,_);const g=s.uiHitTest_getHitEntity(),y=4294967295===g?null:g;if(null===o||t.valid(o)||(o=null),o!==y){if(null!==o&&t.valid(o)&&t.has(o,lo)){const e=t.get(o,lo);e.hovered=!1,t.insert(o,lo,e),i.emit(o,"hover_exit")}if(null!==y){Fi(t,y,lo);const e=t.get(y,lo);e.hovered=!0,t.insert(y,lo,e),i.emit(y,"hover_enter")}o=y}if(m&&null!==y){const e=t.get(y,lo);e.pressed=!0,e.justPressed=!0,t.insert(y,lo,e),r=y,Mo(t,i,y,"press")}if(_&&null!==r){if(t.valid(r)&&t.has(r,lo)){const e=t.get(r,lo);e.pressed=!1,e.justReleased=!0,t.insert(r,lo,e),Mo(t,i,r,"release"),r===o&&Mo(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(gt.Update,xt([],()=>{const e=t.getEntitiesWithComponents([ho]);for(const s of e){if(Fi(t,s,ao,{enabled:!0}),!t.has(s,lo))continue;const e=t.get(s,lo),n=t.get(s,ho),i=t.get(s,ao),o=!a.has(s),r=n.state;if(i.enabled?e.pressed?n.state=co.Pressed:e.hovered?n.state=co.Hovered:n.state=co.Normal:n.state=co.Disabled,o&&a.add(s),(o||r!==n.state)&&n.transition&&t.has(s,fe)){const o=t.get(s,fe);o.color=Mi(n.transition,i.enabled,e.pressed,e.hovered),t.insert(s,fe,o)}}},{name:"ButtonSystem"}))}}const To=new Po,Eo=K("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}),Co=K("Focusable",{tabIndex:0,isFocused:!1});class Ao{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Ro=Re(new Ao,"FocusManager");class Io{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(ie("TextInput",Eo),wo()&&!bo())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,i=h(F.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=0,a=0,l=!1,c=!0,d=0,u=0;const f=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!f)return;const p=f;function m(){const t=e.getResource(Ro);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,Eo)?n:null}const _=()=>{l||null===m()||v()},g=()=>{l=!0},y=()=>{l=!1,v()},w=t=>{const n=m();if(null===n)return;if("Escape"===t.key)return void b();const i=s.get(n,Eo);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(fo).emit(n,"submit"),void b()}let o=i.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?o=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=i.value.length),o!==i.cursorPos&&(i.cursorPos=o,p.selectionStart=o,p.selectionEnd=o,i.dirty=!0,S())},x=()=>{const t=m();if(null!==t){const n=s.get(t,Eo);n.focused=!1,n.dirty=!0;e.getResource(Ro).blur()}};function v(){const t=m();if(null===t)return;const n=s.get(t,Eo);if(n.readOnly)return;let i=p.value;if(n.maxLength>0&&i.length>n.maxLength&&(i=i.substring(0,n.maxLength),p.value=i),i!==n.value){n.value=i;e.getResource(fo).emit(t,"change")}n.cursorPos=p.selectionStart??i.length,n.dirty=!0,S()}function b(){const t=m();if(null!==t){const e=s.get(t,Eo);e.focused=!1,e.dirty=!0}e.getResource(Ro).blur(),p.blur()}function S(){c=!0,d=0}p.addEventListener("input",_),p.addEventListener("compositionstart",g),p.addEventListener("compositionend",y),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",_),p.removeEventListener("compositionstart",g),p.removeEventListener("compositionend",y),p.removeEventListener("keydown",w),p.removeEventListener("blur",x),p.remove();const e=t.getResourceManager();for(const t of n.values())e.releaseTexture(t);n.clear(),0!==r&&(t._free(r),r=0,a=0)};let M=null;function P(e,l,d,h){(i.width<d||i.height<h)&&(i.width=Ei(Math.max(i.width,d)),i.height=Ei(Math.max(i.height,h))),o.clearRect(0,0,i.width,i.height);const u=l.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,d,h),o.save(),o.beginPath(),o.rect(l.padding,0,d-2*l.padding,h),o.clip(),o.font=`${l.fontSize}px ${l.fontFamily}`,o.textBaseline="top",o.textAlign="left";const f=0===l.value.length,p=f?l.placeholder:l.password?"●".repeat(l.value.length):l.value,m=f?l.placeholderColor:l.color;o.fillStyle=`rgba(${Math.round(255*m.r)}, ${Math.round(255*m.g)}, ${Math.round(255*m.b)}, ${m.a})`;const _=Math.ceil(1.2*l.fontSize),g=l.padding;if(l.multiline){const e=Ti(o,p,d-2*g);let t=g;for(const s of e)o.fillText(s,g,t),t+=_}else{const e=(h-l.fontSize)/2;o.fillText(p,g,e)}if(l.focused&&c){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,s,n;if(l.multiline){const e=Ti(o,l.value,d-2*g);let i=0,r=0,a=0;for(let t=0;t<e.length;t++){const s=e[t].length;if(i+s>=l.cursorPos){r=t,a=l.cursorPos-i;break}i+=s,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,r=t+1,a=0}const c=r<e.length?e[r].substring(0,a):"";t=g+o.measureText(c).width,s=g+r*_,n=_}else t=g+o.measureText(e).width,s=(h-l.fontSize)/2,n=l.fontSize;o.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,o.fillRect(t,s,2,n)}o.restore();const y=o.getImageData(0,0,d,h),w=new Uint8Array(y.data.buffer),x=t.getResourceManager();w.length>a&&(0!==r&&t._free(r),r=t._malloc(w.length),a=w.length),t.HEAPU8.set(w,r);const v=n.get(e);void 0!==v&&x.releaseTexture(v);const b=x.createTexture(d,h,r,w.length,1,!0);n.set(e,b);const S=s.get(e,fe);S.texture=b,S.size.x=d,S.size.y=h,S.uvOffset.x=0,S.uvOffset.y=0,S.uvScale.x=1,S.uvScale.y=1,S.color={r:1,g:1,b:1,a:1},s.insert(e,fe,S)}e.addSystemToSchedule(gt.Update,xt([Ie(Ro)],e=>{const t=s.getEntitiesWithComponents([Eo]);for(const e of t)Fi(s,e,Co,{tabIndex:0,isFocused:!1}),Fi(s,e,ao,{enabled:!0,blockRaycast:!0});const n=m();if(n!==M){if(null!==M&&s.valid(M)&&s.has(M,Eo)){const e=s.get(M,Eo);e.focused=!1,e.dirty=!0,p.blur()}null!==n&&function(e){const t=s.get(e,Eo);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),S())}(n),M=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(gt.PreUpdate,xt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===u?0:(e-u)/1e3;u=e,i=Math.min(i,.1);const o=m();if(null!==o&&(d+=i,d>=.5)){d-=.5,c=!c;s.get(o,Eo).dirty=!0}const r=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Eo)||(r.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Eo,_i]);for(const e of a){const t=s.get(e,Eo);if(!t.dirty)continue;const n=s.get(e,_i),i=Math.ceil(n.size.x),o=Math.ceil(n.size.y);i<=0||o<=0||(wi(s,e),P(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const ko=new Io,Fo={Simple:0,Sliced:1,Tiled:2,Filled:3},Bo={Horizontal:0,Vertical:1},zo={Left:0,Right:1,Bottom:2,Top:3},Uo=K("Image",{texture:D,color:{r:1,g:1,b:1,a:1},imageType:Fo.Simple,fillMethod:Bo.Horizontal,fillOrigin:zo.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),$o=zi({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,layer:e=>e.image.layer,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?Ai(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Ri(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class Do{build(e){ie("Image",Uo);const t=e.world,s=new Map;e.addSystemToSchedule(gt.PreUpdate,xt([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,Uo)||s.delete(e);const e=t.getEntitiesWithComponents([Uo]);for(const n of e){const e=t.get(n,Uo),i=t.has(n,_i)?t.get(n,_i):null,o={image:e,uiRect:i,entity:n},r=s.get(n);if(r&&!$o.changed(r,o))continue;wi(t,n);const a=t.get(n,fe);if(e.enabled){if(a.texture=e.texture,a.color.r=e.color.r,a.color.g=e.color.g,a.color.b=e.color.b,a.color.a=e.color.a,a.layer=e.layer,a.material=e.material,i&&(a.size.x=Ai(i,n),a.size.y=Ri(i,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Fo.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===Bo.Horizontal?e.fillOrigin===zo.Left?(a.uvScale.x=t,a.size.x=s*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=s*t):e.fillOrigin===zo.Bottom?(a.uvScale.y=t,a.size.y=n*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=n*t)}else e.imageType===Fo.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale.x=a.size.x/e.tileSize.x,a.uvScale.y=a.size.y/e.tileSize.y);t.insert(n,fe,a),s.set(n,$o.take(o))}else a.color.a=0,t.insert(n,fe,a),s.set(n,$o.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const Lo=new Do,Oo=K("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Wo=K("ToggleGroup",{allowSwitchOff:!1});class Ho{build(e){ie("Toggle",Oo),ie("ToggleGroup",Wo);const t=e.world,s=new Set;e.addSystemToSchedule(gt.Update,xt([Ie(fo)],e=>{const n=t.getEntitiesWithComponents([Oo]);if(!wo()||bo()){const i=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,Oo);n.isOn&&0!==n.group&&t.valid(n.group)&&(i.has(n.group)?(n.isOn=!1,t.insert(e,Oo,n)):i.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,Oo);if(0!==s.group&&t.valid(s.group)){let t=o.get(s.group);t||(t=[],o.set(s.group,t)),t.push(e)}}for(const s of n){if(Fi(t,s,ao,{enabled:!0}),!t.has(s,lo))continue;const n=t.get(s,lo),i=t.get(s,Oo),r=t.get(s,ao);if(n.justPressed&&r.enabled){const n=i.group,r=0!==n&&t.valid(n)&&t.has(n,Wo);if(i.isOn&&r){if(!t.get(n,Wo).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(s,Oo,i),i.isOn&&r){const i=o.get(n);if(i)for(const n of i){if(n===s)continue;const i=t.get(n,Oo);i.isOn&&(i.isOn=!1,t.insert(n,Oo,i),e.emit(n,"change"))}}e.emit(s,"change")}if(i.transition&&t.has(s,fe)){const e=t.get(s,fe);e.color=Mi(i.transition,r.enabled,n.pressed,n.hovered),t.insert(s,fe,e)}}}for(const e of n){const s=t.get(e,Oo);if(s.graphicEntity&&t.valid(s.graphicEntity)&&t.has(s.graphicEntity,fe)){const e=t.get(s.graphicEntity,fe);e.enabled=s.isOn,t.insert(s.graphicEntity,fe,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const Xo=new Ho,jo=pi,Yo=K("ProgressBar",{value:0,fillEntity:0,direction:pi.LeftToRight});function No(e,t,s,n){if(!e.has(t,_i))return;const i=e.get(t,_i),o=s/2,r=n/2,a={left:-o,bottom:-r,right:o,top:r},l=mi(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,fe)){const s=e.get(t,fe);s.size.x===l.width&&s.size.y===l.height||(s.size.x=l.width,s.size.y=l.height,e.insert(t,fe,s))}if(e.has(t,de)){const s=e.get(t,de),n=s.position;n.x===l.originX&&n.y===l.originY||(s.position={x:l.originX,y:l.originY,z:n.z},e.insert(t,de,s))}}class Vo{build(e){ie("ProgressBar",Yo);const t=e.world;e.addSystemToSchedule(gt.PreUpdate,xt([],()=>{const e=t.getEntitiesWithComponents([Yo,_i]);for(const s of e){const e=t.get(s,Yo);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,_i),i=Math.max(0,Math.min(1,e.value));Si(t,e.fillEntity,e.direction,i);const o=Ai(n,s),r=Ri(n,s);No(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const qo=new Vo,Go=K("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Ko=K("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});class Jo{build(e){ie("Draggable",Go),ie("DragState",Ko);const t=e.world,s=e.getResource(fo);let n=null,i={x:0,y:0},o=null;e.addSystemToSchedule(gt.PreUpdate,xt([Ie(Et),Ie(Rt)],(e,r)=>{if(wo()&&!bo())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Go,lo]);let s=null,o=-1/0,r=-1;for(const n of e){if(!t.get(n,Go).enabled)continue;if(t.get(n,lo).hovered){let e=0;t.has(n,fe)&&(e=t.get(n,fe).layer);const i=Ci(t,n);(e>o||e===o&&i>=r)&&(o=e,r=i,s=n)}}if(null!==s){n=s,i={x:a.x,y:a.y},t.has(s,Ko)||t.insert(s,Ko);const e=t.get(s,Ko),o=t.get(s,de);e.startWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.currentWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==n&&!e.isMouseButtonDown(0)){if(t.valid(n)&&t.has(n,Ko)){t.get(n,Ko).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),d=t.get(n,Go);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=d.dragThreshold){o=n,n=null;t.get(o,Ko).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Ko))return void(o=null);const n=t.get(o,Ko),i=t.get(o,Go),r=a.x-n.pointerStartWorld.x,l=a.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+r,d=n.startWorldPos.y+l;const h=function(e,t,s,n){let i=e.lockX?t.startWorldPos.x:s,o=e.lockY?t.startWorldPos.y:n;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:i,y:o}}(i,n,c,d);c=h.x,d=h.y;const u=n.currentWorldPos.x,f=n.currentWorldPos.y;if(n.deltaWorld={x:c-u,y:d-f},n.currentWorldPos={x:c,y:d},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:d-n.startWorldPos.y},t.has(o,de)){const e=function(e,t,s,n){if(!e.has(t,ge))return{x:s,y:n};const i=e.get(t,ge).entity;if(!e.valid(i)||!e.has(i,de))return{x:s,y:n};const o=e.get(i,de),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=eo(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l);return{x:(s*d-n*c)/r,y:(s*c+n*d)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,de);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,de,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}}const Qo=new Jo,Zo=K("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function er(e,t,s,n){return n<=0?1:e<t?Math.max(0,1-(t-e)/n):e>s?Math.max(0,1-(e-s)/n):1}function tr(e,t,s,n,i){const o=2/(n=Math.max(1e-4,n)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(s+o*l)*i,d=t+(l+c)*a;return t-e>0==d>t?{value:t,velocity:0}:{value:d,velocity:(s-o*c)*a}}class sr{build(e){ie("ScrollView",Zo);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(gt.PostUpdate,xt([Ie(Et),Ie(Rt),Ie(ze)],(e,i,o)=>{const r=wo()&&!bo(),a=Math.min(o.delta,.05);for(const[e]of s)t.valid(e)||s.delete(e);i.valid&&(n.x=i.worldMouseX,n.y=i.worldMouseY);const l=t.getEntitiesWithComponents([Zo,_i]);for(const o of l){Fi(t,o,Gi,{enabled:!0,mode:Vi});const l=t.get(o,Zo),c=t.get(o,_i);let d=s.get(o);d||(d={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},s.set(o,d));const h=Ai(c,o),u=Ri(c,o);let f=l.contentWidth,p=l.contentHeight;if((0===f||0===p)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,ye)){const e=t.get(l.contentEntity,ye).entities;let s=0,n=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,de))continue;const e=t.get(r,de);let a=0,l=0,c=.5,d=.5;if(t.has(r,_i)){const e=t.get(r,_i);a=Ai(e,r)||e.size.x,l=Ri(e,r)||e.size.y,c=e.pivot.x,d=e.pivot.y}else if(t.has(r,fe)){const e=t.get(r,fe);a=e.size.x,l=e.size.y}const h=e.position.x-a*c,u=e.position.x+a*(1-c),f=e.position.y-l*d,p=e.position.y+l*(1-d);h<s&&(s=h),u>n&&(n=u),f<i&&(i=f),p>o&&(o=p)}0===f&&(f=n-s),0===p&&(p=o-i)}const m=Math.max(0,f-h),_=Math.max(0,p-u);if(!r&&i.valid){Fi(t,o,ao,{enabled:!0,blockRaycast:!0});const s=t.has(o,lo)?t.get(o,lo):null;if(s?.justPressed&&(d.isDragging=!0,d.lastWorldX=n.x,d.lastWorldY=n.y,d.velocityX=0,d.velocityY=0),d.isDragging&&e.isMouseButtonDown(0)){const e=n.x-d.lastWorldX,t=n.y-d.lastWorldY,s=Math.min(1,10*a);if(l.horizontalEnabled){const t=er(l.scrollX,0,m,h);if(l.scrollX-=e*t,0===e)d.velocityX=0;else{const n=a>0?-e*t/a:0;d.velocityX+=(n-d.velocityX)*s}}if(l.verticalEnabled){const e=er(l.scrollY,0,_,u);if(l.scrollY+=t*e,0===t)d.velocityY=0;else{const n=a>0?t*e/a:0;d.velocityY+=(n-d.velocityY)*s}}d.lastWorldX=n.x,d.lastWorldY=n.y}if(d.isDragging&&e.isMouseButtonReleased(0)){d.isDragging=!1;const e=5*h,t=5*u;d.velocityX=Math.max(-e,Math.min(d.velocityX,e)),d.velocityY=Math.max(-t,Math.min(d.velocityY,t))}if(s?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=er(l.scrollY,0,_,u);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=er(l.scrollX,0,m,h);l.scrollX+=t.x*l.wheelSensitivity*e,d.velocityX=0}}}if(!d.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>_;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=tr(l.scrollX,e,d.velocityX,.1,a);l.scrollX=t.value,d.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(d.velocityX)<Ui&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>Ui?(d.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=d.velocityX*a):d.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:_,t=tr(l.scrollY,e,d.velocityY,.1,a);l.scrollY=t.value,d.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(d.velocityY)<Ui&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>Ui?(d.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=d.velocityY*a):d.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,m)),l.scrollY=Math.max(0,Math.min(l.scrollY,_)),l.scrollX!==e&&(d.velocityX=0),l.scrollY!==t&&(d.velocityY=0)}}if(l.elastic){const e=.5*h,t=.5*u;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,_+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,de)){const e=t.get(l.contentEntity,de),s=e.position.x,n=e.position.y;(isNaN(d.lastAppliedX)||Math.abs(s-d.lastAppliedX)>.01)&&(d.contentBaseX=s),(isNaN(d.lastAppliedY)||Math.abs(n-d.lastAppliedY)>.01)&&(d.contentBaseY=n),e.position.x=d.contentBaseX-l.scrollX,e.position.y=d.contentBaseY+l.scrollY,d.lastAppliedX=e.position.x,d.lastAppliedY=e.position.y,t.insert(l.contentEntity,de,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const nr=new sr,ir=pi,or=K("Slider",{value:0,minValue:0,maxValue:1,direction:pi.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function rr(e,t,s,n,i,o){const r=Ai(n,i)*s.worldScale.x,a=Ri(n,i)*s.worldScale.y,l=eo(s.worldRotation.z,s.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l),h=e-s.worldPosition.x,u=t-s.worldPosition.y,f=h*d-u*c,p=h*c+u*d,m=-n.pivot.x*r,_=-n.pivot.y*a;switch(o){case pi.LeftToRight:return r>0?(f-m)/r:0;case pi.RightToLeft:return r>0?1-(f-m)/r:0;case pi.BottomToTop:return a>0?(p-_)/a:0;case pi.TopToBottom:return a>0?1-(p-_)/a:0}}function ar(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case pi.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case pi.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case pi.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case pi.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class lr{build(e){ie("Slider",or);const t=e.world;let s=null;e.addSystemToSchedule(gt.PreUpdate,xt([Ie(Et),Ie(Rt),Ie(fo)],(e,n,i)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([or,_i]);for(const r of o){const o=t.get(r,or),a=t.get(r,_i);if(!wo()||bo()){if(t.has(r,de)){Fi(t,r,ao,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Fi(t,o.handleEntity,ao,{enabled:!0,blockRaycast:!1});const l=t.get(r,de),c=t.has(r,lo)?t.get(r,lo):null;let d=c?.justPressed??!1;if(!d&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,lo)&&(d=t.get(o.handleEntity,lo).justPressed),d&&(s=r),s===r&&e.isMouseButtonDown(0)){let e=rr(n.worldMouseX,n.worldMouseY,l,a,r,o.direction);e=Math.max(0,Math.min(1,e));let s=o.minValue+e*(o.maxValue-o.minValue);o.wholeNumbers&&(s=Math.round(s));const c=o.value;o.value=Math.max(o.minValue,Math.min(o.maxValue,s)),t.insert(r,or,o),o.value!==c&&i.emit(r,"change")}s===r&&e.isMouseButtonReleased(0)&&(s=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,d=Ai(a,r),h=Ri(a,r),u={left:-d/2,bottom:-h/2,right:d/2,top:h/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(Si(t,o.fillEntity,o.direction,c),Bi(t,o.fillEntity,u,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,_i)){const e=t.get(o.handleEntity,_i);ar(e,o.direction,c),t.insert(o.handleEntity,_i,e),Bi(t,o.handleEntity,u,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const cr=new lr;class dr{build(e){ie("Focusable",Co);const t=e.world,s=new Ao;e.insertResource(Ro,s),e.addSystemToSchedule(gt.Update,xt([Ie(Et),Ie(fo)],(e,n)=>{if(wo()&&!bo())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const i=t.getEntitiesWithComponents([Co]);for(const e of i){if(!t.has(e,lo))continue;t.get(e,lo).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const n=function(){const e=[];for(const s of i){if(!t.valid(s))continue;if(t.has(s,ao)){if(!t.get(s,ao).enabled)continue}const n=t.get(s,Co);e.push({entity:s,tabIndex:n.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===n.length)return;const r=null!==s.focusedEntity?n.findIndex(e=>e===s.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?n.length-1:0:a?(r-1+n.length)%n.length:(r+1)%n.length,o(n[l])}function o(e){const i=s.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Co)){t.get(i,Co).isFocused=!1,n.emit(i,"blur",i)}s.focus(e);t.get(e,Co).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const hr=new dr,ur=K("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function fr(){return i()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:s,screenWidth:n,screenHeight:i}=t;return{top:s.top,bottom:i-s.bottom,left:s.left,right:n-s.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}class pr{build(e){ie("SafeArea",ur);const t=e.world;let s=fr(),n=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{s=fr(),n=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{s=fr(),n=!0});e.addSystemToSchedule(gt.PreUpdate,xt([Ie(Rt)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===r||(o=e.screenH,r=a,n=!0),!n)return;n=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,d=t.getEntitiesWithComponents([ur,_i]);for(const e of d){const n=t.get(e,ur),i=t.get(e,_i),o=n.applyTop?s.top*c:0,r=n.applyBottom?s.bottom*c:0,a=n.applyLeft?s.left*c:0,l=n.applyRight?s.right*c:0;let d=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},d=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},d=!0),d&&t.insert(e,_i,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const mr=new pr,_r=K("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let gr=null;function yr(e,t){if(!gr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=gr.get(e);s?s.renderer=t:gr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}class wr{build(e){ie("ListView",_r);const t=e.world,s=new Map;gr=s,e.addSystemToSchedule(gt.PostUpdate,xt([Ie(Et)],e=>{const n=wo()&&!bo();for(const[e,n]of s)if(!t.valid(e)){for(const e of n.itemEntities.values())t.valid(e)&&t.despawn(e);s.delete(e)}const i=t.getEntitiesWithComponents([_r,_i]);for(const o of i){Fi(t,o,ao,{enabled:!0,blockRaycast:!0}),Fi(t,o,Gi,{enabled:!0,mode:Vi});let i=s.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},s.set(o,i));const r=t.get(o,_r),a=t.get(o,_i),l=Ri(a,o),c=Ai(a,o);if(!n){const s=t.has(o,lo)?t.get(o,lo):null;if(s?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const d=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,d));const h=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),u=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,s]of i.itemEntities)(e<h||e>=u)&&(t.valid(s)&&t.despawn(s),i.itemEntities.delete(e));for(let e=h;e<u;e++){let s=i.itemEntities.get(e);if(s&&t.valid(s)||(s=t.spawn(),t.insert(s,ve,{value:`ListItem_${e}`}),t.insert(s,_i,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(s,o),i.itemEntities.set(e,s),i.renderer&&i.renderer(e,s)),t.has(s,de)){const n=t.get(s,de);n.position.y=-(e*r.itemHeight-r.scrollY),t.insert(s,de,n)}}i.visibleStart=h,i.visibleEnd=u}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const xr=new wr,vr=K("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class br{build(e){ie("Dropdown",vr);const t=e.world,s=new Map;function n(e){if(0===e||!t.valid(e))return;if(!t.has(e,de))return;const s=t.get(e,de);0===s.scale.x&&0===s.scale.y&&0===s.scale.z&&t.insert(e,de,{position:{x:s.position.x,y:s.position.y,z:s.position.z},rotation:{x:s.rotation.x,y:s.rotation.y,z:s.rotation.z,w:s.rotation.w},scale:{x:1,y:1,z:1}})}function i(e){if(t.has(e,fe)){const s=t.get(e,fe);1===s.color.r&&1===s.color.g&&1===s.color.b&&1===s.color.a&&t.insert(e,fe,{texture:s.texture,color:{r:.9,g:.9,b:.9,a:1},size:{x:s.size.x,y:s.size.y},uvOffset:{x:s.uvOffset.x,y:s.uvOffset.y},uvScale:{x:s.uvScale.x,y:s.uvScale.y},layer:s.layer,flipX:s.flipX,flipY:s.flipY,material:s.material,enabled:s.enabled})}}function o(e,s,n){s.isOpen=!0,n.highlightIndex=s.selectedIndex;const i=s.listEntity;if(0===i||!t.valid(i))return;d(i,!0),c(n);const o=t.get(e,fe),r=o.size.x,a=o.size.y;n.ddWidth=r;const l=s.options.length*$i;t.insert(i,_i,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:l},pivot:{x:.5,y:.5}}),t.insert(i,de,{position:{x:0,y:-(a+l)/2,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(i,fe,{texture:D,color:{r:1,g:1,b:1,a:1},size:{x:r,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<s.options.length;e++){const o=t.spawn(),a=l/2-(e+.5)*$i;t.insert(o,ve,{value:`Option_${e}`}),t.insert(o,_i,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*$i},offsetMax:{x:0,y:0},size:{x:r,y:$i},pivot:{x:.5,y:.5}}),t.insert(o,de,{position:{x:0,y:a,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(o,fe,{texture:D,color:{r:.95,g:.95,b:.95,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,enabled:!0}),t.insert(o,ao,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),n.optionEntities.push(o);const c=t.spawn();t.insert(c,de,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(c,Hi,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Li.Left,verticalAlign:Oi.Middle,wordWrap:!1,overflow:Wi.Clip,lineHeight:1.2}),t.insert(c,_i,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:$i},pivot:{x:.5,y:.5}}),t.setParent(c,o),n.textEntities.push(c)}h(n)}function r(e,t,s){t.isOpen=!1,c(s),d(t.listEntity,!1)}function a(e,t,s,n,i){t.selectedIndex=n,r(0,t,s),i.emit(e,"change")}function l(e){const s=e.labelEntity;if(0===s||!t.valid(s))return;if(!t.has(s,Hi))return;const n=t.get(s,Hi);let i={r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},o=n.content,r=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},r=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,r=!0)}r&&t.insert(s,Hi,{content:o,fontSize:n.fontSize,fontFamily:n.fontFamily,color:i,align:n.align,verticalAlign:n.verticalAlign,wordWrap:n.wordWrap,overflow:n.overflow,lineHeight:n.lineHeight})}function c(e){for(const s of e.textEntities)t.valid(s)&&t.despawn(s);for(const s of e.optionEntities)t.valid(s)&&t.despawn(s);e.optionEntities=[],e.textEntities=[]}function d(e,s){if(0!==e&&t.valid(e)&&(t.has(e,ao)&&t.insert(e,ao,{enabled:s,blockRaycast:!0,raycastTarget:!0}),t.has(e,fe))){const n=t.get(e,fe);t.insert(e,fe,{texture:n.texture,color:{r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:s})}}function h(e){for(let s=0;s<e.optionEntities.length;s++){const n=e.optionEntities[s];if(!t.valid(n)||!t.has(n,fe))continue;const i=s===e.highlightIndex?{...Di}:{r:.95,g:.95,b:.95,a:1};t.insert(n,fe,{texture:D,color:i,size:{x:e.ddWidth,y:$i},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function u(e){for(const s of e.optionEntities){if(!t.valid(s)||!t.has(s,lo))continue;if(t.get(s,lo).hovered)return!0}return!1}e.addSystemToSchedule(gt.Update,xt([Ie(Et),Ie(fo)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const f=wo()&&!bo(),p=t.getEntitiesWithComponents([vr]);for(const m of p){const p=t.get(m,vr);let _=s.get(m);if(_||(_={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},s.set(m,_)),n(p.listEntity),i(m),p.isOpen||d(p.listEntity,!1),l(p),f)continue;Fi(t,m,ao,{enabled:!0,blockRaycast:!0});const g=t.has(m,lo)?t.get(m,lo):null;if(g?.justPressed&&(p.isOpen?r(m,p,_):o(m,p,_)),p.isOpen){for(let e=0;e<_.optionEntities.length;e++){const s=_.optionEntities[e];if(!t.valid(s)||!t.has(s,lo))continue;if(t.get(s,lo).justPressed){a(m,p,_,e,c);break}}let s=-1;for(let e=0;e<_.optionEntities.length;e++){const n=_.optionEntities[e];if(!t.valid(n)||!t.has(n,lo))continue;if(t.get(n,lo).hovered){s=e;break}}s>=0&&s!==_.highlightIndex&&(_.highlightIndex=s,h(_)),e.isKeyPressed("ArrowDown")?(_.highlightIndex>=p.options.length-1?_.highlightIndex=0:_.highlightIndex++,h(_)):e.isKeyPressed("ArrowUp")?(_.highlightIndex<=0?_.highlightIndex=p.options.length-1:_.highlightIndex--,h(_)):e.isKeyPressed("Enter")&&_.highlightIndex>=0?a(m,p,_,_.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,p,_),e.isMouseButtonPressed(0)&&(g?.hovered||u(_)||r(m,p,_))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}}const Sr=new br,Mr=0,Pr=0,Tr=2,Er=K("LayoutGroup",{direction:Mr,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Pr,reverseOrder:!1});class Cr{build(e){ie("LayoutGroup",Er);const t=e.world;e.addSystemToSchedule(gt.PreUpdate,xt([],()=>{const e=t.getEntitiesWithComponents([Er,_i,ye]);for(const s of e){const e=t.get(s,Er),n=t.get(s,_i),i=t.get(s,ye);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,_i)&&t.has(e,de)&&o.push({entity:e,rect:t.get(e,_i)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=Ai(n,s),a=Ri(n,s),l=n.pivot.x,c=n.pivot.y,d=e.padding,h=e.direction===Mr;let u=0;for(let s=0;s<o.length;s++){const n=o[s],i=Ai(n.rect,n.entity),f=Ri(n.rect,n.entity),p=n.rect.pivot.x,m=n.rect.pivot.y;let _,g;h?(_=-l*r+d.left+u+p*i,g=e.childAlignment===Pr?(1-c)*a-d.top-(1-m)*f:e.childAlignment===Tr?-c*a+d.bottom+m*f:(.5-c)*a+.5*(d.bottom-d.top)+(m-.5)*f,u+=i,s<o.length-1&&(u+=e.spacing)):(_=e.childAlignment===Pr?-l*r+d.left+p*i:e.childAlignment===Tr?(1-l)*r-d.right-(1-p)*i:(.5-l)*r+.5*(d.left-d.right)+(p-.5)*i,g=(1-c)*a-d.top-u-(1-m)*f,u+=f,s<o.length-1&&(u+=e.spacing));const y=t.get(n.entity,de);y.position.x=_,y.position.y=g,t.insert(n.entity,de,y)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}}const Ar=new Cr;class Rr{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(gt.PostUpdate,xt([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const Ir=new Rr;async function kr(e,t,s){const n=e.getResource(Gn);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function Fr(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 Br=Re({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),zr=Re(null,"PhysicsAPI");function Ur(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function $r(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Dr{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(Br,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Fr(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const i=function(e){const t=e.world.getEntitiesWithComponents([me]);for(const s of t){const t=e.world.get(s,me);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/i,r=e.world;r.onDespawn(e=>{t.has(e)&&(n._physics_destroyBody(e),t.delete(e),s.delete(e))}),e.addSystemToSchedule(gt.PostUpdate,xt([Ie(ze)],a=>{const l=r.getEntitiesWithComponents([Me,de]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,Me),l=r.get(i,de);if(t.has(i)){const e=s.get(i);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(i,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const r=Ur(l.worldRotation);n._physics_createBody(i,a.bodyType,l.worldPosition.x*o,l.worldPosition.y*o,r,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Lr(e,n,i),t.add(i),s.set(i,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===Ce.Kinematic){const e=Ur(l.worldRotation);n._physics_setBodyTransform(i,l.worldPosition.x*o,l.worldPosition.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 i=t._physics_getDynamicBodyTransforms(),o=i>>2;for(let i=0;i<n;i++){const n=o+4*i,r=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(r))continue;const d=e.world.get(r,de);if(!d)continue;let h=a,u=l,f=c;if(e.world.has(r,ge)){const t=e.world.get(r,ge);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,de)){const s=e.world.get(t.entity,de),n=Ur(s.worldRotation),i=a-s.worldPosition.x,o=l-s.worldPosition.y,r=Math.cos(-n),d=Math.sin(-n);h=(i*r-o*d)/(0!==s.worldScale.x?s.worldScale.x:1),u=(i*d+o*r)/(0!==s.worldScale.y?s.worldScale.y:1),f=c-n}}d.position.x=h,d.position.y=u;const p=$r(f);d.rotation.w=p.w,d.rotation.x=p.x,d.rotation.y=p.y,d.rotation.z=p.z,e.world.insert(r,de,d)}}(e,n,i),function(e,t,s){t._physics_collectEvents();const n=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<i;o++){const i=e+6*o;n.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*s,contactY:t.HEAPF32[i+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 n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],d=t._physics_getSensorExitCount();if(d>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<d;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(Br,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,i)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(zr,Or._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function Lr(e,t,s){const n=e.world;if(n.has(s,Pe)){const e=n.get(s,Pe);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,Te)){const e=n.get(s,Te);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,Ee)){const e=n.get(s,Ee);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 Or{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(Or.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}const Wr={nearest:0,linear:1},Hr={repeat:0,clamp:1,mirror:2};function Xr(e,t,s=!0,n){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),n&&(n.filterMode||n.wrapMode)&&i.createTextureEx){const e=Wr[n.filterMode??"linear"]??1,a=Hr[n.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,s,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,s);return e._free(o),r}function jr(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 Yr(e,t,s,n){const i=e.worldScale.x*t*(s?-1:1),o=e.worldScale.y*t*(n?-1:1),r=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,d=e.worldRotation.w,h=a+a,u=l+l,f=c+c,p=a*h,m=a*u,_=a*f,g=l*u,y=l*f,w=c*f,x=d*h,v=d*u,b=d*f;return new Float32Array([(1-(g+w))*i,(m+b)*i,(_-v)*i,0,(m-b)*o,(1-(p+w))*o,(y+x)*o,0,(_+v)*r,(y-x)*r,(1-(p+g))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function Nr(e){const{app:t,module:s,sceneData:n,provider:i,spineModule:o,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,d=await async function(e,t,s){const n={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=ds(t.type);for(const r of o){if("texture"!==r.type)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===n[o])try{const t=i?.[o];n[o]=Xr(e,await s.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),n[o]=0}}}return n}(s,n,i);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const i=s[e];if(i&&i>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(s,n,d);let h={},u=null;if(o&&(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"])}}(o),h=await async function(e,t,s,n,i){const o={};for(const r of n.entities)for(const n of r.components){const r=hs(n.type);if(!r||!n.data)continue;const a=n.data[r.skeletonField],l=n.data[r.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),d=i.resolvePath(l);try{const n=await i.readText(l),r="binary"===Cs(c)?.contentType;let h,u;if(r){const e=await i.readBinary(a);u=e.length,h=t._malloc(u),t.HEAPU8.set(e,h)}else{const e=await i.readText(a),s=(new TextEncoder).encode(e);u=s.length,h=t._malloc(u+1),t.HEAPU8.set(s,h),t.HEAPU8[h+u]=0}const f=s.loadSkeleton(h,u,n,n.length,r);if(t._free(h),f<0)continue;o[a]=f;const p=jr(n),m=d.substring(0,d.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=m+"/"+p[t];try{const o=i.loadPixelsRaw?await i.loadPixelsRaw(n):await i.loadPixels(n),r=Xr(e,o,!1),a=e.getResourceManager().getTextureGLId(r);s.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(s,o,u,n,i)),r){const e={gravity:a?.gravity??{...R},fixedTimestep:a?.fixedTimestep??I,subStepCount:a?.subStepCount??4};new Dr("",e,()=>Promise.resolve(r)).build(t)}const f=await async function(e,t,s){const n={};for(const i of t.entities)for(const t of i.components){const i=ds(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{let t,i;const r=Cs(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await s.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){n[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await s.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),d=Xr(e,c,!1),h=e.getResourceManager();n[o]=h.loadBitmapFont(t,d,c.width,c.height)}catch{n[o]=0}}return n}(s,n,i),p=await async function(e,t){const s={},n={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=ds(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){s[o]=0;continue}const i=e.vertexSource+e.fragmentSource;let r=n[i];r||(r=Ot.createShader(e.vertexSource,e.fragmentSource),n[i]=r),s[o]=Ot.createFromAsset(e,r)}catch{s[o]=0}}return s}(n,i);await async function(e,t,s){const n=new Set;for(const i of t.entities)for(const t of i.components){const i=ds(t.type);for(const o of i){if("anim-clip"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!n.has(i)){n.add(i);try{const t=await s.readText(i),n=JSON.parse(t),o=Jt(n),r=new Map;for(const t of o)try{const n=await s.loadPixels(t);r.set(t,Xr(e,n))}catch{r.set(t,0)}es(Qt(i,n,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(s,n,i),await async function(e){const t=[],s=new Set;for(const n of e.entities)for(const e of n.components){const n=ds(e.type);for(const i of n){if("audio"!==i.type)continue;const n=e.data[i.field];"string"==typeof n&&n&&!s.has(n)&&(s.add(n),t.push(n))}}t.length>0&&await rs.preloadAll(t).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)})}(n),function(e,t,s,n){const i={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=ds(e.type);if(0===t.length)continue;const s=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof s[e.field]&&(s[e.field]=t[s[e.field]]||0)}}}(n,d,f,p);const m=gs(t.world,n);if(c&&t.hasResource(Gn))for(const e of m.values())t.world.insert(e,be,{scene:c,persistent:!1});if(o&&u){const e=function(e,t,s,n){const i={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const r=hs(t.type);if(!r||!t.data)continue;const a=s[t.data[r.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=n.get(o.id);void 0!==c&&(i[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return i}(u,n,h,m);!function(e,t,s,n,i){let o=0;e.setSpineRenderer((r,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=A);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,xe)?c.get(o,xe):null,d=!1!==a?.playing,h=a?.timeScale??1;d&&n.update(r,l*h);let u=0;if(c.has(o,de)){const e=Yr(c.get(o,de),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);u=t._malloc(64),t.HEAPF32.set(e,u>>2)}const f=n.getMeshBatchCount(r);for(let e=0;e<f;e++){const i=n.getMeshBatchVertexCount(r,e),o=n.getMeshBatchIndexCount(r,e);if(!i||!o)continue;const a=8*i*4,l=2*o,c=s._malloc(a),d=s._malloc(l),h=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(r,e,c,d,h,f);const p=s.HEAPU32[h>>2],m=s.HEAPU32[f>>2],_=new Float32Array(s.HEAPF32.buffer,c,8*i),g=new Uint16Array(s.HEAPU8.buffer,d,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,i,w,o,p,m,u),t._free(y),t._free(w),s._free(c),s._free(d),s._free(h),s._free(f)}u&&t._free(u)}})}(t,s,o,u,e)}if(l){const e=t.getResource(Ws);e&&e.setAddressableManifest(l)}}function Vr(e,t,s){return{name:e,async setup(){await Nr({...s,sceneData:t,sceneName:e})}}}async function qr(e){const{app:t,firstScene:s,aspectRatio:n}=e;ei(t);const i={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},o=t.getResource(Gn);for(const t of e.scenes)o.register(Vr(t.name,t.data,i));s&&(o.setInitial(s),await o.load(s)),void 0!==n&&vs(t.world,n)}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 i of e.entities)for(const e of i.components){if(!e.data)continue;const i=hs(e.type);if(i){const n=e.data[i.skeletonField],o=e.data[i.atlasField];n&&("binary"===Cs(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=ds(e.type);for(const s of o){const i=e.data[s.field];"string"==typeof i&&i&&("font"===s.type?(n.add(i),t.add(i)):("material"===s.type||"anim-clip"===s.type)&&t.add(i))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const o=[];for(const e of n){const t=Cs(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(),i=await createImageBitmap(n),o=new OffscreenCanvas(i.width,i.height).getContext("2d");o.drawImage(i,0,0);const r=o.getImageData(0,0,i.width,i.height);return i.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Kr="__preview__";class Jr{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(Gn);t.register({name:Kr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Kr),this.loadPromise_=t.load(Kr).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await r(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 i=this.app_.spineInitPromise;if(i){n=(await i).controller.raw}await Nr({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:s,spineModule:n,sceneName:Kr})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([pe]);for(const n of s){if(e.get(n,pe).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1.7777777777777777;const n=e.getEntitiesWithComponents([me]);for(const i of n){const n=e.get(i,me);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const i=this.app_.getResource(Gn).getScene(Kr),o=i?i.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,de,r);const a={isActive:!0,projectionType:ae.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:le.ColorAndDepth};e.insert(o,pe,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(Gn);await e.switchTo(Kr),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 Qr={create(e){const t=e.depth??!0,s="linear"===e.filter,n=(t?1:0)|(s?2:0),i=Ln.createRenderTarget(e.width,e.height,n);return{_handle:i,textureId:Ln.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:s?"linear":"nearest"}},release(e){Ln.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Ln.releaseRenderTarget(e._handle),Qr.create({width:t,height:s,depth:e._depth,filter:e._filter})),begin(e,t){Ln.begin(t,e._handle)},end(){Ln.end()},getDepthTexture:e=>Ln.getTargetDepthTexture(e._handle)};var Zr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Zr||(Zr={}));class ea{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Zr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Zr.Debug:console.debug(t,s);break;case Zr.Info:console.log(t,s);break;case Zr.Warn:console.warn(t,s);break;case Zr.Error:console.error(t,s)}}}class ta{constructor(){this.handlers_=[],this.minLevel_=Zr.Info,this.addHandler(new ea)}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(Zr.Debug,e,t,s)}info(e,t,s){this.log(Zr.Info,e,t,s)}warn(e,t,s){this.log(Zr.Warn,e,t,s)}error(e,t,s){this.log(Zr.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const i={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const sa=new ta;function na(){return sa}function ia(e){sa.setMinLevel(e)}function oa(e,t,s){sa.debug(e,t,s)}function ra(e,t,s){sa.info(e,t,s)}function aa(e,t,s){sa.warn(e,t,s)}function la(e,t,s){sa.error(e,t,s)}const ca={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},da={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12},ha={Running:0,Paused:1,Completed:2,Cancelled:3},ua={None:0,Restart:1,PingPong:2};class fa{constructor(e,t,s){this.module_=e,this.registry_=t,this.entity=s}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,s,n){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,s,n),this}then(e){return this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let pa=null,ma=null;function _a(e,t){pa=e,ma=t}function ga(){pa=null,ma=null}function ya(){if(!pa)throw new Error("Tween API not initialized");return pa}function wa(){if(!ma)throw new Error("Tween API not initialized");return ma}const xa={to(e,t,s,n,i,o){const r=ya(),a=wa(),l=o?.easing??ca.Linear,c=o?.delay??0,d=o?.loop??ua.None,h=o?.loopCount??0,u=r._anim_createTween(a,e,t,s,n,i,l,c,d,h);return new fa(r,a,u)},cancel(e){ya()._anim_cancelTween(wa(),e.entity)},cancelAll(e){ya()._anim_cancelAllTweens(wa(),e)},update(e){ya()._anim_updateTweens(wa(),e)}};class va{constructor(){this.name="AnimationPlugin"}build(e){_a(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(gt.Update,xt([Ie(ze)],e=>{xa.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(gt.Update,xt([Ie(ze)],e=>{os(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){ga()}}const ba=new va;var Sa;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(Sa||(Sa={}));const Ma={model:Sa.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function Pa(e,t=Ma){const{model:s,refDistance:n,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(s){case Sa.Linear:{const e=i-n;if(e<=0)return 1;a=1-(Math.min(Math.max(r,n),i)-n)/e;break}case Sa.Inverse:a=n/Math.max(r,n);break;case Sa.Exponential:a=Math.pow(Math.max(r,n)/n,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function Ta(e,t,s,n,i){const o=e-s;return Math.max(-1,Math.min(1,o/i))}const Ea=K("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:Sa.Inverse,rolloff:1,priority:0,enabled:!0}),Ca=K("AudioListener",{enabled:!0});class Aa{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const s=t().createAudioBackend(),n=this.config_;s.initialize({initialPoolSize:n.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const i=s.mixer;rs.init(s,i),i&&(void 0!==n.masterVolume&&(i.master.volume=n.masterVolume),void 0!==n.musicVolume&&(i.music.volume=n.musicVolume),void 0!==n.sfxVolume&&(i.sfx.volume=n.sfxVolume));const o=new Map;this.activeSourceHandles_=o;const r=new Set;this.playedEntities_=r;const a=new Set;let l=!1,c=!1;e.addSystemToSchedule(gt.PreUpdate,xt([Ie(ze)],t=>{if(!(!wo()||bo()))return void(c&&(l=!1,c=!1));c=!0;const n=e.world;let i=0,d=0,h=!1;const u=n.getEntitiesWithComponents([Ca,ue]);for(const e of u){if(n.get(e,Ca).enabled){const t=n.get(e,ue);i=t.position.x,d=t.position.y,h=!0;break}}const f=n.getEntitiesWithComponents([Ea]);a.clear();for(const e of f){const t=n.get(e,Ea);if(!t.enabled||!t.clip)continue;const c=e;if(a.add(c),t.playOnAwake&&!r.has(c)&&!o.has(c)&&s.isReady){const e=rs.getBufferHandle(t.clip);if(e){const n=s.play(e,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});o.set(c,n),r.add(c)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(c)){const s=o.get(c);if(!s.isPlaying){o.delete(c);continue}h||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=n.tryGet?.(e,ue),a=r?.position.x??0,u=r?.position.y??0,f=a-i,p=u-d,m=Pa(Math.sqrt(f*f+p*p),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),_=Ta(a,0,i,0,t.maxDistance);s.setVolume(t.volume*m),s.setPan(_)}}for(const[e,t]of o)a.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),rs.dispose()}}const Ra=new Aa;function Ia(e,t){return e.toFixed(t)}function ka(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}class Fa{constructor(e,t="bottom-left"){this.visible_=!0,this.disposed_=!1,this.el_=document.createElement("div"),this.el_.style.cssText="\nposition: fixed;\nz-index: 99999;\npointer-events: none;\nbackground: rgba(30, 30, 30, 0.85);\nborder: 1px solid rgba(60, 60, 60, 0.8);\nborder-radius: 4px;\npadding: 6px 10px;\nfont: 11px monospace;\ncolor: #cccccc;\nline-height: 1.6;\nmin-width: 200px;\nwhite-space: pre;\n"+function(e){switch(e){case"top-left":return"top: 12px; left: 12px;";case"top-right":return"top: 12px; right: 12px;";case"bottom-left":return"bottom: 12px; left: 12px;";case"bottom-right":return"bottom: 12px; right: 12px;"}}(t),e.appendChild(this.el_)}update(e){if(!this.visible_||this.disposed_)return;const t=[];if(t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div><div>FPS: <span style="color:#d19a66">${Ia(e.fps,1)}</span> Frame: <span style="color:#d19a66">${Ia(e.frameTimeMs,1)}ms</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div><div>DC: <span style="color:#d19a66">${e.drawCalls}</span> Tri: <span style="color:#d19a66">${e.triangles}</span></div><div>Sprites: <span style="color:#d19a66">${e.sprites}</span> Culled: <span style="color:#d19a66">${e.culled}</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div><div>Entities: <span style="color:#d19a66">${e.entityCount}</span></div>`),e.systemTimings.size>0){const s=[...e.systemTimings.entries()].sort((e,t)=>t[1]-e[1]).slice(0,5);let n='<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';for(const[e,t]of s){n+=`<div>${ka(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${Ia(t,1)}ms</span></div>`}t.push(n)}this.el_.innerHTML=t.join("")}show(){this.visible_=!0,this.el_.style.display=""}hide(){this.visible_=!1,this.el_.style.display="none"}dispose(){this.disposed_=!0,this.el_.parentElement?.removeChild(this.el_)}}function Ba(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const za=Re(Ba(),"Stats");class Ua{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,s){const n={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:s?new Map(s):new Map};this.count_<this.capacity_?(this.buffer_.push(n),this.count_++):this.buffer_[this.cursor_]=n,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}}const $a="StatsCollect";class Da{constructor(){this.deltas_=[],this.cursor_=0,this.count_=0,this.sum_=0}pushFrame(e){!Number.isFinite(e)||e<0||(this.count_<60?(this.deltas_.push(e),this.sum_+=e,this.count_++):(this.sum_-=this.deltas_[this.cursor_],this.deltas_[this.cursor_]=e,this.sum_+=e,this.cursor_=(this.cursor_+1)%60))}getFps(){return 0===this.count_||this.sum_<=0?0:this.count_/this.sum_}getFrameTimeMs(){return 0===this.count_||this.sum_<=0?0:this.sum_/this.count_*1e3}reset(){this.deltas_.length=0,this.cursor_=0,this.count_=0,this.sum_=0}}class La{constructor(e){this.name="Stats",this.collector_=new Da,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(za,Ba());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new Fa(e,this.options_.position)}const t=this.collector_,s=this.overlay_,n=xt([Ie(ze),{_type:"get_world"}],(n,i)=>{t.pushFrame(n.delta);const o=e.getResource(za);o.fps=t.getFps(),o.frameTimeMs=t.getFrameTimeMs(),o.entityCount=i.entityCount();const r=e.getSystemTimings();if(r){const e=new Map(r);e.delete($a),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=Ln.getStats();o.drawCalls=l.drawCalls,o.triangles=l.triangles,o.sprites=l.sprites,o.text=l.text,o.spine=l.spine,o.meshes=l.meshes,o.culled=l.culled,s?.update(o)},{name:$a});e.addSystemToSchedule(gt.Last,n)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const Oa=new La;class Wa{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,s)=>{const n=new Image;n.onload=()=>{const e=document.createElement("canvas");e.width=n.width,e.height=n.height;const s=e.getContext("2d");s.drawImage(n,0,0);const i=s.getImageData(0,0,n.width,n.height);t({width:n.width,height:n.height,pixels:new Uint8Array(i.data.buffer)})},n.onerror=s,n.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return function(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}(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}async function Ha(e,t){try{const s=function(e){const t=atob(e),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s}(t);return await e({instantiateWasm:(e,t)=>(WebAssembly.instantiate(s.buffer,e).then(e=>{t(e.instance,e.module)}),{})})}catch(e){return null}}async function Xa(e){const{app:t,module:s,assets:n,sceneData:i,sceneName:o}=e,r=t.getResource(Ws);r&&(r.registerEmbeddedAssets(n),r.setEmbeddedOnly(!0));const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await Ha(ESSpineModule,e);return t||console.warn("Spine module not available"),t}(e.spineWasmBase64):null,l=e.physicsWasmBase64?await async function(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await Ha(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new Wa(n);await qr({app:t,module:s,provider:c,scenes:[{name:o,data:i}],firstScene:o,spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()}const ja=[Ni,ro,mo,Lo,qo,To,Qo,nr,cr,Xo,ko,hr,mr,xr,Sr,Ar,Ir],Ya=[...ja,ba,Ra];function Na(e,t){return function(e,t){const s=Zn.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),an(e),$t(e),Mn(e),An(e),$n(e),Wn(e);const i=new jn;s.setPipeline(i);let o=u();const r=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=oi(e,n,t,i));const r=s.getResource(Rt);if(o.length>0){const e=o[0],s=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(s.x*t),r.vpY=Math.round((1-s.y-s.h)*i),r.vpW=Math.round(s.w*t),r.vpH=Math.round(s.h*i),r.screenW=t,r.screenH=i,r.worldLeft=e.cameraX-e.halfW,r.worldRight=e.cameraX+e.halfW,r.worldBottom=e.cameraY-e.halfH,r.worldTop=e.cameraY+e.halfH,r.valid=!0}else r.valid=!1}s.insertResource(Rt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=r();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(n);if(c>=0){const e=n.getCanvas(c).backgroundColor;Ln.setClearColor(e.x,e.y,e.z,e.w)}const d=(u()-o)/1e3;let h;if(Ln.resize(t,l),kn.isInitialized()&&kn.getPassCount()>0&&!kn.isBypassed()&&kn.resize(t,l),s.hasResource(Gn)){const e=s.getResource(Gn).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=oi(e,n,t,l,s.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:n},viewProjection:ti,width:t,height:l,elapsed:d});else{for(const e of f){const s=e.viewportRect,o=Math.round(s.x*t),r=Math.round((1-s.y-s.h)*l),a=Math.round(s.w*t),c=Math.round(s.h*l);i.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:d})}Ln.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(gt.First,l),s.addSystemToSchedule(gt.Last,c),s.addPlugin(Xs),s.addPlugin(en),s.addPlugin(At),s.addPlugin(Qn),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Ya,...t})}e=w;export{Je as Added,va as AnimationPlugin,Zn as App,Hs as AssetPlugin,js as AssetRefCounter,Os as AssetServer,Ws as Assets,Gt as AsyncCache,Sa as AttenuationModel,rs as Audio,p as AudioBus,Ca as AudioListener,m as AudioMixer,Aa as AudioPlugin,_ as AudioPool,Ea as AudioSource,we as BitmapText,It as BlendMode,Ce as BodyType,Pe as BoxCollider,ho as Button,co as ButtonState,pe as Camera,me as Canvas,Ee as CapsuleCollider,Qe as Changed,ye as Children,Te as CircleCollider,le as ClearFlags,at as Commands,ct as CommandsInstance,v as DEFAULT_DESIGN_HEIGHT,x as DEFAULT_DESIGN_WIDTH,A as DEFAULT_FALLBACK_DT,I as DEFAULT_FIXED_TIMESTEP,P as DEFAULT_FONT_FAMILY,T as DEFAULT_FONT_SIZE,R as DEFAULT_GRAVITY,E as DEFAULT_LINE_HEIGHT,C as DEFAULT_MAX_DELTA_TIME,b as DEFAULT_PIXELS_PER_UNIT,k as DEFAULT_SPINE_SKIN,M as DEFAULT_SPRITE_SIZE,S as DEFAULT_TEXT_CANVAS_SIZE,wn as DataType,Jo as DragPlugin,Ko as DragState,Go as Draggable,hn as Draw,vr as Dropdown,br as DropdownPlugin,ca as EasingType,lt as EntityCommands,pt as EventReader,_t as EventReaderInstance,ut as EventRegistry,ft as EventWriter,mt as EventWriterInstance,pi as FillDirection,Bo as FillMethod,zo as FillOrigin,Ro as FocusManager,Ao as FocusManagerState,dr as FocusPlugin,Co as Focusable,Ua as FrameHistory,Xn as GLDebug,En as Geometry,yt as GetWorld,$ as INVALID_ENTITY,L as INVALID_FONT,O as INVALID_MATERIAL,D as INVALID_TEXTURE,Uo as Image,Do as ImagePlugin,Fo as ImageType,Et as Input,Ct as InputPlugin,Tt as InputState,ao as Interactable,Cr as LayoutGroupPlugin,_r as ListView,wr as ListViewPlugin,he as LocalTransform,Zr as LogLevel,ta as Logger,ua as LoopMode,Ot as Material,Kt as MaterialLoader,Ge as Mut,ve as Name,ge as Parent,Or as Physics,Br as PhysicsEvents,Dr as PhysicsPlugin,kn as PostProcess,Js as PrefabServer,Qs as Prefabs,Zs as PrefabsPlugin,Jr as PreviewPlugin,Yo as ProgressBar,jo as ProgressBarDirection,Vo as ProgressBarPlugin,ae as ProjectionType,nt as Query,it as QueryInstance,ot as Removed,rt as RemovedQueryInstance,jn as RenderPipeline,Bn as RenderStage,Qr as RenderTexture,Ln as Renderer,Ie as Res,ke as ResMut,Me as RigidBody,F as RuntimeConfig,ur as SafeArea,pr as SafeAreaPlugin,ce as ScaleMode,Gn as SceneManager,qn as SceneManagerState,be as SceneOwner,gt as Schedule,Zo as ScrollView,sr as ScrollViewPlugin,qt as ShaderSources,or as Slider,ir as SliderDirection,lr as SliderPlugin,xe as SpineAnimation,fe as Sprite,is as SpriteAnimator,za as Stats,Da as StatsCollector,Fa as StatsOverlay,La as StatsPlugin,Pt as SystemRunner,Hi as Text,Li as TextAlign,Eo as TextInput,Io as TextInputPlugin,Wi as TextOverflow,Yi as TextPlugin,Xi as TextRenderer,Oi as TextVerticalAlign,ze as Time,Oo as Toggle,Ho as TogglePlugin,de as Transform,xa as Tween,fa as TweenHandle,ha as TweenState,da as TweenTarget,Rt as UICameraInfo,uo as UIEventQueue,fo as UIEvents,lo as UIInteraction,Po as UIInteractionPlugin,po as UILayoutPlugin,Gi as UIMask,oo as UIMaskPlugin,_i as UIRect,Rr as UIRenderOrderPlugin,_e as Velocity,Gr as WebAssetProvider,qe as World,ue as WorldTransform,St as addStartupSystem,bt as addSystem,Mt as addSystemToSchedule,ba as animationPlugin,U as applyBuildRuntimeConfig,Si as applyDirectionalFill,B as applyRuntimeConfig,Xs as assetPlugin,Ra as audioPlugin,Pa as calculateAttenuation,Ta as calculatePanning,ns as clearAnimClips,yn as clearDrawCallbacks,Z as clearUserComponents,j as color,xi as computeFillAnchors,bi as computeFillSize,vi as computeHandleAnchors,mi as computeUIRectLayout,io as createMaskProcessor,Vr as createRuntimeSceneConfig,Na as createWebApp,oa as debug,Ba as defaultFrameStats,K as defineComponent,dt as defineEvent,Re as defineResource,xt as defineSystem,J as defineTag,Qo as dragPlugin,Sr as dropdownPlugin,la as error,Jt as extractAnimClipTexturePaths,bs as findEntityByName,ei as flushPendingSystems,hr as focusPlugin,Rs as getAddressableType,Is as getAddressableTypeByEditorType,Fs as getAllAssetExtensions,ss as getAnimClip,$s as getAssetMimeType,Cs as getAssetTypeEntry,oe as getComponent,ds as getComponentAssetFieldDescriptors,cs as getComponentAssetFields,Se as getComponentDefaults,ps as getComponentEntityFields,hs as getComponentSpineFieldDescriptor,zs as getCustomExtensions,As as getEditorType,na as getLogger,t as getPlatform,n as getPlatformType,Q as getUserComponent,Us as getWeChatPackOptions,Lo as imagePlugin,ra as info,an as initDrawAPI,Wn as initGLDebugAPI,Mn as initGeometryAPI,$t as initMaterialAPI,Xa as initPlayableRuntime,An as initPostProcessAPI,$n as initRendererAPI,qr as initRuntime,_a as initTweenAPI,At as inputPlugin,Ns as instantiatePrefab,Ki as intersectRects,Ji as invertMatrix4,se as isBuiltinComponent,Ds as isCustomExtension,wo as isEditor,ks as isKnownAssetExtension,s as isPlatformInitialized,bo as isPlayMode,xo as isRuntime,kt as isTextureRef,i as isWeChat,o as isWeb,Ar as layoutGroupPlugin,xr as listViewPlugin,xs as loadComponent,Fr as loadPhysicsModule,Nr as loadRuntimeScene,gs as loadSceneData,ys as loadSceneWithAssets,Bs as looksLikeAssetPath,Qt as parseAnimClipData,r as platformFetch,c as platformFileExists,d as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,so as pointInOBB,Zi as pointInWorldRect,en as prefabsPlugin,qo as progressBarPlugin,Y as quat,es as registerAnimClip,ie as registerComponent,ls as registerComponentAssetFields,fs as registerComponentEntityFields,_n as registerDrawCallback,Ys as registerEmbeddedAssets,Vt as registerMaterialCallback,ms as remapEntityFields,mr as safeAreaPlugin,Qn as sceneManagerPlugin,Qi as screenToWorld,nr as scrollViewPlugin,yo as setEditorMode,yr as setListViewRenderer,ia as setLogLevel,vo as setPlayMode,Oe as setWasmErrorHandler,ln as shutdownDrawAPI,Hn as shutdownGLDebugAPI,Pn as shutdownGeometryAPI,Dt as shutdownMaterialAPI,Rn as shutdownPostProcessAPI,Dn as shutdownRendererAPI,ga as shutdownTweenAPI,cr as sliderPlugin,os as spriteAnimatorSystemUpdate,Oa as statsPlugin,Ii as syncFillSpriteSize,ko as textInputPlugin,Ni as textPlugin,Ls as toBuildPath,Xo as togglePlugin,kr as transitionTo,To as uiInteractionPlugin,mo as uiLayoutPlugin,ro as uiMaskPlugin,ja as uiPlugins,Ir as uiRenderOrderPlugin,ts as unregisterAnimClip,ee as unregisterComponent,gn as unregisterDrawCallback,vs as updateCameraAspectRatio,W as vec2,H as vec3,X as vec4,aa as warn,Kn as wrapSceneSystem};+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function s(){return null!==e}function n(){return e?.name??null}function i(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function r(e,s){return t().fetch(e,s)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,s){return t().instantiateWasm(e,s)}function h(e,s){return t().createCanvas(e,s)}function d(){return t().now()}function f(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}class p{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,t.volume??1)),this.muted_=t.muted??!1,this.gainNode_.gain.value=this.muted_?0:this.volume_}get name(){return this.name_}get node(){return this.gainNode_}get volume(){return this.volume_}set volume(e){this.volume_=Math.max(0,Math.min(1,e)),this.muted_||this.gainNode_.gain.setTargetAtTime(this.volume_,this.gainNode_.context.currentTime,.015)}get muted(){return this.muted_}set muted(e){this.muted_=e,this.gainNode_.gain.setTargetAtTime(e?0:this.volume_,this.gainNode_.context.currentTime,.015)}connect(e){e instanceof p?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class m{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new p(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new p(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new p(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new p(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new p(e,{name:"voice",volume:t.voiceVolume??1}),this.master.addChild(this.voice),this.buses_.set("master",this.master),this.buses_.set("music",this.music),this.buses_.set("sfx",this.sfx),this.buses_.set("ui",this.ui),this.buses_.set("voice",this.voice)}getBus(e){return this.buses_.get(e)}createBus(e){const t=new p(this.context_,e),s=e.parent?this.buses_.get(e.parent):this.master;return s&&s.addChild(t),this.buses_.set(e.name,t),t}}class _{constructor(e,t=16){this.pool_=[],this.activeCount_=0,this.context_=e;for(let e=0;e<t;e++)this.pool_.push(this.createNode())}createNode(){const e=this.context_.createGain(),t=this.context_.createStereoPanner();return e.connect(t),{gain:e,panner:t,source:null,inUse:!1,startTime:0}}acquire(){let e=this.pool_.find(e=>!e.inUse);return e||(e=this.createNode(),this.pool_.push(e)),e.inUse=!0,e.startTime=this.context_.currentTime,e.gain.gain.value=1,e.panner.pan.value=0,this.activeCount_++,e}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}}class g{constructor(e,t,s,n,i,o,r){this.playing_=!0,this.stopped_=!1,this.pausedAt_=0,this.id=e,this.source_=t,this.buffer_=s,this.poolNode_=n,this.pool_=i,this.context_=o,this.startOffset_=r,this.startedAt_=o.currentTime,this.playbackRate_=t.playbackRate.value,this.loop_=t.loop,this.bindOnEnded_(t)}bindOnEnded_(e){e.onended=()=>{this.stopped_||this.loop_||(this.playing_=!1,this.stopped_=!0,this.pool_.release(this.poolNode_),this.onEnd?.())}}stop(){this.stopped_||(this.stopped_=!0,this.playing_=!1,this.source_.onended=null,this.pool_.release(this.poolNode_))}pause(){if(!this.playing_||this.stopped_)return;this.playing_=!1;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;this.pausedAt_=this.startOffset_+e,this.loop_&&this.buffer_.duration>0&&(this.pausedAt_=this.pausedAt_%this.buffer_.duration),this.source_.onended=null;try{this.source_.stop()}catch(e){}this.source_.disconnect()}resume(){if(this.playing_||this.stopped_)return;this.playing_=!0;const e=this.context_.createBufferSource();e.buffer=this.buffer_,e.loop=this.loop_,e.playbackRate.value=this.playbackRate_,e.connect(this.poolNode_.gain),this.source_=e,this.poolNode_.source=e,this.startOffset_=this.pausedAt_,this.startedAt_=this.context_.currentTime,this.bindOnEnded_(e),e.start(0,this.pausedAt_)}setVolume(e){this.poolNode_.gain.gain.value=e}setPan(e){this.poolNode_.panner.pan.value=e}setLoop(e){this.loop_=e,this.source_.loop=e}setPlaybackRate(e){this.playbackRate_=e,this.playing_&&(this.source_.playbackRate.value=e)}get isPlaying(){return this.playing_}get currentTime(){if(this.stopped_)return 0;if(!this.playing_)return this.pausedAt_;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;return this.startOffset_+e}get duration(){return this.buffer_.duration}}class y{constructor(){this.name="WebAudio",this.context_=null,this.mixer_=null,this.pool_=null,this.buffers_=new Map,this.urlToId_=new Map,this.loadingUrls_=new Map,this.nextBufferId_=0,this.nextHandleId_=0,this.resumeHandler_=null}get mixer(){return this.mixer_}get isReady(){return"running"===this.context_?.state}async initialize(e={}){if(this.context_=new AudioContext,this.mixer_=new m(this.context_,e.mixerConfig),this.pool_=new _(this.context_,e.initialPoolSize),"suspended"===this.context_.state){const e=()=>{this.context_.resume(),document.removeEventListener("touchstart",e),document.removeEventListener("mousedown",e),document.removeEventListener("keydown",e),this.resumeHandler_=null};document.addEventListener("touchstart",e),document.addEventListener("mousedown",e),document.addEventListener("keydown",e),this.resumeHandler_=e}}async ensureResumed(){this.context_&&"suspended"===this.context_.state&&await this.context_.resume()}async loadBuffer(e){if(!this.context_)throw new Error("AudioContext not initialized");const t=this.urlToId_.get(e);if(void 0!==t&&this.buffers_.has(t)){return{id:t,duration:this.buffers_.get(t).duration}}const s=this.loadingUrls_.get(e);if(s)return s;const n=this.doLoadBuffer_(e);this.loadingUrls_.set(e,n);try{return await n}finally{this.loadingUrls_.delete(e)}}async doLoadBuffer_(e){const s=await t().readFile(e);let n;try{n=await this.context_.decodeAudioData(s)}catch(t){throw new Error(`Failed to decode audio ${e}: ${t.message}`)}const i=++this.nextBufferId_;return this.buffers_.set(i,n),this.urlToId_.set(e,i),{id:i,duration:n.duration}}unloadBuffer(e){this.buffers_.delete(e.id)}play(e,t){if(!this.context_||!this.pool_||!this.mixer_)throw new Error("Audio system not initialized");const s=this.buffers_.get(e.id);if(!s)throw new Error(`Buffer ${e.id} not found`);const n=this.pool_.acquire(),i=this.context_.createBufferSource();i.buffer=s,i.loop=t.loop??!1,i.playbackRate.value=t.playbackRate??1,i.connect(n.gain),n.source=i,n.gain.gain.value=t.volume??1,n.panner.pan.value=t.pan??0;const o=t.bus??"sfx",r=this.mixer_.getBus(o)??this.mixer_.sfx;n.panner.connect(r.node);const a=t.startOffset??0;i.start(0,a);const l=++this.nextHandleId_;return new g(l,i,s,n,this.pool_,this.context_,a)}suspend(){this.context_?.suspend()}resume(){this.context_?.resume()}dispose(){this.resumeHandler_&&(document.removeEventListener("touchstart",this.resumeHandler_),document.removeEventListener("mousedown",this.resumeHandler_),document.removeEventListener("keydown",this.resumeHandler_),this.resumeHandler_=null),this.pool_=null,this.mixer_=null,this.buffers_.clear(),this.urlToId_.clear(),this.loadingUrls_.clear(),this.context_?.close(),this.context_=null}}const w=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const s=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),n={};return s.headers.forEach((e,t)=>{n[t]=e}),{ok:s.ok,status:s.status,statusText:s.statusText,headers:n,json:()=>s.json(),text:()=>s.text(),arrayBuffer:()=>s.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async loadImagePixels(e){const t=this.createImage();await new Promise((s,n)=>{t.crossOrigin="anonymous",t.onload=()=>s(),t.onerror=()=>n(new Error(`Failed to load image: ${e}`)),t.src=e});const s=this.createCanvas(t.width,t.height).getContext("2d");s.drawImage(t,0,0);const n=s.getImageData(0,0,t.width,t.height);return{width:t.width,height:t.height,pixels:new Uint8Array(n.data.buffer)}}async instantiateWasm(e,t){let s;s="string"==typeof e?await this.readFile(e):e;const n=await WebAssembly.instantiate(s,t);return{instance:n.instance,module:n.module}}createImage(){return new Image}createCanvas(e,t){let s;return s="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),s.width=e,s.height=t,s}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const s=t??document.querySelector("canvas")??document.body,n=t=>e.onKeyDown(t.code),i=t=>e.onKeyUp(t.code),o=t=>{const s=t;e.onPointerMove(s.offsetX,s.offsetY)},r=t=>{const s=t;e.onPointerDown(s.button,s.offsetX,s.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerDown(0,n.clientX-t.left,n.clientY-t.top)}},c=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerMove(n.clientX-t.left,n.clientY-t.top)}},u=()=>{e.onPointerUp(0)},h=t=>{const s=t;let n=s.deltaX,i=s.deltaY;1===s.deltaMode?(n*=16,i*=16):2===s.deltaMode&&(n*=window.innerWidth,i*=window.innerHeight),e.onWheel(n,i)};document.addEventListener("keydown",n),document.addEventListener("keyup",i),s.addEventListener("mousemove",o),s.addEventListener("mousedown",r),document.addEventListener("mouseup",a),s.addEventListener("touchstart",l),s.addEventListener("touchmove",c),s.addEventListener("touchend",u),s.addEventListener("wheel",h),this.inputCleanup_=()=>{document.removeEventListener("keydown",n),document.removeEventListener("keyup",i),s.removeEventListener("mousemove",o),s.removeEventListener("mousedown",r),document.removeEventListener("mouseup",a),s.removeEventListener("touchstart",l),s.removeEventListener("touchmove",c),s.removeEventListener("touchend",u),s.removeEventListener("wheel",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new y}},x=1920,v=1080,b=100,S=512,M={x:100,y:100},P="Arial",T=24,E=1.2,C=.5,R=1/60,A={x:0,y:-9.81},I=1/60,k="default",F={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function B(e){e.Text&&(e.Text._default.fontFamily=F.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=F.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=F.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=F.canvasMatchWidthOrHeight)}const z={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function U(e,t){if(void 0!==t.maxDeltaTime&&(F.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(F.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(F.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(F.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(F.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");F.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&(F.canvasScaleMode=z[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(F.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight)}const $=0,D=4294967295,O=4294967295,L=0,W=(e=0,t=0)=>({x:e,y:t}),H=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),N=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),X=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),j=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});function Y(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(Y);const t={};for(const s in e)t[s]=Y(e[s]);return t}let V=0;function q(e,t){const s=++V,n=function(e){for(const t in e){const s=e[t];if(null!==s&&"object"==typeof s)return!0}return!1}(t);return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>n?e?{...Y(t),...e}:Y(t):e?{...t,...e}:{...t}}}function G(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function K(e,t){const s=ne.get(e)??G().get(e);if(s)return s;const n=q(e,t);return G().set(e,n),ne.set(e,n),te(e,t,!1),n}function J(e){const t=ne.get(e)??G().get(e);if(t)return t;const s=q(e,{});return G().set(e,s),ne.set(e,s),te(e,{},!0),s}function Q(e){return G().get(e)}function Z(){const e=G();for(const t of e.keys())ne.delete(t);e.clear()}function ee(e){G().delete(e),ne.delete(e)}function te(e,t,s){const n=globalThis;n.__esengine_registerComponent&&n.__esengine_registerComponent(e,t,s)}function se(e){return!0===e._builtin}const ne=new Map;function ie(e,t){ne.set(e,t)}function oe(e){return ne.get(e)??Q(e)}function re(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return ne.set(e,s),s}const ae={Perspective:0,Orthographic:1},le={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ce={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},ue=re("Transform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}}),he=ue,de=ue,fe=re("Sprite",{texture:D,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),pe=re("Camera",{projectionType:ae.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:le.ColorAndDepth}),me=re("Canvas",{designResolution:{x:x,y:v},pixelsPerUnit:100,scaleMode:ce.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),_e=re("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),ge=re("Parent",{entity:0}),ye=re("Children",{entities:[]}),we=re("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:O,enabled:!0}),xe=re("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),ve=K("Name",{value:""}),be=K("SceneOwner",{scene:"",persistent:!1});function Se(e){const t=oe(e);return t?Y(t._default):null}const Me=re("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Pe=re("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Te=re("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ee=re("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ce={Static:0,Kinematic:1,Dynamic:2};let Re=0;function Ae(e,t){const s=++Re;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function Ie(e){return{_type:"res",_resource:e}}function ke(e){return{_type:"res_mut",_resource:e}}class Fe{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class Be{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new Fe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const ze=Ae({delta:0,elapsed:0,frameCount:0},"Time");function Ue(e,t,s){const n=[];for(const[e,i]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const s=$e(t[e]),o=$e(i);"null"!==s&&"undefined"!==s&&(s!==o&&null!=i&&n.push({field:e,expected:s,actual:o,value:i}))}return n}function $e(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function De(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}let Oe=null;function Le(e){Oe=e}function We(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Oe&&Oe(e,t)}function He(e){let t=!1;for(const s of Object.keys(e)){const n=e[s];if(null!=n&&"object"==typeof n&&!Array.isArray(n)){if("r"in n&&"g"in n&&"b"in n&&"a"in n&&!("x"in n)){t=!0;break}}}if(!t)return e;const s={};for(const t of Object.keys(e)){const n=e[t];if(null==n||"object"!=typeof n||Array.isArray(n))s[t]=n;else{const e=n;s[t]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:n}}return s}let Ne=1;const Xe=new WeakMap;function je(e){let t=Xe.get(e);return void 0===t&&(t=Ne++,Xe.set(e,t)),t}const Ye=[];function Ve(e,t=[],s=[]){Ye.length=0;for(const t of e)Ye.push(je(t));Ye.sort((e,t)=>e-t);let n=Ye.join(",");if(t.length>0){Ye.length=0;for(const e of t)Ye.push(je(e));Ye.sort((e,t)=>e-t),n+="|+"+Ye.join(",")}if(s.length>0){Ye.length=0;for(const e of s)Ye.push(je(e));Ye.sort((e,t)=>e-t),n+="|-"+Ye.join(",")}return n}class qe{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw We(e,"spawn"),e}else e=++this.nextEntityId_;let t=0;if(this.module_&&this.cppRegistry_)try{t=this.module_.registry_getGeneration(this.cppRegistry_,e)}catch{}else t=++this.nextGeneration_;this.entities_.set(e,t),this.worldVersion_++;for(const t of this.spawnCallbacks_)try{t(e)}catch{}return e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch{}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){We(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t){this.tsStorage_.get(s)?.delete(e),this.componentAddedTicks_.get(s)?.delete(e),this.componentChangedTicks_.get(s)?.delete(e);let t=this.componentRemovedBuffer_.get(s);t||(t=[],this.componentRemovedBuffer_.set(s,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){We(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){We(t,`removeParent(entity=${e})`)}}insert(e,t,s){return se(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}set(e,t,s){if(se(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,He(s))}catch(s){We(s,`set(${t._name}, entity=${e})`)}this.recordChangedTick_(t,e)}else this.getStorage(t).set(e,s),this.recordChangedTick_(t,e)}get(e,t){return se(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return se(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(se(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return We(s,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");se(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_,n=s[`add${e}`],i=s[`get${e}`],o=s[`has${e}`],r=s[`remove${e}`];if("function"!=typeof n||"function"!=typeof i||"function"!=typeof o||"function"!=typeof r)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:n.bind(s),get:i.bind(s),has:o.bind(s),remove:r.bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Ue(t._name,t._default,n);if(e.length>0)throw new Error(De(t._name,e))}const i={...t._default,...n};let o=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(t._cppName);o=!s.has(e),s.add(e,He(i))}catch(s){We(s,`insertBuiltin(${t._name}, entity=${e})`)}return o&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let s=!1;for(const n of Object.keys(t)){const i=t[n];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){const t=e[n];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){s=!0;break}}}if(!s)return e;const n={};for(const s of Object.keys(e)){const i=e[s],o=t[s];if(null==i||"object"!=typeof i||Array.isArray(i)||null==o||"object"!=typeof o||Array.isArray(o))n[s]=i;else{const e=i,t=o;n[s]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:i}}return n}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(s){return We(s,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(s){return We(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){We(s,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++}}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 i=Ue(t._name,t._default,e);if(i.length>0)throw new Error(De(t._name,i));n=e}const i=t.create(n),o=this.getStorage(t),r=!o.has(e);o.set(e,i);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}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.recordRemovedTick_(t,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}getComponentTypes(e){const t=new Set;for(const[s,n]of this.builtinMethodCache_)try{n.has(e)&&t.add(s)}catch{}if(this.cppRegistry_)for(const[s,n]of ne)if(se(n)&&!t.has(s))try{this.getBuiltinMethods(n._cppName).has(e)&&t.add(s)}catch{}const s=this.entityComponents_.get(e);if(s){const e=G();for(const n of s)for(const[s,i]of e)if(i._id===n){t.add(s);break}}return Array.from(t)}getEntitiesWithComponents(e,t=[],s=[],n){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();const i=n??Ve(e,t,s),o=this.queryCache_.get(i);if(o&&o.version===this.worldVersion_)return o.result;let r=null,a=1/0;for(const t of e)if(!se(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<a&&(a=s,r=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=r?r.keys():this.entities_.keys();for(const n of c){let i=!0;for(const t of e)if(!this.has(n,t)){i=!1;break}if(i)for(const e of t)if(!this.has(n,e)){i=!1;break}if(i)for(const e of s)if(this.has(n,e)){i=!1;break}i&&l.push(n)}return this.queryCache_.set(i,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,s){const n=this.componentAddedTicks_.get(t._id);if(!n)return!1;const i=n.get(e);return void 0!==i&&i>s}isChangedSince(e,t,s){const n=this.componentChangedTicks_.get(t._id);if(!n)return!1;const i=n.get(e);return void 0!==i&&i>s}getRemovedEntitiesSince(e,t){const s=this.componentRemovedBuffer_.get(e._id);if(!s)return[];const n=[];for(const e of s)e.tick>t&&n.push(e.entity);return n}cleanRemovedBuffer(e){for(const[t,s]of this.componentRemovedBuffer_){let n=0;for(let t=0;t<s.length;t++)s[t].tick>=e&&(s[n++]=s[t]);s.length=n,0===n&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let s=this.componentAddedTicks_.get(e._id);s||(s=new Map,this.componentAddedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordChangedTick_(e,t){let s=this.componentChangedTicks_.get(e._id);s||(s=new Map,this.componentChangedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordRemovedTick_(e,t){let s=this.componentRemovedBuffer_.get(e._id);s||(s=[],this.componentRemovedBuffer_.set(e._id,s)),s.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function Ge(e){return{_type:"mut",_component:e}}function Ke(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Je(e){return{_filterType:"added",_component:e}}function Qe(e){return{_filterType:"changed",_component:e}}function Ze(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function et(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function tt(e){return Ke(e)||Ze(e)||et(e)?e._component:e}function st(e,t=[],s=[]){const n=[],i=[],o=[];return e.forEach((e,t)=>{Ke(e)&&n.push(t),Ze(e)?i.push({index:t,component:e._component}):et(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s,_addedFilters:i,_changedFilters:o,with:(...n)=>st(e,[...t,...n],s),without:(...n)=>st(e,t,[...s,...n])}}function nt(...e){return st(e)}class it{constructor(e,t,s=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=s,this.actualComponents_=t._components.map(tt),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=Ve(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:s}=this.descriptor_;if(0===t.length&&0===s.length)return!0;const n=this.lastRunTick_;for(const s of t)if(!this.world_.isAddedSince(e,s.component,n))return!1;for(const t of s)if(!this.world_.isChangedSince(e,t.component,n))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),n=t.length,i=e.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const u of s)if(!o||this.passesChangeFilters_(u)){if(null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}r[0]=u;for(let e=0;e<n;e++)r[e+1]=this.world_.get(u,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];c=u}yield r}}finally{if(this.world_.endIteration(),null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function ot(e){return{_type:"removed",_component:e}}class rt{constructor(e,t,s){this.world_=e,this.component_=t,this.lastRunTick_=s}*[Symbol.iterator](){yield*this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}isEmpty(){return 0===this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_).length}toArray(){return this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}}function at(){return{_type:"commands"}}class lt{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=se(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 ct{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new lt(this,null);return this.spawned_.push(e),e}entity(e){return new lt(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"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}function ut(e){return{_id:Symbol(`Event_${e}`),_name:e}}class ht{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(e){this.writeBuffer_.push(e)}getReadBuffer(){return this.readBuffer_}swap(){const e=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=e,this.writeBuffer_.length=0}}class dt{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new ht)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new ht,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function ft(e){return{_type:"event_writer",_event:e}}function pt(e){return{_type:"event_reader",_event:e}}class mt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class _t{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var gt;function yt(){return{_type:"get_world"}}!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(gt||(gt={}));let wt=0;function xt(e,t,s){const n=++wt;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function vt(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function bt(e){vt().push({schedule:gt.Update,system:e})}function St(e){vt().push({schedule:gt.Startup,system:e})}function Mt(e,t){vt().push({schedule:e,system:t})}class Pt{constructor(e,t,s){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=s??null}setTimingEnabled(e){this.timings_=e?new Map:null}getTimings(){return this.timings_}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);const s=this.timings_?performance.now():0;try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof ct&&t[e].flush()}finally{this.timings_&&this.timings_.set(e._name,performance.now()-s),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new it(this.world_,e,this.currentLastRunTick_);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new ct(this.world_,this.resources_);case"event_writer":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new mt(s)}case"event_reader":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new _t(s)}case"removed":{const t=e;return new rt(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class Tt{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 Et=Ae(new Tt,"Input");class Ct{constructor(e){this.target_=e??null}build(e){const s=new Tt;e.insertResource(Et,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(gt.Last,xt([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Rt=new Ct,At=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,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var It;function kt(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"}(It||(It={}));let Ft=null,Bt=null,zt=1;const Ut=new Map;function $t(e){Ft=e,Bt=e.getResourceManager(),Vt()}function Dt(){0!==Ht&&Ft&&(Ft._free(Ht),Ht=0),Ut.clear(),zt=1,Wt=!1,Xt.clear(),jt=null,Bt=null,Ft=null}function Ot(){if(!Bt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Bt}const Lt={createShader:(e,t)=>Ot().createShader(e,t),releaseShader(e){e>0&&Ot().releaseShader(e)},create(e){const t=zt++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??It.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 Ut.set(t,s),t},get:e=>Ut.get(e),setUniform(e,t,s){const n=Ut.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0,Ft?.invalidateMaterialCache(e))},getUniform(e,t){const s=Ut.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ut.get(e);s&&(s.blendMode=t,Ft?.invalidateMaterialCache(e))},getBlendMode(e){const t=Ut.get(e);return t?.blendMode??It.Normal},setDepthTest(e,t){const s=Ut.get(e);s&&(s.depthTest=t,Ft?.invalidateMaterialCache(e))},getShader(e){const t=Ut.get(e);return t?.shader??0},release(e){Ut.delete(e),Ft?.invalidateMaterialCache(e)},isValid:e=>Ut.has(e),releaseAll(){Ut.clear(),Ft?.clearMaterialCache()},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??It.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ut.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=zt++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ut.set(s,n),s},toAssetData(e,t){const s=Ut.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=Ut.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Wt=!1,Ht=0;const Nt=16384,Xt=new Map;let jt=null;function Yt(e){const t=(0===Ht&&Ft&&(Ht=Ft._malloc(Nt)),Ht);if(0===t||!Ft)return{ptr:0,count:0};let s=0,n=0;const i=Ft.HEAPU8,o=Ft.HEAPU32,r=Ft.HEAPF32;for(const[a,l]of e){if(kt(l))continue;let e=Xt.get(a);e||(jt||(jt=new TextEncoder),e=jt.encode(a),Xt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(s+(4+u+4+16)>Nt){console.warn(`[ESEngine] Material uniform buffer full (${s}/${Nt} bytes), skipping remaining uniforms`);break}o[t+s>>2]=c,s+=4,i.set(e,t+s),s+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+s>>2]=h,s+=4;for(let e=0;e<4;e++)r[t+s>>2]=d[e],s+=4;n++}return{ptr:t,count:n}}function Vt(){if(!Ft||Wt)return;Ft.materialDataProvider=(e,t,s,n,i)=>{const o=Ut.get(e);if(!o)return Ft.HEAPU32[t>>2]=0,Ft.HEAPU32[s>>2]=0,Ft.HEAPU32[n>>2]=0,void(Ft.HEAPU32[i>>2]=0);Ft.HEAPU32[t>>2]=o.shader,Ft.HEAPU32[s>>2]=o.blendMode;const{ptr:r,count:a}=Yt(o.uniforms);Ft.HEAPU32[n>>2]=r,Ft.HEAPU32[i>>2]=a},Wt=!0}const qt={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 Gt{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 i=this.pending_.get(e);if(i&&!i.aborted)return i.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),i=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,i),this.pending_.delete(e),i})(),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 Kt{constructor(e,t=""){this.cache_=new Gt,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&&(Lt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Lt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const s=await l(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const i=this.resolveShaderPath(e,n.shader),o=await this.shaderLoader_.load(i);return{handle:Lt.createFromAsset(n,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 s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}function Jt(e){const t=new Set;for(const s of e.frames)s.texture&&t.add(s.texture);return Array.from(t)}function Qt(e,t,s){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>{const t={texture:s.get(e.texture)??0};if(e.atlasFrame){const s=e.atlasFrame;t.uvOffset={x:s.x/s.pageWidth,y:1-(s.y+s.height)/s.pageHeight},t.uvScale={x:s.width/s.pageWidth,y:s.height/s.pageHeight}}return t})}}const Zt=new Map;function es(e){Zt.set(e.name,e)}function ts(e){Zt.delete(e)}function ss(e){return Zt.get(e)}function ns(){Zt.clear()}const is=K("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function os(e,t){const s=e.getEntitiesWithComponents([is]);for(const n of s){const s=e.get(n,is);if(!s.enabled||!s.playing||!s.clip)continue;const i=Zt.get(s.clip);if(!i||0===i.frames.length)continue;const o=1/(i.fps*s.speed),r=0===s.frameTimer&&0===s.currentFrame;s.frameTimer+=t;let a=r;if(s.frameTimer>=o&&(s.frameTimer-=o,s.currentFrame++,s.currentFrame>=i.frames.length&&(s.loop&&i.loop?s.currentFrame=0:(s.currentFrame=i.frames.length-1,s.playing=!1)),a=!0),a&&e.has(n,fe)){const t=i.frames[s.currentFrame],o=e.get(n,fe);o.texture=t.texture,t.uvOffset&&(o.uvOffset=t.uvOffset,o.uvScale=t.uvScale),e.insert(n,fe,o)}a&&e.insert(n,is,s)}}class rs{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null,this.bgmVolume_=1,this.disposed_=!1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}static async preload(e){if(this.bufferCache_.has(e))return;const t=await this.backend_.loadBuffer(e);this.bufferCache_.set(e,t)}static async preloadAll(e){await Promise.all(e.map(e=>this.preload(e)))}static playSFX(e,t){const s={bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0},n=this.bufferCache_.get(e);if(!n){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const n=this.bufferCache_.get(e);n&&t.resolve(this.backend_.play(n,s))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(n,s)}static playBGM(e,t){const s=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const s=t?.volume??1,n=this.bgmVolume_;this.bgmVolume_=s,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,n):this.bgmHandle_&&this.bgmHandle_.stop();const i=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:i?0:s,loop:!0}),i&&this.fadeIn(this.bgmHandle_,i,s)},n=this.bufferCache_.get(e);n?s(n):this.preload(e).then(()=>{if(this.disposed_)return;const t=this.bufferCache_.get(e);t&&s(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else this.bgmHandle_.stop(),this.bgmHandle_=null}static setMasterVolume(e){this.mixer_&&(this.mixer_.master.volume=e)}static setMusicVolume(e){this.mixer_&&(this.mixer_.music.volume=e)}static setSFXVolume(e){this.mixer_&&(this.mixer_.sfx.volume=e)}static setUIVolume(e){this.mixer_&&(this.mixer_.ui.volume=e)}static muteBus(e,t){const s=this.mixer_?.getBus(e);s&&(s.muted=t)}static getBufferHandle(e){return this.bufferCache_.get(e)}static dispose(){this.disposed_=!0,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}static fadeIn(e,t,s){e.setVolume(0);const n=performance.now(),i=()=>{const o=(performance.now()-n)/1e3,r=Math.min(o/t,1);e.setVolume(r*s),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,s){const n=performance.now(),i=()=>{const o=(performance.now()-n)/1e3,r=Math.min(o/t,1);e.setVolume(s*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}static createDeferredHandle(){let e=null;return{id:-1,stop(){e?.stop()},pause(){e?.pause()},resume(){e?.resume()},setVolume(t){e?.setVolume(t)},setPan(t){e?.setPan(t)},setLoop(t){e?.setLoop(t)},setPlaybackRate(t){e?.setPlaybackRate(t)},get isPlaying(){return e?.isPlaying??!1},get currentTime(){return e?.currentTime??0},get duration(){return e?.duration??0},resolve(t){e=t}}}}rs.mixer_=null,rs.bufferCache_=new Map,rs.bgmHandle_=null,rs.bgmVolume_=1,rs.fadeAnimId_=0,rs.disposed_=!1;const as=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}],["AudioSource",{fields:[{field:"clip",type:"audio"}]}]]);function ls(e,t){as.set(e,t)}function cs(e){const t=as.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 us(e){return as.get(e)?.fields??[]}function hs(e){return as.get(e)?.spine??null}const ds=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function fs(e,t){ds.set(e,t)}function ps(e){return ds.get(e)}function ms(e,t){const s=ds.get(e.type);if(!s)return;const n=e.data;for(const i of s){const s=n[i];if("number"==typeof s&&0!==s){const o=t.get(s);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${s} which does not exist`),n[i]=void 0!==o?o:0}}}function _s(e,t){const s=new Map;for(const n of t.entities){if(!1===n.visible)continue;const t=e.spawn();s.set(n.id,t),e.insert(t,ve,{value:n.name})}for(const n of t.entities){if(!1===n.visible)continue;const t=s.get(n.id);for(const i of n.components)ms(i,s),xs(e,t,i,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),i=s.get(n.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return s}function gs(e,t){return _s(e,t)}async function ys(e,t,s){const n=s?.assetServer,i=s?.assetBaseUrl??n?.baseUrl,o=new Map;n&&await async function(e,t,s,n,i){const o=new Map;for(const e of ws.keys())o.set(e,new Set);const r=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=as.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}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...ws.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,s,n);l.set(e,r)}),u=r.map(async e=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)});if(await Promise.all([...c,...u]),i){for(const e of n.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=as.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const n=s[e.field];if("string"!=typeof n||!n)continue;const i=t.get(n);void 0!==i&&(s[e.field]=i)}}}(t,n,i,o,s?.collectAssets);const r=_s(e,t);if(n&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&n.setTextureMetadataByPath(t,s.sliceBorder)}return r}const ws=new Map([["texture",{async load(e,t,s,n){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),n.set(e,o)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(o),i}}],["material",{async load(e,t,s){const n=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,s);n.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),n.set(e,0)}});return await Promise.all(i),n}}],["font",{async load(e,t,s){const n=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,s);n.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),n.set(e,0)}});return await Promise.all(i),n}}],["anim-clip",{async load(e,t,s,n){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=Jt(i),r=new Map,a=o.map(async e=>{try{const i=s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),n.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);es(Qt(e,i,r))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(i),new Map}}],["audio",{async load(e,t,s){const n=[...e].map(e=>s?`${s}/${e}`:`/${e}`);return await rs.preloadAll(n).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}]]);function xs(e,t,s,n){if("LocalTransform"!==s.type&&"WorldTransform"!==s.type||(s.type="Transform"),"UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===s.type){const e=s.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=oe(s.type);if(i)e.insert(t,i,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function vs(e,t){const s=e.getEntitiesWithComponents([pe]);for(const n of s){const s=e.get(n,pe);s&&(s.aspectRatio=t,e.insert(n,pe,s))}}function bs(e,t){const s=e.getEntitiesWithComponents([ve]);for(const n of s){const s=e.get(n,ve);if(s&&s.value===t)return n}return null}const Ss=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],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},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0}],Ms={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",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",bmfont:"application/json",fnt:"text/plain"},Ps=new Map,Ts=new Set;for(const e of Ss)for(const t of e.extensions)Ps.set(t,e),Ts.add(t);function Es(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function Cs(e){return Ps.get(Es(e))}function Rs(e){return Cs(e)?.editorType??"unknown"}function As(e){return Cs(e)?.addressableType??null}function Is(e){for(const t of Ss)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function ks(e){return Ts.has(e.toLowerCase())}function Fs(){return Ts}function Bs(e){return"string"==typeof e&&(!!e.includes("/")&&ks(Es(e)))}function zs(){const e=[];for(const t of Ss)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function Us(){return zs().map(e=>({type:"suffix",value:e}))}function $s(e){return Ms[e.toLowerCase()]}function Ds(e){const t=Cs(e);return t?.wechatPackInclude??!1}function Os(e){const t=Cs(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const s=e.lastIndexOf(".");return s>=0?e.substring(0,s)+".json":e}function Ls(e,t){for(const s of Ss)s.editorType===e&&(s.buildTransform=t)}function Ws(e){return Cs(e)?.buildTransform}class Hs{constructor(e){this.textureCache_=new Gt,this.shaderCache_=new Gt,this.jsonCache_=new Gt,this.textCache_=new Gt,this.binaryCache_=new Gt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Gt,this.prefabCache_=new Gt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=h(F.textCanvasSize,F.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Kt(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),i=this.textureCache_.get(n);if(!i)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),Lt.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const i=this.resolveUrl(t,s),o=await this.fetchText(i);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=r?`${r}/${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"===Cs(e)?.contentType,h=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(h,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),i=l.find(e=>e.name===s);if(i){const s=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,i.info.width,i.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}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=Cs(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 i=s?`${s}/${n}`:n;return this.loadFntFile(i)}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],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${n}`:n,r=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,r.handle,r.width,r.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,async()=>{const e=await this.fetchJson(s);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const s of e.entities){for(const e of s.components){if(!e.data)continue;for(const s of cs(e.type)){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}const s=hs(e.type);if(s)for(const n of[s.skeletonField,s.atlasField]){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}}if(s.nestedPrefab?.prefabPath){const e=t(s.nestedPrefab.prefabPath);e&&(s.nestedPrefab.prefabPath=e)}}}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const 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 ys(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 i=n.metadata?.atlas;i&&s.push(this.loadSpine(n.path,i).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return this.loadImageFromSrc(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){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=e})}createTextureFromImage(e,t){const{width:s,height:n}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,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,i){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const r=this.module_.GL,a=r.getNewId(r.textures);r.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 i=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(o);const r=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=r.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.getEmbedded(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:i}=this.parseEsShader(t);if(!n||!i)throw new Error(`Invalid shader format: ${e}`);return Lt.createShader(n,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const n=await l(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:o}=this.parseEsShader(n);if(!i||!o)throw new Error(`Invalid shader format: ${e}`);return Lt.createShader(i,o)}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://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(Os(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await l(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await r(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.getEmbedded(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await r(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.getEmbedded(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 r(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 i="";for(const e of n){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const 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 Ns=Ae(null,"Assets");class Xs{build(e){const t=e.wasmModule;t?e.insertResource(Ns,new Hs(t)):console.warn("AssetPlugin: No WASM module available")}}const js=new Xs;class Ys{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 Vs(e,t){const s=e.getResource(Ns);s&&s.registerEmbeddedAssets(t)}async function qs(e,t,s){const{entities:n,rootId:i}=await Ks(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}))},r=await ys(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=r.get(i);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:r}}const Gs=10;async function Ks(e,t,s,n,i,o=0){if(o>Gs)throw new Error(`Prefab nesting depth exceeded ${Gs}. Check for deep or circular nesting in: ${e.name}`);const r=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,a++)}const l=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(i?.has(n.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${n.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await Ks(e,n.nestedPrefab.overrides,s,a,i,o+1);r.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?r.get(n.parent)??null:null),l.push(...t.entities);continue}const c=r.get(n.prefabEntityId),u=n.prefabEntityId===e.rootEntityId,h={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?null:null!==n.parent?r.get(n.parent)??null:null,children:n.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};Js(h.components,r),Qs(h,t),l.push(h)}const c=r.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function Js(e,t){for(const s of e){const e=ps(s.type);if(e)for(const n of e){const e=s.data[n];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(s.data[n]=i)}}}}function Qs(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 Zs{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,i=await this.assetServer_.loadPrefab(n,t?.baseUrl);return qs(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const en=Ae(null,"Prefabs");class tn{constructor(){this.name="PrefabsPlugin",this.dependencies=[Ns]}build(e){const t=e.getResource(Ns);e.insertResource(en,new Zs(e.world,t))}}const sn=new tn;let nn=null,on=0,rn=0,an=0;const ln=new Float32Array(256);function cn(e){nn=e,on=nn._malloc(64),rn=nn._malloc(64),an=nn._malloc(1024)}function un(){nn&&(on&&(nn._free(on),on=0),rn&&(nn._free(rn),rn=0),an&&(nn._free(an),an=0)),nn=null}function hn(){if(!nn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return nn}const dn={r:1,g:1,b:1,a:1},fn={begin(e){const t=hn();try{t.HEAPF32.set(e,on/4),t.draw_begin(on)}catch(e){We(e,"Draw.begin")}},end(){try{hn().draw_end()}catch(e){We(e,"Draw.end")}},line(e,t,s,n=1){try{hn().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){We(e,"Draw.line")}},rect(e,t,s,n=!0){try{hn().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){We(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{hn().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){We(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,i=32){try{hn().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){We(e,"Draw.circle")}},circleOutline(e,t,s,n=1,i=32){try{hn().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){We(e,"Draw.circleOutline")}},texture(e,t,s,n=dn){try{hn().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){We(e,"Draw.texture")}},textureRotated(e,t,s,n,i=dn){try{hn().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,i.r,i.g,i.b,i.a)}catch(e){We(e,"Draw.textureRotated")}},setLayer(e){hn().draw_setLayer(e)},setDepth(e){hn().draw_setDepth(e)},getDrawCallCount:()=>nn?nn.draw_getDrawCallCount():0,getPrimitiveCount:()=>nn?nn.draw_getPrimitiveCount():0,setBlendMode(e){hn().draw_setBlendMode(e)},setDepthTest(e){hn().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=hn();n.HEAPF32.set(s,rn/4),n.draw_mesh(e,t,rn)}catch(s){We(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=hn(),i=Lt.get(t);if(!i)return;if(fn.setBlendMode(i.blendMode),fn.setDepthTest(i.depthTest),0===i.uniforms.size)return void fn.drawMesh(e,i.shader,s);let o;if(n.HEAPF32.set(s,rn/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,s]of i.uniforms){const n=_n(t);if(!(n<0)){if(kt(s))ln[o++]=10,ln[o++]=n,ln[o++]=s.slot??e++,ln[o++]=s.textureId;else if("number"==typeof s)ln[o++]=1,ln[o++]=n,ln[o++]=s;else if(Array.isArray(s)){ln[o++]=s.length,ln[o++]=n;for(let e=0;e<s.length;e++)ln[o++]=s[e]}else"w"in s?(ln[o++]=4,ln[o++]=n,ln[o++]=s.x,ln[o++]=s.y,ln[o++]=s.z,ln[o++]=s.w):"z"in s?(ln[o++]=3,ln[o++]=n,ln[o++]=s.x,ln[o++]=s.y,ln[o++]=s.z):(ln[o++]=2,ln[o++]=n,ln[o++]=s.x,ln[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<o)&&(i.cachedBuffer_=new Float32Array(o)),i.cachedBuffer_.set(ln.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void n.draw_mesh(e,i.shader,rn);n.HEAPF32.set(i.cachedBuffer_.subarray(0,o),an/4),n.draw_meshWithUniforms(e,i.shader,rn,an,o)}catch(s){We(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},pn={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},mn=new Set;function _n(e){const t=pn[e];return void 0!==t?t:(mn.has(e)||(mn.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(pn).join(", ")}`)),-1)}const gn=new Map;function yn(e,t,s){gn.set(e,{fn:t,scene:s??""})}function wn(e){gn.delete(e)}function xn(){gn.clear()}var vn;!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"}(vn||(vn={}));let bn=null,Sn=0,Mn=0,Pn=0;function Tn(e){bn=e,Sn=bn._malloc(262144),Mn=bn._malloc(65536),Pn=bn._malloc(256)}function En(){bn&&(Sn&&bn._free(Sn),Mn&&bn._free(Mn),Pn&&bn._free(Pn),Sn=0,Mn=0,Pn=0),bn=null}function Cn(){if(!bn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return bn}const Rn={create(e){const t=Cn(),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,Sn/4);const i=e.layout.length,o=new Int32Array(i);for(let t=0;t<i;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Pn,i).set(o),t.geometry_init(s,Sn,n,Pn,i,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,Mn,n).set(e.indices),t.geometry_setIndices16(s,Mn,n)}else{new Uint32Array(t.HEAPU8.buffer,Mn,n).set(e.indices),t.geometry_setIndices32(s,Mn,n)}}return s},updateVertices(e,t,s=0){const n=Cn(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);n.HEAPF32.set(t,Sn/4),n.geometry_updateVertices(e,Sn,i,s)},release(e){e>0&&Cn().geometry_release(e)},isValid:e=>!(!bn||e<=0)&&bn.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Rn.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:vn.Float2},{name:"a_texCoord",type:vn.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 i=n/t*Math.PI*2,o=Math.cos(i)*e,r=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;s.push(o,r,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Rn.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:vn.Float2},{name:"a_texCoord",type:vn.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,i=-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),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(n-t),a=(r.y-s)/(i-s);o.push(r.x,r.y,e,a)}const r=[];for(let t=1;t<e.length-1;t++)r.push(0,t,t+1);return Rn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:vn.Float2},{name:"a_texCoord",type:vn.Float2}],indices:new Uint16Array(r)})}};let An=null;function In(e){An=e}function kn(){An&&Bn.isInitialized()&&Bn.shutdown(),An=null}function Fn(){if(!An)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return An}const Bn={init(e,t){try{return Fn().postprocess_init(e,t)}catch(s){return We(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Fn().postprocess_shutdown()}catch(e){We(e,"PostProcess.shutdown")}},resize(e,t){try{Fn().postprocess_resize(e,t)}catch(s){We(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Fn().postprocess_addPass(e,t)}catch(t){return We(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Fn().postprocess_removePass(e)}catch(t){We(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Fn().postprocess_setPassEnabled(e,t)}catch(t){We(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Fn().postprocess_isPassEnabled(e)}catch(t){return We(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{Fn().postprocess_setUniformFloat(e,t,s)}catch(s){We(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{Fn().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){We(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Fn().postprocess_begin()}catch(e){We(e,"PostProcess.begin")}},end(){try{Fn().postprocess_end()}catch(e){We(e,"PostProcess.end")}},getPassCount(){try{return Fn().postprocess_getPassCount()}catch(e){return We(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!An)return!1;try{return An.postprocess_isInitialized()}catch(e){return We(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Fn().postprocess_setBypass(e)}catch(e){We(e,"PostProcess.setBypass")}},isBypassed(){if(!An)return!0;try{return An.postprocess_isBypassed()}catch(e){return We(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Lt.createShader(zn,"#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:()=>Lt.createShader(zn,"#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:()=>Lt.createShader(zn,"#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:()=>Lt.createShader(zn,"#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")},zn="#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 Un;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Un||(Un={}));let $n=null,Dn=0;function On(e){$n=e,Dn=$n._malloc(64)}function Ln(){$n&&Dn&&($n._free(Dn),Dn=0),$n=null}const Wn={init(e,t){$n?.renderer_init(e,t)},resize(e,t){$n?.renderer_resize(e,t)},begin(e,t){if($n&&Dn)try{$n.HEAPF32.set(e,Dn/4),$n.renderer_begin(Dn,t??0)}catch(e){We(e,"Renderer.begin")}},flush(){try{$n?.renderer_flush()}catch(e){We(e,"Renderer.flush")}},end(){try{$n?.renderer_end()}catch(e){We(e,"Renderer.end")}},submitSprites(e){if($n)try{$n.renderer_submitSprites(e._cpp)}catch(e){We(e,"Renderer.submitSprites")}},submitBitmapText(e){if($n)try{$n.renderer_submitBitmapText(e._cpp)}catch(e){We(e,"Renderer.submitBitmapText")}},submitSpine(e){if($n)try{$n.renderer_submitSpine?.(e._cpp)}catch(e){We(e,"Renderer.submitSpine")}},setStage(e){$n?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>$n?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){$n?.renderer_releaseTarget(e)},getTargetTexture:e=>$n?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>$n?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){$n?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){$n?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,i){$n?.renderer_setScissor(e,t,s,n,i)},clearBuffers(e){$n?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>$n?$n.getResourceManager().measureBitmapText(e,t,s,n):{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 Hn=null;function Nn(e){Hn=e}function Xn(){Hn=null}const jn={enable(){Hn?.gl_enableErrorCheck(!0)},disable(){Hn?.gl_enableErrorCheck(!1)},check:e=>Hn?.gl_checkErrors(e)??0,diagnose(){Hn?.renderer_diagnose()}};class Yn{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:i,elapsed:o}=e;n===this.lastWidth_&&i===this.lastHeight_||(Wn.resize(n,i),Bn.isInitialized()&&Bn.getPassCount()>0&&Bn.resize(n,i),this.lastWidth_=n,this.lastHeight_=i),Wn.setViewport(0,0,n,i),Wn.clearBuffers(3),Wn.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,i),Wn.submitSprites(t),Wn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Wn.submitSpine(t),Wn.flush(),this.executeDrawCallbacks(s,o),Wn.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:i,elapsed:o}=e;Wn.setViewport(n.x,n.y,n.w,n.h),Wn.setScissor(n.x,n.y,n.w,n.h,!0),Wn.clearBuffers(i),Wn.setScissor(0,0,0,0,!1),Wn.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Wn.submitSprites(t),Wn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Wn.submitSpine(t),Wn.flush(),this.executeDrawCallbacks(s,o),Wn.end()}executeDrawCallbacks(e,t){const s=gn;if(s.size>0){fn.begin(e);const n=[];for(const[e,i]of s.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}fn.end();for(const e of n)wn(e)}}}const Vn="__scene_transition_overlay__";class qn{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class Gn{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,be,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),yn(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Bn.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Bn.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,be)){const s=this.app_.world.get(e,be);s.persistent=t,this.app_.world.insert(e,be,s)}}}class Kn{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??F.sceneTransitionDuration,i=t.color??{...F.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:i,targetScene:e,options:t,resolve:s},yn(Vn,()=>{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;fn.setLayer(9999),fn.setDepth(9999),fn.rect({x:0,y:0},{x:2e4,y:2e4},{r:i.r,g:i.g,b:i.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()=>{try{s&&s!==e&&await this.unload(s,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,wn(Vn),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,wn(Vn),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new qn(t);this.scenes_.set(e,s);const n=new Gn(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Ns)?this.app_.getResource(Ns):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(s,e,t,i),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new qn(t);this.scenes_.set(e,s);const n=new Gn(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Ns)?this.app_.getResource(Ns):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(s,e,t,i),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const i=t?.keepPersistent??!0;for(const e of s.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,be)){if(this.app_.world.get(e,be).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())wn(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Bn.removePass(e)}catch{}s.postProcessPasses.length=0,this.releaseSceneAssets_(s),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)}async loadSceneData_(e,t,s,n){if(n){const s={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:s};this.app_.hasResource(Ns)&&(i.assetServer=this.app_.getResource(Ns));const o=await ys(this.app_.world,n,i);e.loadedAssets=s;for(const s of o.values())e.entities.add(s),this.app_.world.insert(s,be,{scene:t,persistent:!1})}if(s.systems)for(const{schedule:e,system:n}of s.systems){const s=Qn(this.app_,t,n);this.app_.addSystemToSchedule(e,s)}const i=this.contexts_.get(t);s.setup&&await s.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const s=this.app_.hasResource(Ns)?this.app_.getResource(Ns):null;if(s){for(const e of t.textureUrls)s.releaseTexture(e);for(const e of t.fontPaths)s.releaseFont(e);for(const e of t.spineKeys)s.releaseSpine(e)}for(const e of t.materialHandles)Lt.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n={};let i=!1;if(s.has(e,fe)){const t=s.get(e,fe);n.sprite=t.color.a,t.color.a=0,s.insert(e,fe,t),i=!0}if(s.has(e,xe)){const t=s.get(e,xe);n.spine=t.color.a,t.color.a=0,s.insert(e,xe,t),i=!0}if(s.has(e,we)){const t=s.get(e,we);n.bitmapText=t.color.a,t.color.a=0,s.insert(e,we,t),i=!0}i&&t.savedAlphas.set(e,n)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n=t.savedAlphas.get(e);if(n){if(void 0!==n.sprite&&s.has(e,fe)){const t=s.get(e,fe);t.color.a=n.sprite,s.insert(e,fe,t)}if(void 0!==n.spine&&s.has(e,xe)){const t=s.get(e,xe);t.color.a=n.spine,s.insert(e,xe,t)}if(void 0!==n.bitmapText&&s.has(e,we)){const t=s.get(e,we);t.color.a=n.bitmapText,s.insert(e,we,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{Bn.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 Jn=Ae(null,"SceneManager");function Qn(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Jn).getSceneStatus(t)&&s._fn(...n)}}}const Zn=xt([ke(Jn),Ie(ze)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),ei={name:"SceneManager",build(e){const t=new Kn(e);e.insertResource(Jn,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Jn),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(gt.Startup,s),e.addSystemToSchedule(gt.Last,Zn)}};class ti{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new dt,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(gt.Last);else{this.runSchedule(gt.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(gt.FixedPreUpdate),this.runSchedule(gt.FixedUpdate),this.runSchedule(gt.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(gt.PreUpdate),this.runSchedule(gt.Update),this.runSchedule(gt.PostUpdate),this.runSchedule(gt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new qe,this.resources_=new Be;for(const e of Object.values(gt))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new ti}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(gt.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(gt.Startup,e)}removeSystem(e){let t=!1;for(const[s,n]of this.systems_){const i=n.filter(t=>t.system._id!==e);i.length!==n.length&&(this.systems_.set(s,i),this.sortedSystemsCache_.delete(s),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return Le(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}enableStats(){return this.statsEnabled_=!0,this.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}getEntityCount(){return this.world_.entityCount()}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(Jn).register(e),this}setInitialScene(e){return this.getResource(Jn).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new Pt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(ze)||this.resources_.insert(ze,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(gt.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(gt.Last);else{this.runSchedule(gt.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(gt.FixedPreUpdate),this.runSchedule(gt.FixedUpdate),this.runSchedule(gt.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(gt.PreUpdate),this.runSchedule(gt.Update),this.runSchedule(gt.PostUpdate),this.runSchedule(gt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new Pt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(ze,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(gt.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,xn();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[Xn,Ln,kn,En,Dt,un];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let 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 i=t.get(n);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,i=new Set,o=r=>{if(n.has(r))return;if(i.has(r)){const t=e[r].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(r);const a=e[r];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}i.delete(r),n.add(r),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));const n=this.phaseTimings_?performance.now():0;for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}this.phaseTimings_&&this.phaseTimings_.set(gt[e],performance.now()-n)}updateTime(e){const t=this.resources_.get(ze);t.delta=e,t.elapsed+=e,t.frameCount++}}function si(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const ni=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ii(e,t,s,n,i){const o=e*t/s,r=e;switch(n){case ce.FixedWidth:return o;case ce.FixedHeight:return r;case ce.Expand:return Math.max(o,r);case ce.Shrink:return Math.min(o,r);case ce.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const oi=[];function ri(e){if(e<oi.length)return oi[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return oi.push(t),t}function ai(e,t,s,n,i,o){if(0===s||0===n)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,be);return!t||""===t.scene||o.has(t.scene)}):r;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 i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*s/(i.viewportH*n);let a,u=0,h=0;if(i.projectionType===ae.Orthographic){if(h=i.orthoSize,l){h=ii(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=h*r,a=ci(-u,u,-h,h,-i.farPlane,i.farPlane)}else a=hi(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const d=fi(o.position.x,o.position.y,o.position.z),f=ri(c.length);f.entity=e,f.viewProjection.set(mi(a,d)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=u,f.halfH=h,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const li=new Float32Array(16);function ci(e,t,s,n,i,o){const r=li;r.fill(0);const a=t-e,l=n-s,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(n+s)/l,r[14]=-(o+i)/c,r[15]=1,r}const ui=new Float32Array(16);function hi(e,t,s,n){const i=ui;i.fill(0);const o=1/Math.tan(e/2),r=s-n;return i[0]=o/t,i[5]=o,i[10]=(n+s)/r,i[11]=-1,i[14]=2*n*s/r,i}const di=new Float32Array(16);function fi(e,t,s){const n=di;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 pi=new Float32Array(16);function mi(e,t){const s=pi;for(let n=0;n<4;n++)for(let i=0;i<4;i++)s[4*i+n]=e[0+n]*t[4*i+0]+e[4+n]*t[4*i+1]+e[8+n]*t[4*i+2]+e[12+n]*t[4*i+3];return s}const _i={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function gi(e,t,s,n,i,o,r={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,u=o.left+t.x*a,h=o.bottom+e.y*l,d=o.bottom+t.y*l;let f,p,m,_;e.x===t.x?(f=c+s.x-i.x*r.x,m=f+i.x):(f=c+s.x,m=u+n.x),e.y===t.y?(p=h+s.y-i.y*r.y,_=p+i.y):(p=h+s.y,_=d+n.y);const g=Math.max(0,m-f),y=Math.max(0,_-p);return{originX:f+r.x*g,originY:p+r.y*y,width:g,height:y,rect:{left:f,bottom:p,right:m,top:_}}}const yi=re("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});let wi=null,xi=null;function vi(e,t){e.has(t,fe)||e.insert(t,fe,{texture:D,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0})}function bi(e,t){switch(e){case _i.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case _i.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case _i.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function Si(e,t){switch(e){case _i.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case _i.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case _i.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1-t}};default:return{anchorMin:{x:t,y:0},anchorMax:{x:t,y:1}}}}function Mi(e,t,s,n){switch(e){case _i.BottomToTop:case _i.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}}function Pi(e,t,s,n){if(!e.has(t,yi))return;const i=e.get(t,yi),o=bi(s,n);i.anchorMin=o.anchorMin,i.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(i.size={...i.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,yi,i)}function Ti(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Ei(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Ci(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),i=[];for(const t of n){if(!t){i.push("");continue}let n="";for(let o=0;o<t.length;o++){const r=t[o],a=n+r;if(e.measureText(a).width>s&&n){if(Ei(r.charCodeAt(0))&&n.length>0&&Ei(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!Ei(n.charCodeAt(t))){e=t;break}e>=0?(i.push(n.substring(0,e+1)),n=n.substring(e+1)+r):(i.push(n),n=r)}else i.push(n),n=r}else n=a}n&&i.push(n)}return i.length>0?i:[""]}function Ri(e){let t=1;for(;t<e;)t*=2;return t}function Ai(e,t){let s=0,n=t;for(;e.has(n,ge);){const t=e.get(n,ge).entity;if(!e.valid(t))break;s++,n=t}return s}function Ii(e,t){if(wi&&xi){const e=wi.getUIRectComputedWidth(xi,t);if(e>0)return e}return e.size.x}function ki(e,t){if(wi&&xi){const e=wi.getUIRectComputedHeight(xi,t);if(e>0)return e}return e.size.y}function Fi(e,t,s,n,i,o){if(!e.has(t,fe))return;const r=e.get(t,fe);let a,l;switch(s){case _i.BottomToTop:case _i.TopToBottom:a=i,l=o*n;break;default:a=i*n,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,fe,r))}function Bi(e,t,s){let n=t;for(;e.has(n,ge);){const t=e.get(n,ge).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function zi(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function Ui(e,t,s,n,i){if(!e.has(t,yi))return;const o=e.get(t,yi),r=gi(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s,o.pivot),a=r.rect.right-r.rect.left,l=r.rect.top-r.rect.bottom;if(e.has(t,fe)){const s=e.get(t,fe);s.size.x===a&&s.size.y===l||(s.size.x=a,s.size.y=l,e.insert(t,fe,s))}if(e.has(t,ue)){const s=e.get(t,ue);s.position.x=r.originX-n,s.position.y=r.originY-i,e.insert(t,ue,s)}}function $i(e){const t=Object.keys(e),s=t.map(t=>e[t]);return{take(e){const n={};for(let i=0;i<t.length;i++)n[t[i]]=s[i](e);return n},changed(e,n){for(let i=0;i<t.length;i++)if(e[t[i]]!==s[i](n))return!0;return!1},update(e,n){for(let i=0;i<t.length;i++)e[t[i]]=s[i](n)}}}const Di=.1,Oi=30,Li={r:.3,g:.5,b:.8,a:1},Wi={Left:0,Center:1,Right:2},Hi={Top:0,Middle:1,Bottom:2},Ni={Visible:0,Clip:1,Ellipsis:2},Xi=K("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Wi.Left,verticalAlign:Hi.Top,wordWrap:!0,overflow:Ni.Visible,lineHeight:1.2});class ji{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(F.textCanvasSize,F.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,Ri(this.frameMaxW_)),e.height=Math.max(e.height,Ri(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Ri(this.frameMaxW_),e.height=Ri(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,o=i?t.size.x:0,r=i?t.size.y:0,a=e.wordWrap&&i;let l=Ci(s,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=i?Math.ceil(o):h+2*u,p=i?Math.ceil(r):d+2*u;if(i&&e.overflow===Ni.Ellipsis&&d>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(n.width<f||n.height<p)&&(n.width=Math.max(n.width,Ri(f)),n.height=Math.max(n.height,Ri(p)));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;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${m}, ${_}, ${g}, ${y})`,i&&e.overflow===Ni.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const w=l.length*c;let x;if(i){switch(e.verticalAlign){case Hi.Top:x=u;break;case Hi.Middle:x=u+(p-2*u-w)/2;break;case Hi.Bottom:x=p-w-u;break;default:x=u}x<0&&(x=0)}else x=u;let v=x;for(const t of l){let n;switch(e.align){case Wi.Left:n=u;break;case Wi.Center:n=f/2;break;case Wi.Right:n=f-u;break;default:n=u}s.fillText(t,n,v),v+=c}i&&e.overflow===Ni.Clip&&s.restore();const b=s.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),M=this.module.getResourceManager(),P=this.module._malloc(S.length);this.module.HEAPU8.set(S,P);const T=M.createTexture(f,p,P,S.length,1,!0);return this.module._free(P),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let 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 i=this.renderText(t,s);return this.cache.set(e,i),i}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}measureWidth(e){let t=0;for(const s of e)t=Math.max(t,this.ctx.measureText(s).width);return t}mapAlign(e){switch(e){case Wi.Left:return"left";case Wi.Center:return"center";case Wi.Right:return"right"}}}const Yi=$i({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?Ii(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?ki(e.uiRect,e.entity):0});class Vi{build(e){ie("Text",Xi);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new ji(t),n=e.world,i=new Map;e.addSystemToSchedule(gt.PreUpdate,xt([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Xi));for(const e of i.keys())if(!n.valid(e)||!n.has(e,Xi)){if(n.valid(e)&&n.has(e,fe)){const t=n.get(e,fe);n.insert(e,fe,{texture:D,color:{r:t.color.r,g:t.color.g,b:t.color.b,a:t.color.a},size:{x:t.size.x,y:t.size.y},uvOffset:{x:t.uvOffset.x,y:t.uvOffset.y},uvScale:{x:t.uvScale.x,y:t.uvScale.y},layer:t.layer,flipX:t.flipX,flipY:t.flipY,material:t.material,enabled:t.enabled})}i.delete(e)}const e=n.getEntitiesWithComponents([Xi]);for(const t of e){const e=n.get(t,Xi),o=n.has(t,yi)?n.get(t,yi):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!Yi.changed(a,r)){if(n.has(t,fe)&&n.get(t,fe).texture!==D)continue}vi(n,t);const l=o?{size:{x:Ii(o,t),y:ki(o,t)}}:null,c=s.renderForEntity(t,e,l),u=n.get(t,fe);n.insert(t,fe,{texture:c.textureHandle,color:{r:u.color.r,g:u.color.g,b:u.color.b,a:u.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:u.layer,flipX:u.flipX,flipY:u.flipY,material:u.material,enabled:u.enabled}),i.set(t,Yi.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const qi=new Vi,Gi=0,Ki=1,Ji=re("UIMask",{enabled:!0,mode:Gi});function Qi(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),i=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,i-s),h:Math.max(0,o-n)}}function Zi(e,t){const s=t??new Float32Array(16),n=e[0],i=e[1],o=e[2],r=e[3],a=e[4],l=e[5],c=e[6],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],m=e[12],_=e[13],g=e[14],y=e[15],w=n*l-i*a,x=n*c-o*a,v=n*u-r*a,b=i*c-o*l,S=i*u-r*l,M=o*u-r*c,P=h*_-d*m,T=h*g-f*m,E=h*y-p*m,C=d*g-f*_,R=d*y-p*_,A=f*y-p*g;let I=w*A-x*R+v*C+b*E-S*T+M*P;return 0===I||(I=1/I,s[0]=(l*A-c*R+u*C)*I,s[1]=(o*R-i*A-r*C)*I,s[2]=(_*M-g*S+y*b)*I,s[3]=(f*S-d*M-p*b)*I,s[4]=(c*E-a*A-u*T)*I,s[5]=(n*A-o*E+r*T)*I,s[6]=(g*v-m*M-y*x)*I,s[7]=(h*M-f*v+p*x)*I,s[8]=(a*R-l*E+u*P)*I,s[9]=(i*E-n*R-r*P)*I,s[10]=(m*S-_*v+y*w)*I,s[11]=(d*v-h*S-p*w)*I,s[12]=(l*T-a*C-c*P)*I,s[13]=(n*C-i*T+o*P)*I,s[14]=(_*x-m*b-g*w)*I,s[15]=(h*b-d*x+f*w)*I),s}function eo(e,t,s,n,i,o,r){const a=(e-n)/o*2-1,l=(t-i)/r*2-1,c=s[0]*a+s[4]*l+s[12],u=s[1]*a+s[5]*l+s[13],h=s[3]*a+s[7]*l+s[15];return{x:c/h,y:u/h}}function to(e,t,s,n,i,o,r,a){return e>=s-i*r&&e<=s+i*(1-r)&&t>=n-o*a&&t<=n+o*(1-a)}function so(e,t){return 2*Math.atan2(e,t)}function no(e,t,s,n,i,o,r){const a=s[0]*e+s[4]*t+s[12],l=s[1]*e+s[5]*t+s[13],c=s[3]*e+s[7]*t+s[15];return[n+(.5*(a/c)+.5)*o,i+(.5*(l/c)+.5)*r]}function io(e,t,s,n,i,o,r,a,l,c){const u=so(l,c),h=Math.sin(-u),d=Math.cos(-u),f=e-s,p=t-n,m=f*d-p*h+s,_=f*h+p*d+n;return m>=s-i*r&&m<=s+i*(1-r)&&_>=n-o*a&&_<=n+o*(1-a)}function oo(e,t,s,n,i,o,r){if(!e.has(t,yi)||!e.has(t,ue))return null;const a=e.get(t,yi),l=e.get(t,ue),c=Ii(a,t)*l.worldScale.x,u=ki(a,t)*l.worldScale.y,h=l.worldPosition.x,d=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,m=-c*f,_=c*(1-f),g=-u*p,y=u*(1-p),w=so(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[h+m*x-g*v,d+m*v+g*x],[h+_*x-g*v,d+_*v+g*x],[h+_*x-y*v,d+_*v+y*x],[h+m*x-y*v,d+m*v+y*x]];let S=1/0,M=1/0,P=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=no(e,t,s,n,i,o,r);S=Math.min(S,a),M=Math.min(M,l),P=Math.max(P,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(M),w:Math.round(P-S),h:Math.round(T-M)}}function ro(e,t){return(s,n,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Ji]);if(0===l.length)return;const c=[],u=[],h=new Set,d=new Set;for(const e of l){const s=t.get(e,Ji);s.enabled&&(h.add(e),s.mode===Ki?(u.push(e),d.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,i,o,r,a,l,c){const u=[];for(const e of n){let s=!0;Bi(t,e,e=>{if(i.has(e)){if(t.get(e,Ji).mode===Gi)return s=!1,!0}return!1}),s&&u.push(e)}function h(n,u){const d=e.getChildEntities(s,n);for(const s of d){let n=u;if(i.has(s)){if(t.get(s,Ji).mode===Gi){const e=oo(t,s,o,r,a,l,c);e&&(n=Qi(u,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),h(s,n)}}for(const e of u){const s=oo(t,e,o,r,a,l,c);s&&h(e,s)}}(e,t,s,c,h,n,i,o,r,a),u.length>0&&function(e,t,s,n,i){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0;Bi(t,e,e=>!!i.has(e)&&(s=!1,!0)),s&&o.push(e)}let r=1,a=!1;function l(){return r>255?(a||console.warn("Stencil mask overflow"),a=!0,null):r++}function c(t,n){if(a)return;e.renderer_setEntityStencilMask(t,n);const o=e.getChildEntities(s,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),u(t,n)}function u(t,n){if(a)return;const o=e.getChildEntities(s,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),u(t,n)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,s,u,d)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class ao{build(e){if(ie("UIMask",Ji),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(ro(e.wasmModule,e.world))}}const lo=new ao,co=re("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),uo=re("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),ho={Normal:0,Hovered:1,Pressed:2,Disabled:3},fo=K("Button",{state:ho.Normal,transition:null});class po{constructor(){this.events_=[]}emit(e,t,s){const n=s??e;this.events_.push({entity:e,type:t,target:n,currentTarget:e})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const mo=Ae(new po,"UIEvents");class _o{build(e){ie("UIRect",yi);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){wi=e,xi=t}(s,n);e.addSystemToSchedule(gt.PreUpdate,xt([Ie(At)],e=>{e.valid&&(s.uiLayout_update(n,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),s.uiFlexLayout_update(n),s.transform_update(n))},{name:"UILayoutSystem"})),e.addSystemToSchedule(gt.PostUpdate,xt([Ie(At)],e=>{e.valid&&(s.uiLayout_update(n,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),s.uiFlexLayout_update(n))},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(gt.PostUpdate,xt([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const go=new _o;let yo=!1,wo=!1;function xo(e){yo=e}function vo(){return yo}function bo(){return!yo}function So(e){wo=e}function Mo(){return wo}const Po=function(){const e=new Float32Array(16),t=new Float32Array(16);let s=!0;return{update(e){for(let n=0;n<16;n++)if(t[n]!==e[n]){t.set(e),s=!0;break}},getInverse:t=>(s&&(Zi(t,e),s=!1),e)}}();function To(e,t,s,n){t.emit(s,n,s),Bi(e,s,i=>{if(!e.has(i,co))return!1;const o=e.get(i,co);return o.enabled&&t.emit(i,n,s),o.blockRaycast})}class Eo{build(e){ie("Interactable",co),ie("Button",fo);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),i=new po;e.insertResource(mo,i);let o=null,r=null;e.addSystemToSchedule(gt.PreUpdate,xt([Ie(Et),Ie(At)],(e,a)=>{if(i.drain(),vo()&&!Mo())return;const l=t.getEntitiesWithComponents([uo]);for(const e of l){const s=t.get(e,uo);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,uo,s))}if(!a.valid)return;const c=f(),u=e.mouseX*c,h=a.screenH-e.mouseY*c;Po.update(a.viewProjection);const d=eo(u,h,Po.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=d.x,a.worldMouseY=d.y;const p=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),_=e.isMouseButtonReleased(0);s.uiHitTest_update(n,d.x,d.y,p,m,_);const g=s.uiHitTest_getHitEntity(),y=4294967295===g?null:g;if(null===o||t.valid(o)||(o=null),o!==y){if(null!==o&&t.valid(o)&&t.has(o,uo)){const e=t.get(o,uo);e.hovered=!1,t.insert(o,uo,e),i.emit(o,"hover_exit")}if(null!==y){zi(t,y,uo);const e=t.get(y,uo);e.hovered=!0,t.insert(y,uo,e),i.emit(y,"hover_enter")}o=y}if(m&&null!==y){const e=t.get(y,uo);e.pressed=!0,e.justPressed=!0,t.insert(y,uo,e),r=y,To(t,i,y,"press")}if(_&&null!==r){if(t.valid(r)&&t.has(r,uo)){const e=t.get(r,uo);e.pressed=!1,e.justReleased=!0,t.insert(r,uo,e),To(t,i,r,"release"),r===o&&To(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(gt.Update,xt([],()=>{const e=t.getEntitiesWithComponents([fo]);for(const s of e){if(zi(t,s,co,{enabled:!0}),!t.has(s,uo))continue;const e=t.get(s,uo),n=t.get(s,fo),i=t.get(s,co),o=!a.has(s),r=n.state;if(i.enabled?e.pressed?n.state=ho.Pressed:e.hovered?n.state=ho.Hovered:n.state=ho.Normal:n.state=ho.Disabled,o&&a.add(s),(o||r!==n.state)&&n.transition&&t.has(s,fe)){const o=t.get(s,fe);o.color=Ti(n.transition,i.enabled,e.pressed,e.hovered),t.insert(s,fe,o)}}},{name:"ButtonSystem"}))}}const Co=new Eo,Ro=K("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}),Ao=K("Focusable",{tabIndex:0,isFocused:!1});class Io{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const ko=Ae(new Io,"FocusManager");class Fo{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(ie("TextInput",Ro),vo()&&!Mo())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,i=h(F.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=0,a=0,l=!1,c=!0,u=0,d=0;const f=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!f)return;const p=f;function m(){const t=e.getResource(ko);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,Ro)?n:null}const _=()=>{l||null===m()||v()},g=()=>{l=!0},y=()=>{l=!1,v()},w=t=>{const n=m();if(null===n)return;if("Escape"===t.key)return void b();const i=s.get(n,Ro);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(mo).emit(n,"submit"),void b()}let o=i.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?o=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=i.value.length),o!==i.cursorPos&&(i.cursorPos=o,p.selectionStart=o,p.selectionEnd=o,i.dirty=!0,S())},x=()=>{const t=m();if(null!==t){const n=s.get(t,Ro);n.focused=!1,n.dirty=!0;e.getResource(ko).blur()}};function v(){const t=m();if(null===t)return;const n=s.get(t,Ro);if(n.readOnly)return;let i=p.value;if(n.maxLength>0&&i.length>n.maxLength&&(i=i.substring(0,n.maxLength),p.value=i),i!==n.value){n.value=i;e.getResource(mo).emit(t,"change")}n.cursorPos=p.selectionStart??i.length,n.dirty=!0,S()}function b(){const t=m();if(null!==t){const e=s.get(t,Ro);e.focused=!1,e.dirty=!0}e.getResource(ko).blur(),p.blur()}function S(){c=!0,u=0}p.addEventListener("input",_),p.addEventListener("compositionstart",g),p.addEventListener("compositionend",y),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",_),p.removeEventListener("compositionstart",g),p.removeEventListener("compositionend",y),p.removeEventListener("keydown",w),p.removeEventListener("blur",x),p.remove();const e=t.getResourceManager();for(const t of n.values())e.releaseTexture(t);n.clear(),0!==r&&(t._free(r),r=0,a=0)};let M=null;function P(e,l,u,h){(i.width<u||i.height<h)&&(i.width=Ri(Math.max(i.width,u)),i.height=Ri(Math.max(i.height,h))),o.clearRect(0,0,i.width,i.height);const d=l.backgroundColor;o.fillStyle=`rgba(${Math.round(255*d.r)}, ${Math.round(255*d.g)}, ${Math.round(255*d.b)}, ${d.a})`,o.fillRect(0,0,u,h),o.save(),o.beginPath(),o.rect(l.padding,0,u-2*l.padding,h),o.clip(),o.font=`${l.fontSize}px ${l.fontFamily}`,o.textBaseline="top",o.textAlign="left";const f=0===l.value.length,p=f?l.placeholder:l.password?"●".repeat(l.value.length):l.value,m=f?l.placeholderColor:l.color;o.fillStyle=`rgba(${Math.round(255*m.r)}, ${Math.round(255*m.g)}, ${Math.round(255*m.b)}, ${m.a})`;const _=Math.ceil(1.2*l.fontSize),g=l.padding;if(l.multiline){const e=Ci(o,p,u-2*g);let t=g;for(const s of e)o.fillText(s,g,t),t+=_}else{const e=(h-l.fontSize)/2;o.fillText(p,g,e)}if(l.focused&&c){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,s,n;if(l.multiline){const e=Ci(o,l.value,u-2*g);let i=0,r=0,a=0;for(let t=0;t<e.length;t++){const s=e[t].length;if(i+s>=l.cursorPos){r=t,a=l.cursorPos-i;break}i+=s,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,r=t+1,a=0}const c=r<e.length?e[r].substring(0,a):"";t=g+o.measureText(c).width,s=g+r*_,n=_}else t=g+o.measureText(e).width,s=(h-l.fontSize)/2,n=l.fontSize;o.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,o.fillRect(t,s,2,n)}o.restore();const y=o.getImageData(0,0,u,h),w=new Uint8Array(y.data.buffer),x=t.getResourceManager();w.length>a&&(0!==r&&t._free(r),r=t._malloc(w.length),a=w.length),t.HEAPU8.set(w,r);const v=n.get(e);void 0!==v&&x.releaseTexture(v);const b=x.createTexture(u,h,r,w.length,1,!0);n.set(e,b);const S=s.get(e,fe);S.texture=b,S.size.x=u,S.size.y=h,S.uvOffset.x=0,S.uvOffset.y=0,S.uvScale.x=1,S.uvScale.y=1,S.color={r:1,g:1,b:1,a:1},s.insert(e,fe,S)}e.addSystemToSchedule(gt.Update,xt([Ie(ko)],e=>{const t=s.getEntitiesWithComponents([Ro]);for(const e of t)zi(s,e,Ao,{tabIndex:0,isFocused:!1}),zi(s,e,co,{enabled:!0,blockRaycast:!0});const n=m();if(n!==M){if(null!==M&&s.valid(M)&&s.has(M,Ro)){const e=s.get(M,Ro);e.focused=!1,e.dirty=!0,p.blur()}null!==n&&function(e){const t=s.get(e,Ro);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),S())}(n),M=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(gt.PreUpdate,xt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===d?0:(e-d)/1e3;d=e,i=Math.min(i,.1);const o=m();if(null!==o&&(u+=i,u>=.5)){u-=.5,c=!c;s.get(o,Ro).dirty=!0}const r=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Ro)||(r.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Ro,yi]);for(const e of a){const t=s.get(e,Ro);if(!t.dirty)continue;const n=s.get(e,yi),i=Math.ceil(n.size.x),o=Math.ceil(n.size.y);i<=0||o<=0||(vi(s,e),P(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Bo=new Fo,zo={Simple:0,Sliced:1,Tiled:2,Filled:3},Uo={Horizontal:0,Vertical:1},$o={Left:0,Right:1,Bottom:2,Top:3},Do=K("Image",{texture:D,color:{r:1,g:1,b:1,a:1},imageType:zo.Simple,fillMethod:Uo.Horizontal,fillOrigin:$o.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Oo=$i({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,layer:e=>e.image.layer,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?Ii(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?ki(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class Lo{build(e){ie("Image",Do);const t=e.world,s=new Map;e.addSystemToSchedule(gt.PreUpdate,xt([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,Do)||s.delete(e);const e=t.getEntitiesWithComponents([Do]);for(const n of e){const e=t.get(n,Do),i=t.has(n,yi)?t.get(n,yi):null,o={image:e,uiRect:i,entity:n},r=s.get(n);if(r&&!Oo.changed(r,o))continue;vi(t,n);const a=t.get(n,fe);if(e.enabled){if(a.texture=e.texture,a.color.r=e.color.r,a.color.g=e.color.g,a.color.b=e.color.b,a.color.a=e.color.a,a.layer=e.layer,a.material=e.material,i&&(a.size.x=Ii(i,n),a.size.y=ki(i,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===zo.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===Uo.Horizontal?e.fillOrigin===$o.Left?(a.uvScale.x=t,a.size.x=s*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=s*t):e.fillOrigin===$o.Bottom?(a.uvScale.y=t,a.size.y=n*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=n*t)}else e.imageType===zo.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale.x=a.size.x/e.tileSize.x,a.uvScale.y=a.size.y/e.tileSize.y);t.insert(n,fe,a),s.set(n,Oo.take(o))}else a.color.a=0,t.insert(n,fe,a),s.set(n,Oo.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const Wo=new Lo,Ho=K("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),No=K("ToggleGroup",{allowSwitchOff:!1});class Xo{build(e){ie("Toggle",Ho),ie("ToggleGroup",No);const t=e.world,s=new Set;e.addSystemToSchedule(gt.Update,xt([Ie(mo)],e=>{const n=t.getEntitiesWithComponents([Ho]);if(!vo()||Mo()){const i=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,Ho);n.isOn&&0!==n.group&&t.valid(n.group)&&(i.has(n.group)?(n.isOn=!1,t.insert(e,Ho,n)):i.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,Ho);if(0!==s.group&&t.valid(s.group)){let t=o.get(s.group);t||(t=[],o.set(s.group,t)),t.push(e)}}for(const s of n){if(zi(t,s,co,{enabled:!0}),!t.has(s,uo))continue;const n=t.get(s,uo),i=t.get(s,Ho),r=t.get(s,co);if(n.justPressed&&r.enabled){const n=i.group,r=0!==n&&t.valid(n)&&t.has(n,No);if(i.isOn&&r){if(!t.get(n,No).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(s,Ho,i),i.isOn&&r){const i=o.get(n);if(i)for(const n of i){if(n===s)continue;const i=t.get(n,Ho);i.isOn&&(i.isOn=!1,t.insert(n,Ho,i),e.emit(n,"change"))}}e.emit(s,"change")}if(i.transition&&t.has(s,fe)){const e=t.get(s,fe);e.color=Ti(i.transition,r.enabled,n.pressed,n.hovered),t.insert(s,fe,e)}}}for(const e of n){const s=t.get(e,Ho);if(s.graphicEntity&&t.valid(s.graphicEntity)&&t.has(s.graphicEntity,fe)){const e=t.get(s.graphicEntity,fe);e.enabled=s.isOn,t.insert(s.graphicEntity,fe,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const jo=new Xo,Yo=_i,Vo=K("ProgressBar",{value:0,fillEntity:0,direction:_i.LeftToRight});function qo(e,t,s,n){if(!e.has(t,yi))return;const i=e.get(t,yi),o=s/2,r=n/2,a={left:-o,bottom:-r,right:o,top:r},l=gi(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,fe)){const s=e.get(t,fe);s.size.x===l.width&&s.size.y===l.height||(s.size.x=l.width,s.size.y=l.height,e.insert(t,fe,s))}if(e.has(t,ue)){const s=e.get(t,ue),n=s.position;n.x===l.originX&&n.y===l.originY||(s.position={x:l.originX,y:l.originY,z:n.z},e.insert(t,ue,s))}}class Go{build(e){ie("ProgressBar",Vo);const t=e.world;e.addSystemToSchedule(gt.PreUpdate,xt([],()=>{const e=t.getEntitiesWithComponents([Vo,yi]);for(const s of e){const e=t.get(s,Vo);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,yi),i=Math.max(0,Math.min(1,e.value));Pi(t,e.fillEntity,e.direction,i);const o=Ii(n,s),r=ki(n,s);qo(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Ko=new Go,Jo=K("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Qo=K("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});class Zo{build(e){ie("Draggable",Jo),ie("DragState",Qo);const t=e.world,s=e.getResource(mo);let n=null,i={x:0,y:0},o=null;e.addSystemToSchedule(gt.PreUpdate,xt([Ie(Et),Ie(At)],(e,r)=>{if(vo()&&!Mo())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Jo,uo]);let s=null,o=-1/0,r=-1;for(const n of e){if(!t.get(n,Jo).enabled)continue;if(t.get(n,uo).hovered){let e=0;t.has(n,fe)&&(e=t.get(n,fe).layer);const i=Ai(t,n);(e>o||e===o&&i>=r)&&(o=e,r=i,s=n)}}if(null!==s){n=s,i={x:a.x,y:a.y},t.has(s,Qo)||t.insert(s,Qo);const e=t.get(s,Qo),o=t.get(s,ue);e.startWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.currentWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==n&&!e.isMouseButtonDown(0)){if(t.valid(n)&&t.has(n,Qo)){t.get(n,Qo).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),u=t.get(n,Jo);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=n,n=null;t.get(o,Qo).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Qo))return void(o=null);const n=t.get(o,Qo),i=t.get(o,Jo),r=a.x-n.pointerStartWorld.x,l=a.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+r,u=n.startWorldPos.y+l;const h=function(e,t,s,n){let i=e.lockX?t.startWorldPos.x:s,o=e.lockY?t.startWorldPos.y:n;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:i,y:o}}(i,n,c,u);c=h.x,u=h.y;const d=n.currentWorldPos.x,f=n.currentWorldPos.y;if(n.deltaWorld={x:c-d,y:u-f},n.currentWorldPos={x:c,y:u},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:u-n.startWorldPos.y},t.has(o,ue)){const e=function(e,t,s,n){if(!e.has(t,ge))return{x:s,y:n};const i=e.get(t,ge).entity;if(!e.valid(i)||!e.has(i,ue))return{x:s,y:n};const o=e.get(i,ue),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=so(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(s*u-n*c)/r,y:(s*c+n*u)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,ue);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,ue,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}}const er=new Zo,tr=K("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function sr(e,t,s,n){return n<=0?1:e<t?Math.max(0,1-(t-e)/n):e>s?Math.max(0,1-(e-s)/n):1}function nr(e,t,s,n,i){const o=2/(n=Math.max(1e-4,n)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(s+o*l)*i,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(s-o*c)*a}}class ir{build(e){ie("ScrollView",tr);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(gt.PostUpdate,xt([Ie(Et),Ie(At),Ie(ze)],(e,i,o)=>{const r=vo()&&!Mo(),a=Math.min(o.delta,.05);for(const[e]of s)t.valid(e)||s.delete(e);i.valid&&(n.x=i.worldMouseX,n.y=i.worldMouseY);const l=t.getEntitiesWithComponents([tr,yi]);for(const o of l){zi(t,o,Ji,{enabled:!0,mode:Gi});const l=t.get(o,tr),c=t.get(o,yi);let u=s.get(o);u||(u={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},s.set(o,u));const h=Ii(c,o),d=ki(c,o);let f=l.contentWidth,p=l.contentHeight;if((0===f||0===p)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,ye)){const e=t.get(l.contentEntity,ye).entities;let s=0,n=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,ue))continue;const e=t.get(r,ue);let a=0,l=0,c=.5,u=.5;if(t.has(r,yi)){const e=t.get(r,yi);a=Ii(e,r)||e.size.x,l=ki(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,fe)){const e=t.get(r,fe);a=e.size.x,l=e.size.y}const h=e.position.x-a*c,d=e.position.x+a*(1-c),f=e.position.y-l*u,p=e.position.y+l*(1-u);h<s&&(s=h),d>n&&(n=d),f<i&&(i=f),p>o&&(o=p)}0===f&&(f=n-s),0===p&&(p=o-i)}const m=Math.max(0,f-h),_=Math.max(0,p-d);if(!r&&i.valid){zi(t,o,co,{enabled:!0,blockRaycast:!0});const s=t.has(o,uo)?t.get(o,uo):null;if(s?.justPressed&&(u.isDragging=!0,u.lastWorldX=n.x,u.lastWorldY=n.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=n.x-u.lastWorldX,t=n.y-u.lastWorldY,s=Math.min(1,10*a);if(l.horizontalEnabled){const t=sr(l.scrollX,0,m,h);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const n=a>0?-e*t/a:0;u.velocityX+=(n-u.velocityX)*s}}if(l.verticalEnabled){const e=sr(l.scrollY,0,_,d);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const n=a>0?t*e/a:0;u.velocityY+=(n-u.velocityY)*s}}u.lastWorldX=n.x,u.lastWorldY=n.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*h,t=5*d;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(s?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=sr(l.scrollY,0,_,d);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=sr(l.scrollX,0,m,h);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>_;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=nr(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<Di&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Di?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:_,t=nr(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<Di&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Di?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,m)),l.scrollY=Math.max(0,Math.min(l.scrollY,_)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*h,t=.5*d;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,_+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,ue)){const e=t.get(l.contentEntity,ue),s=e.position.x,n=e.position.y;(isNaN(u.lastAppliedX)||Math.abs(s-u.lastAppliedX)>.01)&&(u.contentBaseX=s),(isNaN(u.lastAppliedY)||Math.abs(n-u.lastAppliedY)>.01)&&(u.contentBaseY=n),e.position.x=u.contentBaseX-l.scrollX,e.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=e.position.x,u.lastAppliedY=e.position.y,t.insert(l.contentEntity,ue,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const or=new ir,rr=_i,ar=K("Slider",{value:0,minValue:0,maxValue:1,direction:_i.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function lr(e,t,s,n,i,o){const r=Ii(n,i)*s.worldScale.x,a=ki(n,i)*s.worldScale.y,l=so(s.worldRotation.z,s.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),h=e-s.worldPosition.x,d=t-s.worldPosition.y,f=h*u-d*c,p=h*c+d*u,m=-n.pivot.x*r,_=-n.pivot.y*a;switch(o){case _i.LeftToRight:return r>0?(f-m)/r:0;case _i.RightToLeft:return r>0?1-(f-m)/r:0;case _i.BottomToTop:return a>0?(p-_)/a:0;case _i.TopToBottom:return a>0?1-(p-_)/a:0}}function cr(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case _i.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case _i.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case _i.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case _i.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class ur{build(e){ie("Slider",ar);const t=e.world;let s=null;e.addSystemToSchedule(gt.PreUpdate,xt([Ie(Et),Ie(At),Ie(mo)],(e,n,i)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([ar,yi]);for(const r of o){const o=t.get(r,ar),a=t.get(r,yi);if(!vo()||Mo()){if(t.has(r,ue)){zi(t,r,co,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&zi(t,o.handleEntity,co,{enabled:!0,blockRaycast:!1});const l=t.get(r,ue),c=t.has(r,uo)?t.get(r,uo):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,uo)&&(u=t.get(o.handleEntity,uo).justPressed),u&&(s=r),s===r&&e.isMouseButtonDown(0)){let e=lr(n.worldMouseX,n.worldMouseY,l,a,r,o.direction);e=Math.max(0,Math.min(1,e));let s=o.minValue+e*(o.maxValue-o.minValue);o.wholeNumbers&&(s=Math.round(s));const c=o.value;o.value=Math.max(o.minValue,Math.min(o.maxValue,s)),t.insert(r,ar,o),o.value!==c&&i.emit(r,"change")}s===r&&e.isMouseButtonReleased(0)&&(s=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,u=Ii(a,r),h=ki(a,r),d={left:-u/2,bottom:-h/2,right:u/2,top:h/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(Pi(t,o.fillEntity,o.direction,c),Ui(t,o.fillEntity,d,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,yi)){const e=t.get(o.handleEntity,yi);cr(e,o.direction,c),t.insert(o.handleEntity,yi,e),Ui(t,o.handleEntity,d,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const hr=new ur;class dr{build(e){ie("Focusable",Ao);const t=e.world,s=new Io;e.insertResource(ko,s),e.addSystemToSchedule(gt.Update,xt([Ie(Et),Ie(mo)],(e,n)=>{if(vo()&&!Mo())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const i=t.getEntitiesWithComponents([Ao]);for(const e of i){if(!t.has(e,uo))continue;t.get(e,uo).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const n=function(){const e=[];for(const s of i){if(!t.valid(s))continue;if(t.has(s,co)){if(!t.get(s,co).enabled)continue}const n=t.get(s,Ao);e.push({entity:s,tabIndex:n.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===n.length)return;const r=null!==s.focusedEntity?n.findIndex(e=>e===s.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?n.length-1:0:a?(r-1+n.length)%n.length:(r+1)%n.length,o(n[l])}function o(e){const i=s.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Ao)){t.get(i,Ao).isFocused=!1,n.emit(i,"blur",i)}s.focus(e);t.get(e,Ao).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const fr=new dr,pr=K("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function mr(){return i()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:s,screenWidth:n,screenHeight:i}=t;return{top:s.top,bottom:i-s.bottom,left:s.left,right:n-s.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}class _r{build(e){ie("SafeArea",pr);const t=e.world;let s=mr(),n=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{s=mr(),n=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{s=mr(),n=!0});e.addSystemToSchedule(gt.PreUpdate,xt([Ie(At)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===r||(o=e.screenH,r=a,n=!0),!n)return;n=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([pr,yi]);for(const e of u){const n=t.get(e,pr),i=t.get(e,yi),o=n.applyTop?s.top*c:0,r=n.applyBottom?s.bottom*c:0,a=n.applyLeft?s.left*c:0,l=n.applyRight?s.right*c:0;let u=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},u=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,yi,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const gr=new _r,yr=K("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let wr=null;function xr(e,t){if(!wr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=wr.get(e);s?s.renderer=t:wr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}class vr{build(e){ie("ListView",yr);const t=e.world,s=new Map;wr=s,e.addSystemToSchedule(gt.PostUpdate,xt([Ie(Et)],e=>{const n=vo()&&!Mo();for(const[e,n]of s)if(!t.valid(e)){for(const e of n.itemEntities.values())t.valid(e)&&t.despawn(e);s.delete(e)}const i=t.getEntitiesWithComponents([yr,yi]);for(const o of i){zi(t,o,co,{enabled:!0,blockRaycast:!0}),zi(t,o,Ji,{enabled:!0,mode:Gi});let i=s.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},s.set(o,i));const r=t.get(o,yr),a=t.get(o,yi),l=ki(a,o),c=Ii(a,o);if(!n){const s=t.has(o,uo)?t.get(o,uo):null;if(s?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const u=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,u));const h=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),d=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,s]of i.itemEntities)(e<h||e>=d)&&(t.valid(s)&&t.despawn(s),i.itemEntities.delete(e));for(let e=h;e<d;e++){let s=i.itemEntities.get(e);if(s&&t.valid(s)||(s=t.spawn(),t.insert(s,ve,{value:`ListItem_${e}`}),t.insert(s,yi,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(s,o),i.itemEntities.set(e,s),i.renderer&&i.renderer(e,s)),t.has(s,ue)){const n=t.get(s,ue);n.position.y=-(e*r.itemHeight-r.scrollY),t.insert(s,ue,n)}}i.visibleStart=h,i.visibleEnd=d}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const br=new vr,Sr=K("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class Mr{build(e){ie("Dropdown",Sr);const t=e.world,s=new Map;function n(e){if(0===e||!t.valid(e))return;if(!t.has(e,ue))return;const s=t.get(e,ue);0===s.scale.x&&0===s.scale.y&&0===s.scale.z&&t.insert(e,ue,{position:{x:s.position.x,y:s.position.y,z:s.position.z},rotation:{x:s.rotation.x,y:s.rotation.y,z:s.rotation.z,w:s.rotation.w},scale:{x:1,y:1,z:1}})}function i(e){if(t.has(e,fe)){const s=t.get(e,fe);1===s.color.r&&1===s.color.g&&1===s.color.b&&1===s.color.a&&t.insert(e,fe,{texture:s.texture,color:{r:.9,g:.9,b:.9,a:1},size:{x:s.size.x,y:s.size.y},uvOffset:{x:s.uvOffset.x,y:s.uvOffset.y},uvScale:{x:s.uvScale.x,y:s.uvScale.y},layer:s.layer,flipX:s.flipX,flipY:s.flipY,material:s.material,enabled:s.enabled})}}function o(e,s,n){s.isOpen=!0,n.highlightIndex=s.selectedIndex;const i=s.listEntity;if(0===i||!t.valid(i))return;u(i,!0),c(n);const o=t.get(e,fe),r=o.size.x,a=o.size.y;n.ddWidth=r;const l=s.options.length*Oi;t.insert(i,yi,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:l},pivot:{x:.5,y:.5}}),t.insert(i,ue,{position:{x:0,y:-(a+l)/2,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(i,fe,{texture:D,color:{r:1,g:1,b:1,a:1},size:{x:r,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<s.options.length;e++){const o=t.spawn(),a=l/2-(e+.5)*Oi;t.insert(o,ve,{value:`Option_${e}`}),t.insert(o,yi,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Oi},offsetMax:{x:0,y:0},size:{x:r,y:Oi},pivot:{x:.5,y:.5}}),t.insert(o,ue,{position:{x:0,y:a,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(o,fe,{texture:D,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:Oi},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,co,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),n.optionEntities.push(o);const c=t.spawn();t.insert(c,ue,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(c,Xi,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Wi.Left,verticalAlign:Hi.Middle,wordWrap:!1,overflow:Ni.Clip,lineHeight:1.2}),t.insert(c,yi,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:Oi},pivot:{x:.5,y:.5}}),t.setParent(c,o),n.textEntities.push(c)}h(n)}function r(e,t,s){t.isOpen=!1,c(s),u(t.listEntity,!1)}function a(e,t,s,n,i){t.selectedIndex=n,r(0,t,s),i.emit(e,"change")}function l(e){const s=e.labelEntity;if(0===s||!t.valid(s))return;if(!t.has(s,Xi))return;const n=t.get(s,Xi);let i={r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},o=n.content,r=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},r=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,r=!0)}r&&t.insert(s,Xi,{content:o,fontSize:n.fontSize,fontFamily:n.fontFamily,color:i,align:n.align,verticalAlign:n.verticalAlign,wordWrap:n.wordWrap,overflow:n.overflow,lineHeight:n.lineHeight})}function c(e){for(const s of e.textEntities)t.valid(s)&&t.despawn(s);for(const s of e.optionEntities)t.valid(s)&&t.despawn(s);e.optionEntities=[],e.textEntities=[]}function u(e,s){if(0!==e&&t.valid(e)&&(t.has(e,co)&&t.insert(e,co,{enabled:s,blockRaycast:!0,raycastTarget:!0}),t.has(e,fe))){const n=t.get(e,fe);t.insert(e,fe,{texture:n.texture,color:{r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:s})}}function h(e){for(let s=0;s<e.optionEntities.length;s++){const n=e.optionEntities[s];if(!t.valid(n)||!t.has(n,fe))continue;const i=s===e.highlightIndex?{...Li}:{r:.95,g:.95,b:.95,a:1};t.insert(n,fe,{texture:D,color:i,size:{x:e.ddWidth,y:Oi},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function d(e){for(const s of e.optionEntities){if(!t.valid(s)||!t.has(s,uo))continue;if(t.get(s,uo).hovered)return!0}return!1}e.addSystemToSchedule(gt.Update,xt([Ie(Et),Ie(mo)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const f=vo()&&!Mo(),p=t.getEntitiesWithComponents([Sr]);for(const m of p){const p=t.get(m,Sr);let _=s.get(m);if(_||(_={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},s.set(m,_)),n(p.listEntity),i(m),p.isOpen||u(p.listEntity,!1),l(p),f)continue;zi(t,m,co,{enabled:!0,blockRaycast:!0});const g=t.has(m,uo)?t.get(m,uo):null;if(g?.justPressed&&(p.isOpen?r(m,p,_):o(m,p,_)),p.isOpen){for(let e=0;e<_.optionEntities.length;e++){const s=_.optionEntities[e];if(!t.valid(s)||!t.has(s,uo))continue;if(t.get(s,uo).justPressed){a(m,p,_,e,c);break}}let s=-1;for(let e=0;e<_.optionEntities.length;e++){const n=_.optionEntities[e];if(!t.valid(n)||!t.has(n,uo))continue;if(t.get(n,uo).hovered){s=e;break}}s>=0&&s!==_.highlightIndex&&(_.highlightIndex=s,h(_)),e.isKeyPressed("ArrowDown")?(_.highlightIndex>=p.options.length-1?_.highlightIndex=0:_.highlightIndex++,h(_)):e.isKeyPressed("ArrowUp")?(_.highlightIndex<=0?_.highlightIndex=p.options.length-1:_.highlightIndex--,h(_)):e.isKeyPressed("Enter")&&_.highlightIndex>=0?a(m,p,_,_.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,p,_),e.isMouseButtonPressed(0)&&(g?.hovered||d(_)||r(m,p,_))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}}const Pr=new Mr,Tr=0,Er=0,Cr=2,Rr=K("LayoutGroup",{direction:Tr,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Er,reverseOrder:!1});class Ar{build(e){ie("LayoutGroup",Rr);const t=e.world;e.addSystemToSchedule(gt.PreUpdate,xt([],()=>{const e=t.getEntitiesWithComponents([Rr,yi,ye]);for(const s of e){const e=t.get(s,Rr),n=t.get(s,yi),i=t.get(s,ye);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,yi)&&t.has(e,ue)&&o.push({entity:e,rect:t.get(e,yi)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=Ii(n,s),a=ki(n,s),l=n.pivot.x,c=n.pivot.y,u=e.padding,h=e.direction===Tr;let d=0;for(let s=0;s<o.length;s++){const n=o[s],i=Ii(n.rect,n.entity),f=ki(n.rect,n.entity),p=n.rect.pivot.x,m=n.rect.pivot.y;let _,g;h?(_=-l*r+u.left+d+p*i,g=e.childAlignment===Er?(1-c)*a-u.top-(1-m)*f:e.childAlignment===Cr?-c*a+u.bottom+m*f:(.5-c)*a+.5*(u.bottom-u.top)+(m-.5)*f,d+=i,s<o.length-1&&(d+=e.spacing)):(_=e.childAlignment===Er?-l*r+u.left+p*i:e.childAlignment===Cr?(1-l)*r-u.right-(1-p)*i:(.5-l)*r+.5*(u.left-u.right)+(p-.5)*i,g=(1-c)*a-u.top-d-(1-m)*f,d+=f,s<o.length-1&&(d+=e.spacing));const y=t.get(n.entity,ue);y.position.x=_,y.position.y=g,t.insert(n.entity,ue,y)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}}const Ir=new Ar;class kr{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(gt.PostUpdate,xt([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const Fr=new kr;async function Br(e,t,s){const n=e.getResource(Jn);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function zr(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 Ur=Ae({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),$r=Ae(null,"PhysicsAPI");function Dr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Or(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(Ur,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=zr(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const i=function(e){const t=e.world.getEntitiesWithComponents([me]);for(const s of t){const t=e.world.get(s,me);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/i,r=e.world;r.onDespawn(e=>{t.has(e)&&(n._physics_destroyBody(e),t.delete(e),s.delete(e))}),e.addSystemToSchedule(gt.PostUpdate,xt([Ie(ze)],a=>{const l=r.getEntitiesWithComponents([Me,ue]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,Me),l=r.get(i,ue);if(t.has(i)){const e=s.get(i);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(i,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const r=Dr(l.worldRotation);n._physics_createBody(i,a.bodyType,l.worldPosition.x*o,l.worldPosition.y*o,r,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Wr(e,n,i),t.add(i),s.set(i,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===Ce.Kinematic){const e=Dr(l.worldRotation);n._physics_setBodyTransform(i,l.worldPosition.x*o,l.worldPosition.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 i=t._physics_getDynamicBodyTransforms(),o=i>>2;for(let i=0;i<n;i++){const n=o+4*i,r=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(r))continue;const u=e.world.get(r,ue);if(!u)continue;let h=a,d=l,f=c;if(e.world.has(r,ge)){const t=e.world.get(r,ge);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ue)){const s=e.world.get(t.entity,ue),n=Dr(s.worldRotation),i=a-s.worldPosition.x,o=l-s.worldPosition.y,r=Math.cos(-n),u=Math.sin(-n);h=(i*r-o*u)/(0!==s.worldScale.x?s.worldScale.x:1),d=(i*u+o*r)/(0!==s.worldScale.y?s.worldScale.y:1),f=c-n}}u.position.x=h,u.position.y=d;const p=Or(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(r,ue,u)}}(e,n,i),function(e,t,s){t._physics_collectEvents();const n=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<i;o++){const i=e+6*o;n.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*s,contactY:t.HEAPF32[i+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 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(Ur,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,i)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource($r,Hr._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function Wr(e,t,s){const n=e.world;if(n.has(s,Pe)){const e=n.get(s,Pe);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,Te)){const e=n.get(s,Te);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,Ee)){const e=n.get(s,Ee);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Hr{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(Hr.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}const Nr={nearest:0,linear:1},Xr={repeat:0,clamp:1,mirror:2};function jr(e,t,s=!0,n){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),n&&(n.filterMode||n.wrapMode)&&i.createTextureEx){const e=Nr[n.filterMode??"linear"]??1,a=Xr[n.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,s,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,s);return e._free(o),r}function Yr(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 Vr(e,t,s,n){const i=e.worldScale.x*t*(s?-1:1),o=e.worldScale.y*t*(n?-1:1),r=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,u=e.worldRotation.w,h=a+a,d=l+l,f=c+c,p=a*h,m=a*d,_=a*f,g=l*d,y=l*f,w=c*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(g+w))*i,(m+b)*i,(_-v)*i,0,(m-b)*o,(1-(p+w))*o,(y+x)*o,0,(_+v)*r,(y-x)*r,(1-(p+g))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function qr(e){const{app:t,module:s,sceneData:n,provider:i,spineModule:o,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,u=await async function(e,t,s){const n={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=us(t.type);for(const r of o){if("texture"!==r.type)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===n[o])try{const t=i?.[o];n[o]=jr(e,await s.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),n[o]=0}}}return n}(s,n,i);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const i=s[e];if(i&&i>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(s,n,u);let h={},d=null;if(o&&(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"])}}(o),h=await async function(e,t,s,n,i){const o={};for(const r of n.entities)for(const n of r.components){const r=hs(n.type);if(!r||!n.data)continue;const a=n.data[r.skeletonField],l=n.data[r.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),u=i.resolvePath(l);try{const n=await i.readText(l),r="binary"===Cs(c)?.contentType;let h,d;if(r){const e=await i.readBinary(a);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=await i.readText(a),s=(new TextEncoder).encode(e);d=s.length,h=t._malloc(d+1),t.HEAPU8.set(s,h),t.HEAPU8[h+d]=0}const f=s.loadSkeleton(h,d,n,n.length,r);if(t._free(h),f<0)continue;o[a]=f;const p=Yr(n),m=u.substring(0,u.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=m+"/"+p[t];try{const o=i.loadPixelsRaw?await i.loadPixelsRaw(n):await i.loadPixels(n),r=jr(e,o,!1),a=e.getResourceManager().getTextureGLId(r);s.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(s,o,d,n,i)),r){const e={gravity:a?.gravity??{...A},fixedTimestep:a?.fixedTimestep??I,subStepCount:a?.subStepCount??4};new Lr("",e,()=>Promise.resolve(r)).build(t)}const f=await async function(e,t,s){const n={};for(const i of t.entities)for(const t of i.components){const i=us(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{let t,i;const r=Cs(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await s.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){n[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await s.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),u=jr(e,c,!1),h=e.getResourceManager();n[o]=h.loadBitmapFont(t,u,c.width,c.height)}catch{n[o]=0}}return n}(s,n,i),p=await async function(e,t){const s={},n={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=us(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){s[o]=0;continue}const i=e.vertexSource+e.fragmentSource;let r=n[i];r||(r=Lt.createShader(e.vertexSource,e.fragmentSource),n[i]=r),s[o]=Lt.createFromAsset(e,r)}catch{s[o]=0}}return s}(n,i);await async function(e,t,s){const n=new Set;for(const i of t.entities)for(const t of i.components){const i=us(t.type);for(const o of i){if("anim-clip"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!n.has(i)){n.add(i);try{const t=await s.readText(i),n=JSON.parse(t),o=Jt(n),r=new Map;for(const t of o)try{const n=await s.loadPixels(t);r.set(t,jr(e,n))}catch{r.set(t,0)}es(Qt(i,n,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(s,n,i),await async function(e){const t=[],s=new Set;for(const n of e.entities)for(const e of n.components){const n=us(e.type);for(const i of n){if("audio"!==i.type)continue;const n=e.data[i.field];"string"==typeof n&&n&&!s.has(n)&&(s.add(n),t.push(n))}}t.length>0&&await rs.preloadAll(t).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)})}(n),function(e,t,s,n){const i={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=us(e.type);if(0===t.length)continue;const s=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof s[e.field]&&(s[e.field]=t[s[e.field]]||0)}}}(n,u,f,p);const m=gs(t.world,n);if(c&&t.hasResource(Jn))for(const e of m.values())t.world.insert(e,be,{scene:c,persistent:!1});if(o&&d){const e=function(e,t,s,n){const i={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const r=hs(t.type);if(!r||!t.data)continue;const a=s[t.data[r.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=n.get(o.id);void 0!==c&&(i[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return i}(d,n,h,m);!function(e,t,s,n,i){let o=0;e.setSpineRenderer((r,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=R);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,xe)?c.get(o,xe):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&n.update(r,l*h);let d=0;if(c.has(o,ue)){const e=Vr(c.get(o,ue),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=n.getMeshBatchCount(r);for(let e=0;e<f;e++){const i=n.getMeshBatchVertexCount(r,e),o=n.getMeshBatchIndexCount(r,e);if(!i||!o)continue;const a=8*i*4,l=2*o,c=s._malloc(a),u=s._malloc(l),h=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(r,e,c,u,h,f);const p=s.HEAPU32[h>>2],m=s.HEAPU32[f>>2],_=new Float32Array(s.HEAPF32.buffer,c,8*i),g=new Uint16Array(s.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,i,w,o,p,m,d),t._free(y),t._free(w),s._free(c),s._free(u),s._free(h),s._free(f)}d&&t._free(d)}})}(t,s,o,d,e)}if(l){const e=t.getResource(Ns);e&&e.setAddressableManifest(l)}}function Gr(e,t,s){return{name:e,async setup(){await qr({...s,sceneData:t,sceneName:e})}}}async function Kr(e){const{app:t,firstScene:s,aspectRatio:n}=e;si(t);const i={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},o=t.getResource(Jn);for(const t of e.scenes)o.register(Gr(t.name,t.data,i));s&&(o.setInitial(s),await o.load(s)),void 0!==n&&vs(t.world,n)}class Jr{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 i of e.entities)for(const e of i.components){if(!e.data)continue;const i=hs(e.type);if(i){const n=e.data[i.skeletonField],o=e.data[i.atlasField];n&&("binary"===Cs(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=us(e.type);for(const s of o){const i=e.data[s.field];"string"==typeof i&&i&&("font"===s.type?(n.add(i),t.add(i)):("material"===s.type||"anim-clip"===s.type)&&t.add(i))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const o=[];for(const e of n){const t=Cs(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(),i=await createImageBitmap(n),o=new OffscreenCanvas(i.width,i.height).getContext("2d");o.drawImage(i,0,0);const r=o.getImageData(0,0,i.width,i.height);return i.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Qr="__preview__";class Zr{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(Jn);t.register({name:Qr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Qr),this.loadPromise_=t.load(Qr).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await r(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new Jr(this.baseUrl_);await s.prefetch(t);let n=null;const i=this.app_.spineInitPromise;if(i){n=(await i).controller.raw}await qr({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:s,spineModule:n,sceneName:Qr})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([pe]);for(const n of s){if(e.get(n,pe).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1.7777777777777777;const n=e.getEntitiesWithComponents([me]);for(const i of n){const n=e.get(i,me);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const i=this.app_.getResource(Jn).getScene(Qr),o=i?i.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,ue,r);const a={isActive:!0,projectionType:ae.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:le.ColorAndDepth};e.insert(o,pe,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(Jn);await e.switchTo(Qr),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 ea={create(e){const t=e.depth??!0,s="linear"===e.filter,n=(t?1:0)|(s?2:0),i=Wn.createRenderTarget(e.width,e.height,n);return{_handle:i,textureId:Wn.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:s?"linear":"nearest"}},release(e){Wn.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Wn.releaseRenderTarget(e._handle),ea.create({width:t,height:s,depth:e._depth,filter:e._filter})),begin(e,t){Wn.begin(t,e._handle)},end(){Wn.end()},getDepthTexture:e=>Wn.getTargetDepthTexture(e._handle)};var ta;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(ta||(ta={}));class sa{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${ta[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case ta.Debug:console.debug(t,s);break;case ta.Info:console.log(t,s);break;case ta.Warn:console.warn(t,s);break;case ta.Error:console.error(t,s)}}}class na{constructor(){this.handlers_=[],this.minLevel_=ta.Info,this.addHandler(new sa)}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(ta.Debug,e,t,s)}info(e,t,s){this.log(ta.Info,e,t,s)}warn(e,t,s){this.log(ta.Warn,e,t,s)}error(e,t,s){this.log(ta.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const i={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const ia=new na;function oa(){return ia}function ra(e){ia.setMinLevel(e)}function aa(e,t,s){ia.debug(e,t,s)}function la(e,t,s){ia.info(e,t,s)}function ca(e,t,s){ia.warn(e,t,s)}function ua(e,t,s){ia.error(e,t,s)}const ha={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},da={Running:0,Paused:1,Completed:2,Cancelled:3},fa={None:0,Restart:1,PingPong:2};const pa=1.70158,ma=2.70158,_a=2.5949095;const ga=2*Math.PI/3,ya=2*Math.PI/4.5;const wa=7.5625,xa=2.75;const va=1e-6;function ba(e,t,s){switch(e){case ha.Linear:return t;case ha.EaseInQuad:return function(e){return e*e}(t);case ha.EaseOutQuad:return function(e){return e*(2-e)}(t);case ha.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case ha.EaseInCubic:return function(e){return e*e*e}(t);case ha.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case ha.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case ha.EaseInBack:return function(e){return ma*e*e*e-pa*e*e}(t);case ha.EaseOutBack:return function(e){const t=e-1;return 1+ma*t*t*t+pa*t*t}(t);case ha.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-_a)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+_a)+2)/2}(t);case ha.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*ga)}(t);case ha.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*ga)+1}(t);case ha.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*ya)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*ya)/2+1}(t);case ha.EaseOutBounce:return function(e){return e<1/xa?wa*e*e:e<2/xa?wa*(e-=1.5/xa)*e+.75:e<2.5/xa?wa*(e-=2.25/xa)*e+.9375:wa*(e-=2.625/xa)*e+.984375}(t);case ha.CubicBezier:return s?function(e,t,s,n,i){let o=e;for(let s=0;s<8;s++){const s=1-o,i=3*t*s*s*o+3*n*s*o*o+o*o*o-e;if(Math.abs(i)<va)break;const r=3*t*(1-2*o)*(1-o)+6*n*o*(1-o)-3*n*o*o+3*o*o;if(Math.abs(r)<va)break;o-=i/r}const r=1-o;return 3*s*r*r*o+3*i*r*o*o+o*o*o}(t,s.p1x,s.p1y,s.p2x,s.p2y):t;case ha.Step:return function(e){return e<1?0:1}(t);default:return t}}const Sa=new class{constructor(){this.entries_=new Map,this.nextId_=1,this.cppSequences_=new Map,this.module_=null,this.registry_=null}init(e,t){this.module_=e,this.registry_=t}create(e,t,s,n,i){const o=this.nextId_++;return this.entries_.set(o,{id:o,from:e,to:t,duration:s,elapsed:0,delay:i?.delay??0,easing:i?.easing??ha.Linear,bezierPoints:null,state:da.Running,loop:i?.loop??fa.None,loopCount:i?.loopCount??0,loopsRemaining:i?.loopCount??0,callback:n,sequenceNext:null,sequenceNextExternal:null}),o}update(e){if(this.module_&&this.registry_)for(const[e,t]of this.cppSequences_){this.module_._anim_getTweenState(this.registry_,e)===da.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==da.Running)continue;if(t.delay>0){if(t.delay-=e,t.delay>0)continue;e=-t.delay,t.delay=0}t.elapsed+=e;const s=Math.min(t.elapsed/t.duration,1),n=ba(t.easing,s,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*n),s>=1){if(t.loop!==fa.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===fa.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=da.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===da.Running&&(t.state=da.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===da.Paused&&(t.state=da.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=da.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:da.Cancelled}setBezier(e,t,s,n,i){const o=this.entries_.get(e);o&&(o.bezierPoints={p1x:t,p1y:s,p2x:n,p2y:i})}setSequenceNext(e,t){const s=this.entries_.get(e);s&&(s.sequenceNext=t,this.pause(t))}setSequenceNextExternal(e,t){const s=this.entries_.get(e);s&&(s.sequenceNextExternal=t,t.pause())}registerCppSequence(e,t){this.cppSequences_.set(e,t),this.pause(t)}shutdown(){this.entries_.clear(),this.cppSequences_.clear(),this.module_=null,this.registry_=null,this.nextId_=1}};class Ma{constructor(e){this.id=e}get state(){return Sa.getState(this.id)}bezier(e,t,s,n){return Sa.setBezier(this.id,e,t,s,n),this}then(e){return e instanceof Ma?Sa.setSequenceNext(this.id,e.id):Sa.setSequenceNextExternal(this.id,e),this}pause(){Sa.pause(this.id)}resume(){Sa.resume(this.id)}cancel(){Sa.cancel(this.id)}}const Pa={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12};class Ta{constructor(e,t,s){this.module_=e,this.registry_=t,this.entity=s}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,s,n){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,s,n),this}then(e){return e instanceof Ma?(Sa.registerCppSequence(this.entity,e.id),this):(this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this)}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let Ea=null,Ca=null;function Ra(e,t){Ea=e,Ca=t,Sa.init(e,t)}function Aa(){Sa.shutdown(),Ea=null,Ca=null}function Ia(){if(!Ea)throw new Error("Tween API not initialized");return Ea}function ka(){if(!Ca)throw new Error("Tween API not initialized");return Ca}const Fa={to(e,t,s,n,i,o){const r=Ia(),a=ka(),l=o?.easing??ha.Linear,c=o?.delay??0,u=o?.loop??fa.None,h=o?.loopCount??0,d=r._anim_createTween(a,e,t,s,n,i,l,c,u,h);return new Ta(r,a,d)},value(e,t,s,n,i){const o=Sa.create(e,t,s,n,i);return new Ma(o)},cancel(e){Ia()._anim_cancelTween(ka(),e.entity)},cancelAll(e){Ia()._anim_cancelAllTweens(ka(),e)},update(e){Ia()._anim_updateTweens(ka(),e),Sa.update(e)}};class Ba{constructor(){this.name="AnimationPlugin"}build(e){Ra(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(gt.Update,xt([Ie(ze)],e=>{Fa.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(gt.Update,xt([Ie(ze)],e=>{os(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){Aa()}}const za=new Ba;var Ua;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(Ua||(Ua={}));const $a={model:Ua.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function Da(e,t=$a){const{model:s,refDistance:n,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(s){case Ua.Linear:{const e=i-n;if(e<=0)return 1;a=1-(Math.min(Math.max(r,n),i)-n)/e;break}case Ua.Inverse:a=n/Math.max(r,n);break;case Ua.Exponential:a=Math.pow(Math.max(r,n)/n,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function Oa(e,t,s,n,i){const o=e-s;return Math.max(-1,Math.min(1,o/i))}const La=K("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:Ua.Inverse,rolloff:1,priority:0,enabled:!0}),Wa=K("AudioListener",{enabled:!0});class Ha{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const s=t().createAudioBackend(),n=this.config_;s.initialize({initialPoolSize:n.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const i=s.mixer;rs.init(s,i),i&&(void 0!==n.masterVolume&&(i.master.volume=n.masterVolume),void 0!==n.musicVolume&&(i.music.volume=n.musicVolume),void 0!==n.sfxVolume&&(i.sfx.volume=n.sfxVolume));const o=new Map;this.activeSourceHandles_=o;const r=new Set;this.playedEntities_=r;const a=new Set;let l=!1,c=!1;e.addSystemToSchedule(gt.PreUpdate,xt([Ie(ze)],t=>{if(!(!vo()||Mo()))return void(c&&(l=!1,c=!1));c=!0;const n=e.world;let i=0,u=0,h=!1;const d=n.getEntitiesWithComponents([Wa,de]);for(const e of d){if(n.get(e,Wa).enabled){const t=n.get(e,de);i=t.position.x,u=t.position.y,h=!0;break}}const f=n.getEntitiesWithComponents([La]);a.clear();for(const e of f){const t=n.get(e,La);if(!t.enabled||!t.clip)continue;const c=e;if(a.add(c),t.playOnAwake&&!r.has(c)&&!o.has(c)&&s.isReady){const e=rs.getBufferHandle(t.clip);if(e){const n=s.play(e,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});o.set(c,n),r.add(c)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(c)){const s=o.get(c);if(!s.isPlaying){o.delete(c);continue}h||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=n.tryGet?.(e,de),a=r?.position.x??0,d=r?.position.y??0,f=a-i,p=d-u,m=Da(Math.sqrt(f*f+p*p),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),_=Oa(a,0,i,0,t.maxDistance);s.setVolume(t.volume*m),s.setPan(_)}}for(const[e,t]of o)a.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),rs.dispose()}}const Na=new Ha;function Xa(e,t){return e.toFixed(t)}function ja(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}class Ya{constructor(e,t="bottom-left"){this.visible_=!0,this.disposed_=!1,this.el_=document.createElement("div"),this.el_.style.cssText="\nposition: fixed;\nz-index: 99999;\npointer-events: none;\nbackground: rgba(30, 30, 30, 0.85);\nborder: 1px solid rgba(60, 60, 60, 0.8);\nborder-radius: 4px;\npadding: 6px 10px;\nfont: 11px monospace;\ncolor: #cccccc;\nline-height: 1.6;\nmin-width: 200px;\nwhite-space: pre;\n"+function(e){switch(e){case"top-left":return"top: 12px; left: 12px;";case"top-right":return"top: 12px; right: 12px;";case"bottom-left":return"bottom: 12px; left: 12px;";case"bottom-right":return"bottom: 12px; right: 12px;"}}(t),e.appendChild(this.el_)}update(e){if(!this.visible_||this.disposed_)return;const t=[];if(t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div><div>FPS: <span style="color:#d19a66">${Xa(e.fps,1)}</span> Frame: <span style="color:#d19a66">${Xa(e.frameTimeMs,1)}ms</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div><div>DC: <span style="color:#d19a66">${e.drawCalls}</span> Tri: <span style="color:#d19a66">${e.triangles}</span></div><div>Sprites: <span style="color:#d19a66">${e.sprites}</span> Culled: <span style="color:#d19a66">${e.culled}</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div><div>Entities: <span style="color:#d19a66">${e.entityCount}</span></div>`),e.systemTimings.size>0){const s=[...e.systemTimings.entries()].sort((e,t)=>t[1]-e[1]).slice(0,5);let n='<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';for(const[e,t]of s){n+=`<div>${ja(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${Xa(t,1)}ms</span></div>`}t.push(n)}this.el_.innerHTML=t.join("")}show(){this.visible_=!0,this.el_.style.display=""}hide(){this.visible_=!1,this.el_.style.display="none"}dispose(){this.disposed_=!0,this.el_.parentElement?.removeChild(this.el_)}}function Va(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const qa=Ae(Va(),"Stats");class Ga{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,s){const n={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:s?new Map(s):new Map};this.count_<this.capacity_?(this.buffer_.push(n),this.count_++):this.buffer_[this.cursor_]=n,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}}const Ka="StatsCollect";class Ja{constructor(){this.deltas_=[],this.cursor_=0,this.count_=0,this.sum_=0}pushFrame(e){!Number.isFinite(e)||e<0||(this.count_<60?(this.deltas_.push(e),this.sum_+=e,this.count_++):(this.sum_-=this.deltas_[this.cursor_],this.deltas_[this.cursor_]=e,this.sum_+=e,this.cursor_=(this.cursor_+1)%60))}getFps(){return 0===this.count_||this.sum_<=0?0:this.count_/this.sum_}getFrameTimeMs(){return 0===this.count_||this.sum_<=0?0:this.sum_/this.count_*1e3}reset(){this.deltas_.length=0,this.cursor_=0,this.count_=0,this.sum_=0}}class Qa{constructor(e){this.name="Stats",this.collector_=new Ja,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(qa,Va());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new Ya(e,this.options_.position)}const t=this.collector_,s=this.overlay_,n=xt([Ie(ze),{_type:"get_world"}],(n,i)=>{t.pushFrame(n.delta);const o=e.getResource(qa);o.fps=t.getFps(),o.frameTimeMs=t.getFrameTimeMs(),o.entityCount=i.entityCount();const r=e.getSystemTimings();if(r){const e=new Map(r);e.delete(Ka),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=Wn.getStats();o.drawCalls=l.drawCalls,o.triangles=l.triangles,o.sprites=l.sprites,o.text=l.text,o.spine=l.spine,o.meshes=l.meshes,o.culled=l.culled,s?.update(o)},{name:Ka});e.addSystemToSchedule(gt.Last,n)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const Za=new Qa;class el{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,s)=>{const n=new Image;n.onload=()=>{const e=document.createElement("canvas");e.width=n.width,e.height=n.height;const s=e.getContext("2d");s.drawImage(n,0,0);const i=s.getImageData(0,0,n.width,n.height);t({width:n.width,height:n.height,pixels:new Uint8Array(i.data.buffer)})},n.onerror=s,n.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return function(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}(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}async function tl(e,t){try{const s=function(e){const t=atob(e),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s}(t);return await e({instantiateWasm:(e,t)=>(WebAssembly.instantiate(s.buffer,e).then(e=>{t(e.instance,e.module)}),{})})}catch(e){return null}}async function sl(e){const{app:t,module:s,assets:n,sceneData:i,sceneName:o}=e,r=t.getResource(Ns);r&&(r.registerEmbeddedAssets(n),r.setEmbeddedOnly(!0));const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await tl(ESSpineModule,e);return t||console.warn("Spine module not available"),t}(e.spineWasmBase64):null,l=e.physicsWasmBase64?await async function(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await tl(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new el(n);await Kr({app:t,module:s,provider:c,scenes:[{name:o,data:i}],firstScene:o,spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()}const nl=[qi,lo,go,Wo,Ko,Co,er,or,hr,jo,Bo,fr,gr,br,Pr,Ir,Fr],il=[...nl,za,Na];function ol(e,t){return function(e,t){const s=ti.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),cn(e),$t(e),Tn(e),In(e),On(e),Nn(e);const i=new Yn;s.setPipeline(i);let o=d();const r=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=ai(e,n,t,i));const r=s.getResource(At);if(o.length>0){const e=o[0],s=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(s.x*t),r.vpY=Math.round((1-s.y-s.h)*i),r.vpW=Math.round(s.w*t),r.vpH=Math.round(s.h*i),r.screenW=t,r.screenH=i,r.worldLeft=e.cameraX-e.halfW,r.worldRight=e.cameraX+e.halfW,r.worldBottom=e.cameraY-e.halfH,r.worldTop=e.cameraY+e.halfH,r.valid=!0}else r.valid=!1}s.insertResource(At,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=r();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(n);if(c>=0){const e=n.getCanvas(c).backgroundColor;Wn.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-o)/1e3;let h;if(Wn.resize(t,l),Bn.isInitialized()&&Bn.getPassCount()>0&&!Bn.isBypassed()&&Bn.resize(t,l),s.hasResource(Jn)){const e=s.getResource(Jn).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=ai(e,n,t,l,s.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:n},viewProjection:ni,width:t,height:l,elapsed:u});else{for(const e of f){const s=e.viewportRect,o=Math.round(s.x*t),r=Math.round((1-s.y-s.h)*l),a=Math.round(s.w*t),c=Math.round(s.h*l);i.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:u})}Wn.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(gt.First,l),s.addSystemToSchedule(gt.Last,c),s.addPlugin(js),s.addPlugin(sn),s.addPlugin(Rt),s.addPlugin(ei),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:il,...t})}e=w;export{Je as Added,Ba as AnimationPlugin,ti as App,Xs as AssetPlugin,Ys as AssetRefCounter,Hs as AssetServer,Ns as Assets,Gt as AsyncCache,Ua as AttenuationModel,rs as Audio,p as AudioBus,Wa as AudioListener,m as AudioMixer,Ha as AudioPlugin,_ as AudioPool,La as AudioSource,we as BitmapText,It as BlendMode,Ce as BodyType,Pe as BoxCollider,fo as Button,ho as ButtonState,pe as Camera,me as Canvas,Ee as CapsuleCollider,Qe as Changed,ye as Children,Te as CircleCollider,le as ClearFlags,at as Commands,ct as CommandsInstance,v as DEFAULT_DESIGN_HEIGHT,x as DEFAULT_DESIGN_WIDTH,R as DEFAULT_FALLBACK_DT,I as DEFAULT_FIXED_TIMESTEP,P as DEFAULT_FONT_FAMILY,T as DEFAULT_FONT_SIZE,A as DEFAULT_GRAVITY,E as DEFAULT_LINE_HEIGHT,C as DEFAULT_MAX_DELTA_TIME,b as DEFAULT_PIXELS_PER_UNIT,k as DEFAULT_SPINE_SKIN,M as DEFAULT_SPRITE_SIZE,S as DEFAULT_TEXT_CANVAS_SIZE,vn as DataType,Zo as DragPlugin,Qo as DragState,Jo as Draggable,fn as Draw,Sr as Dropdown,Mr as DropdownPlugin,ha as EasingType,lt as EntityCommands,pt as EventReader,_t as EventReaderInstance,dt as EventRegistry,ft as EventWriter,mt as EventWriterInstance,_i as FillDirection,Uo as FillMethod,$o as FillOrigin,ko as FocusManager,Io as FocusManagerState,dr as FocusPlugin,Ao as Focusable,Ga as FrameHistory,jn as GLDebug,Rn as Geometry,yt as GetWorld,$ as INVALID_ENTITY,O as INVALID_FONT,L as INVALID_MATERIAL,D as INVALID_TEXTURE,Do as Image,Lo as ImagePlugin,zo as ImageType,Et as Input,Ct as InputPlugin,Tt as InputState,co as Interactable,Ar as LayoutGroupPlugin,yr as ListView,vr as ListViewPlugin,he as LocalTransform,ta as LogLevel,na as Logger,fa as LoopMode,Lt as Material,Kt as MaterialLoader,Ge as Mut,ve as Name,ge as Parent,Hr as Physics,Ur as PhysicsEvents,Lr as PhysicsPlugin,Bn as PostProcess,Zs as PrefabServer,en as Prefabs,tn as PrefabsPlugin,Zr as PreviewPlugin,Vo as ProgressBar,Yo as ProgressBarDirection,Go as ProgressBarPlugin,ae as ProjectionType,nt as Query,it as QueryInstance,ot as Removed,rt as RemovedQueryInstance,Yn as RenderPipeline,Un as RenderStage,ea as RenderTexture,Wn as Renderer,Ie as Res,ke as ResMut,Me as RigidBody,F as RuntimeConfig,pr as SafeArea,_r as SafeAreaPlugin,ce as ScaleMode,Jn as SceneManager,Kn as SceneManagerState,be as SceneOwner,gt as Schedule,tr as ScrollView,ir as ScrollViewPlugin,qt as ShaderSources,ar as Slider,rr as SliderDirection,ur as SliderPlugin,xe as SpineAnimation,fe as Sprite,is as SpriteAnimator,qa as Stats,Ja as StatsCollector,Ya as StatsOverlay,Qa as StatsPlugin,Pt as SystemRunner,Xi as Text,Wi as TextAlign,Ro as TextInput,Fo as TextInputPlugin,Ni as TextOverflow,Vi as TextPlugin,ji as TextRenderer,Hi as TextVerticalAlign,ze as Time,Ho as Toggle,Xo as TogglePlugin,ue as Transform,Fa as Tween,Ta as TweenHandle,da as TweenState,Pa as TweenTarget,At as UICameraInfo,po as UIEventQueue,mo as UIEvents,uo as UIInteraction,Eo as UIInteractionPlugin,_o as UILayoutPlugin,Ji as UIMask,ao as UIMaskPlugin,yi as UIRect,kr as UIRenderOrderPlugin,_e as Velocity,Jr as WebAssetProvider,qe as World,de as WorldTransform,St as addStartupSystem,bt as addSystem,Mt as addSystemToSchedule,za as animationPlugin,U as applyBuildRuntimeConfig,Pi as applyDirectionalFill,B as applyRuntimeConfig,js as assetPlugin,Na as audioPlugin,Da as calculateAttenuation,Oa as calculatePanning,ns as clearAnimClips,xn as clearDrawCallbacks,Z as clearUserComponents,X as color,bi as computeFillAnchors,Mi as computeFillSize,Si as computeHandleAnchors,gi as computeUIRectLayout,ro as createMaskProcessor,Gr as createRuntimeSceneConfig,ol as createWebApp,aa as debug,Va as defaultFrameStats,K as defineComponent,ut as defineEvent,Ae as defineResource,xt as defineSystem,J as defineTag,er as dragPlugin,Pr as dropdownPlugin,ua as error,Jt as extractAnimClipTexturePaths,bs as findEntityByName,si as flushPendingSystems,fr as focusPlugin,As as getAddressableType,Is as getAddressableTypeByEditorType,Fs as getAllAssetExtensions,ss as getAnimClip,Ws as getAssetBuildTransform,$s as getAssetMimeType,Cs as getAssetTypeEntry,oe as getComponent,us as getComponentAssetFieldDescriptors,cs as getComponentAssetFields,Se as getComponentDefaults,ps as getComponentEntityFields,hs as getComponentSpineFieldDescriptor,zs as getCustomExtensions,Rs as getEditorType,oa as getLogger,t as getPlatform,n as getPlatformType,Q as getUserComponent,Us as getWeChatPackOptions,Wo as imagePlugin,la as info,cn as initDrawAPI,Nn as initGLDebugAPI,Tn as initGeometryAPI,$t as initMaterialAPI,sl as initPlayableRuntime,In as initPostProcessAPI,On as initRendererAPI,Kr as initRuntime,Ra as initTweenAPI,Rt as inputPlugin,qs as instantiatePrefab,Qi as intersectRects,Zi as invertMatrix4,se as isBuiltinComponent,Ds as isCustomExtension,vo as isEditor,ks as isKnownAssetExtension,s as isPlatformInitialized,Mo as isPlayMode,bo as isRuntime,kt as isTextureRef,i as isWeChat,o as isWeb,Ir as layoutGroupPlugin,br as listViewPlugin,xs as loadComponent,zr as loadPhysicsModule,qr as loadRuntimeScene,gs as loadSceneData,ys as loadSceneWithAssets,Bs as looksLikeAssetPath,Qt as parseAnimClipData,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,io as pointInOBB,to as pointInWorldRect,sn as prefabsPlugin,Ko as progressBarPlugin,j as quat,es as registerAnimClip,Ls as registerAssetBuildTransform,ie as registerComponent,ls as registerComponentAssetFields,fs as registerComponentEntityFields,yn as registerDrawCallback,Vs as registerEmbeddedAssets,Vt as registerMaterialCallback,ms as remapEntityFields,gr as safeAreaPlugin,ei as sceneManagerPlugin,eo as screenToWorld,or as scrollViewPlugin,xo as setEditorMode,xr as setListViewRenderer,ra as setLogLevel,So as setPlayMode,Le as setWasmErrorHandler,un as shutdownDrawAPI,Xn as shutdownGLDebugAPI,En as shutdownGeometryAPI,Dt as shutdownMaterialAPI,kn as shutdownPostProcessAPI,Ln as shutdownRendererAPI,Aa as shutdownTweenAPI,hr as sliderPlugin,os as spriteAnimatorSystemUpdate,Za as statsPlugin,Fi as syncFillSpriteSize,Bo as textInputPlugin,qi as textPlugin,Os as toBuildPath,jo as togglePlugin,Br as transitionTo,Co as uiInteractionPlugin,go as uiLayoutPlugin,lo as uiMaskPlugin,nl as uiPlugins,Fr as uiRenderOrderPlugin,ts as unregisterAnimClip,ee as unregisterComponent,wn as unregisterDrawCallback,vs as updateCameraAspectRatio,W as vec2,H as vec3,N as vec4,ca as warn,Qn as wrapSceneSystem};//# sourceMappingURL=index.js.mapdiff --git a/desktop/public/wasm/esengine.wxgame.js b/desktop/public/wasm/esengine.wxgame.jsindex d2b7a9b4f..4c852513c 100644--- a/desktop/public/wasm/esengine.wxgame.js+++ b/desktop/public/wasm/esengine.wxgame.js@@ -8,5 +8,5 @@// environments and skip DOM-dependent features (e.g. TextInputPlugin).if (typeof window === 'undefined') { globalThis.window = globalThis; }if (typeof document === 'undefined') { globalThis.document = {}; }-var ESEngineModule=(()=>{var _scriptName=globalThis.document?.currentScript?.src;return async function(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_WEB=true;var ENVIRONMENT_IS_WORKER=false;var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{readAsync=async url=>{var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var EXITSTATUS;var readyPromiseResolve,readyPromiseReject;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var HEAP64,HEAPU64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.initialized)FS.init();TTY.init();wasmExports["fb"]();FS.ignorePermissions=false}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject?.(e);throw e}var wasmBinaryFile;function findWasmBinary(){return locateFile("esengine.wxgame.wasm")}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);var noExitRuntime=true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();var syscallGetVarargI=()=>{var ret=HEAP32[+SYSCALLS.varargs>>2];SYSCALLS.varargs+=4;return ret};var syscallGetVarargP=syscallGetVarargI;var PATH={isAbs:path=>path.charAt(0)==="/",splitPath:filename=>{var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:(parts,allowAboveRoot)=>{var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:path=>{var isAbsolute=PATH.isAbs(path),trailingSlash=path.slice(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(p=>!!p),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:path=>{var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.slice(0,-1)}return root+dir},basename:path=>path&&path.match(/([^\/]+|\/)\/*$/)[1],join:(...paths)=>PATH.normalize(paths.join("/")),join2:(l,r)=>PATH.normalize(l+"/"+r)};var initRandomFill=()=>view=>crypto.getRandomValues(view);var randomFill=view=>{(randomFill=initRandomFill())(view)};var PATH_FS={resolve:(...args)=>{var resolvedPath="",resolvedAbsolute=false;for(var i=args.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?args[i]:FS.cwd();if(typeof path!="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=PATH.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).slice(1);to=PATH_FS.resolve(to).slice(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")}};var UTF8Decoder=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var FS_stdin_getChar_buffer=[];var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.codePointAt(i);if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63;i++}}heap[outIdx]=0;return outIdx-startIdx};var intArrayFromString=(stringy,dontAddNull,length)=>{var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array};var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var result=null;if(globalThis.window?.prompt){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else{}if(!result){return null}FS_stdin_getChar_buffer=intArrayFromString(result,true)}return FS_stdin_getChar_buffer.shift()};var TTY={ttys:[],init(){},shutdown(){},register(dev,ops){TTY.ttys[dev]={input:[],output:[],ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close(stream){stream.tty.ops.fsync(stream.tty)},fsync(stream){stream.tty.ops.fsync(stream.tty)},read(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=stream.tty.ops.get_char(stream.tty)}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.put_char){throw new FS.ErrnoError(60)}try{for(var i=0;i<length;i++){stream.tty.ops.put_char(stream.tty,buffer[offset+i])}}catch(e){throw new FS.ErrnoError(29)}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}},default_tty_ops:{get_char(tty){return FS_stdin_getChar()},put_char(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){out(UTF8ArrayToString(tty.output));tty.output=[]}},ioctl_tcgets(tty){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(tty,optional_actions,data){return 0},ioctl_tiocgwinsz(tty){return[24,80]}},default_tty1_ops:{put_char(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){err(UTF8ArrayToString(tty.output));tty.output=[]}}}};var mmapAlloc=size=>{abort()};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",16895,0)},createNode(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}MEMFS.ops_table||={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}};var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=null}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.atime=node.mtime=node.ctime=Date.now();if(parent){parent.contents[name]=node;parent.atime=parent.mtime=parent.ctime=node.atime}return node},getFileDataAsTypedArray(node){if(!node.contents)return new Uint8Array(0);if(node.contents.subarray)return node.contents.subarray(0,node.usedBytes);return new Uint8Array(node.contents)},expandFileStorage(node,newCapacity){var prevCapacity=node.contents?node.contents.length:0;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity<CAPACITY_DOUBLING_MAX?2:1.125)>>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.atime);attr.mtime=new Date(node.mtime);attr.ctime=new Date(node.ctime);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr(node,attr){for(const key of["mode","atime","mtime","ctime"]){if(attr[key]!=null){node[key]=attr[key]}}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup(parent,name){if(!MEMFS.doesNotExistError){MEMFS.doesNotExistError=new FS.ErrnoError(44);MEMFS.doesNotExistError.stack="<generic error, no stack>"}throw MEMFS.doesNotExistError},mknod(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename(old_node,new_dir,new_name){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){if(FS.isDir(old_node.mode)){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}FS.hashRemoveNode(new_node)}delete old_node.parent.contents[old_node.name];new_dir.contents[new_name]=old_node;old_node.name=new_name;new_dir.ctime=new_dir.mtime=old_node.parent.ctime=old_node.parent.mtime=Date.now()},unlink(parent,name){delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},rmdir(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},readdir(node){return[".","..",...Object.keys(node.contents)]},symlink(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i<size;i++)buffer[offset+i]=contents[position+i]}return size},write(stream,buffer,offset,length,position,canOwn){if(buffer.buffer===HEAP8.buffer){canOwn=false}if(!length)return 0;var node=stream.node;node.mtime=node.ctime=Date.now();if(buffer.subarray&&(!node.contents||node.contents.subarray)){if(canOwn){node.contents=buffer.subarray(offset,offset+length);node.usedBytes=length;return length}else if(node.usedBytes===0&&position===0){node.contents=buffer.slice(offset,offset+length);node.usedBytes=length;return length}else if(position+length<=node.usedBytes){node.contents.set(buffer.subarray(offset,offset+length),position);return length}}MEMFS.expandFileStorage(node,position+length);if(node.contents.subarray&&buffer.subarray){node.contents.set(buffer.subarray(offset,offset+length),position)}else{for(var i=0;i<length;i++){node.contents[position+i]=buffer[offset+i]}}node.usedBytes=Math.max(node.usedBytes,position+length);return length},llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(FS.isFile(stream.node.mode)){position+=stream.node.usedBytes}}if(position<0){throw new FS.ErrnoError(28)}return position},mmap(stream,length,position,prot,flags){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}var ptr;var allocated;var contents=stream.node.contents;if(!(flags&2)&&contents&&contents.buffer===HEAP8.buffer){allocated=false;ptr=contents.byteOffset}else{allocated=true;ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}if(contents){if(position>0||position+length<contents.length){if(contents.subarray){contents=contents.subarray(position,position+length)}else{contents=Array.prototype.slice.call(contents,position,position+length)}}HEAP8.set(contents,ptr)}}return{ptr,allocated}},msync(stream,buffer,offset,length,mmapFlags){MEMFS.stream_ops.write(stream,buffer,0,length,offset,false);return 0}}};var FS_modeStringToFlags=str=>{var flagModes={r:0,"r+":2,w:512|64|1,"w+":512|64|2,a:1024|64|1,"a+":1024|64|2};var flags=flagModes[str];if(typeof flags=="undefined"){throw new Error(`Unknown file open mode: ${str}`)}return flags};var FS_getMode=(canRead,canWrite)=>{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode};var asyncLoad=async url=>{var arrayBuffer=await readAsync(url);return new Uint8Array(arrayBuffer)};var FS_createDataFile=(...args)=>FS.createDataFile(...args);var getUniqueRunDependency=id=>id;var runDependencies=0;var dependenciesFulfilled=null;var removeRunDependency=id=>{runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}};var addRunDependency=id=>{runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)};var preloadPlugins=[];var FS_handledByPreloadPlugin=async(byteArray,fullname)=>{if(typeof Browser!="undefined")Browser.init();for(var plugin of preloadPlugins){if(plugin["canHandle"](fullname)){return plugin["handle"](byteArray,fullname)}}return byteArray};var FS_preloadFile=async(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency(`cp ${fullname}`);addRunDependency(dep);try{var byteArray=url;if(typeof url=="string"){byteArray=await asyncLoad(url)}byteArray=await FS_handledByPreloadPlugin(byteArray,fullname);preFinish?.();if(!dontCreateFile){FS_createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}}finally{removeRunDependency(dep)}};var FS_createPreloadedFile=(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{FS_preloadFile(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish).then(onload).catch(onerror)};var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,filesystems:null,syncFSRequests:0,readFiles:{},ErrnoError:class{name="ErrnoError";constructor(errno){this.errno=errno}},FSStream:class{shared={};get object(){return this.node}set object(val){this.node=val}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(val){this.shared.flags=val}get position(){return this.shared.position}set position(val){this.shared.position=val}},FSNode:class{node_ops={};stream_ops={};readMode=292|73;writeMode=146;mounted=null;constructor(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.rdev=rdev;this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(val){val?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(val){val?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return FS.isDir(this.mode)}get isDevice(){return FS.isChrdev(this.mode)}},lookupPath(path,opts={}){if(!path){throw new FS.ErrnoError(44)}opts.follow_mount??=true;if(!PATH.isAbs(path)){path=FS.cwd()+"/"+path}linkloop:for(var nlinks=0;nlinks<40;nlinks++){var parts=path.split("/").filter(p=>!!p);var current=FS.root;var current_path="/";for(var i=0;i<parts.length;i++){var islast=i===parts.length-1;if(islast&&opts.parent){break}if(parts[i]==="."){continue}if(parts[i]===".."){current_path=PATH.dirname(current_path);if(FS.isRoot(current)){path=current_path+"/"+parts.slice(i+1).join("/");nlinks--;continue linkloop}else{current=current.parent}continue}current_path=PATH.join2(current_path,parts[i]);try{current=FS.lookupNode(current,parts[i])}catch(e){if(e?.errno===44&&islast&&opts.noent_okay){return{path:current_path}}throw e}if(FS.isMountpoint(current)&&(!islast||opts.follow_mount)){current=current.mounted.root}if(FS.isLink(current.mode)&&(!islast||opts.follow)){if(!current.node_ops.readlink){throw new FS.ErrnoError(52)}var link=current.node_ops.readlink(current);if(!PATH.isAbs(link)){link=PATH.dirname(current_path)+"/"+link}path=link+"/"+parts.slice(i+1).join("/");continue linkloop}}return{path:current_path,node:current}}throw new FS.ErrnoError(32)},getPath(node){var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?`${mount}/${path}`:mount+path}path=path?`${node.name}/${path}`:node.name;node=node.parent}},hashName(parentid,name){var hash=0;for(var i=0;i<name.length;i++){hash=(hash<<5)-hash+name.charCodeAt(i)|0}return(parentid+hash>>>0)%FS.nameTable.length},hashAddNode(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode(node){FS.hashRemoveNode(node)},isRoot(node){return node===node.parent},isMountpoint(node){return!!node.mounted},isFile(mode){return(mode&61440)===32768},isDir(mode){return(mode&61440)===16384},isLink(mode){return(mode&61440)===40960},isChrdev(mode){return(mode&61440)===8192},isBlkdev(mode){return(mode&61440)===24576},isFIFO(mode){return(mode&61440)===4096},isSocket(mode){return(mode&49152)===49152},flagsToPermissionString(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}else if(perms.includes("w")&&!(node.mode&146)){return 2}else if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup(dir){if(!FS.isDir(dir.mode))return 54;var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate(dir,name){if(!FS.isDir(dir.mode)){return 54}try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else{if(FS.isDir(node.mode)){return 31}}return 0},mayOpen(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}else if(FS.isDir(node.mode)){if(FS.flagsToPermissionString(flags)!=="r"||flags&(512|64)){return 31}}return FS.nodePermissions(node,FS.flagsToPermissionString(flags))},checkOpExists(op,err){if(!op){throw new FS.ErrnoError(err)}return op},MAX_OPEN_FDS:4096,nextfd(){for(var fd=0;fd<=FS.MAX_OPEN_FDS;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStreamChecked(fd){var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}return stream},getStream:fd=>FS.streams[fd],createStream(stream,fd=-1){stream=Object.assign(new FS.FSStream,stream);if(fd==-1){fd=FS.nextfd()}stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream(fd){FS.streams[fd]=null},dupStream(origStream,fd=-1){var stream=FS.createStream(origStream,fd);stream.stream_ops?.dup?.(stream);return stream},doSetAttr(stream,node,attr){var setattr=stream?.stream_ops.setattr;var arg=setattr?stream:node;setattr??=node.node_ops.setattr;FS.checkOpExists(setattr,63);setattr(arg,attr)},chrdev_stream_ops:{open(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;stream.stream_ops.open?.(stream)},llseek(){throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push(...m.mounts)}return mounts},syncfs(populate,callback){if(typeof populate=="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`)}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}for(var mount of mounts){if(mount.type.syncfs){mount.type.syncfs(mount,populate,done)}else{done(null)}}},mount(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type,opts,mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);for(var[hash,current]of Object.entries(FS.nameTable)){while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}}node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup(parent,name){return parent.node_ops.lookup(parent,name)},mknod(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name){throw new FS.ErrnoError(28)}if(name==="."||name===".."){throw new FS.ErrnoError(20)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},statfs(path){return FS.statfsNode(FS.lookupPath(path,{follow:true}).node)},statfsStream(stream){return FS.statfsNode(stream.node)},statfsNode(node){var rtn={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:FS.nextInode,ffree:FS.nextInode-1,fsid:42,flags:2,namelen:255};if(node.node_ops.statfs){Object.assign(rtn,node.node_ops.statfs(node.mount.opts.root))}return rtn},create(path,mode=438){mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir(path,mode=511){mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree(path,mode){var dirs=path.split("/");var d="";for(var dir of dirs){if(!dir)continue;if(d||PATH.isAbs(path))d+="/";d+=dir;try{FS.mkdir(d,mode)}catch(e){if(e.errno!=20)throw e}}},mkdev(path,mode,dev){if(typeof dev=="undefined"){dev=mode;mode=438}mode|=8192;return FS.mknod(path,mode,dev)},symlink(oldpath,newpath){if(!PATH_FS.resolve(oldpath)){throw new FS.ErrnoError(44)}var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.symlink){throw new FS.ErrnoError(63)}return parent.node_ops.symlink(parent,newname,oldpath)},rename(old_path,new_path){var old_dirname=PATH.dirname(old_path);var new_dirname=PATH.dirname(new_path);var old_name=PATH.basename(old_path);var new_name=PATH.basename(new_path);var lookup,old_dir,new_dir;lookup=FS.lookupPath(old_path,{parent:true});old_dir=lookup.node;lookup=FS.lookupPath(new_path,{parent:true});new_dir=lookup.node;if(!old_dir||!new_dir)throw new FS.ErrnoError(44);if(old_dir.mount!==new_dir.mount){throw new FS.ErrnoError(75)}var old_node=FS.lookupNode(old_dir,old_name);var relative=PATH_FS.relative(old_path,new_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(28)}relative=PATH_FS.relative(new_path,old_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(55)}var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(old_node===new_node){return}var isdir=FS.isDir(old_node.mode);var errCode=FS.mayDelete(old_dir,old_name,isdir);if(errCode){throw new FS.ErrnoError(errCode)}errCode=new_node?FS.mayDelete(new_dir,new_name,isdir):FS.mayCreate(new_dir,new_name);if(errCode){throw new FS.ErrnoError(errCode)}if(!old_dir.node_ops.rename){throw new FS.ErrnoError(63)}if(FS.isMountpoint(old_node)||new_node&&FS.isMountpoint(new_node)){throw new FS.ErrnoError(10)}if(new_dir!==old_dir){errCode=FS.nodePermissions(old_dir,"w");if(errCode){throw new FS.ErrnoError(errCode)}}FS.hashRemoveNode(old_node);try{old_dir.node_ops.rename(old_node,new_dir,new_name);old_node.parent=new_dir}catch(e){throw e}finally{FS.hashAddNode(old_node)}},rmdir(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,true);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.rmdir){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.rmdir(parent,name);FS.destroyNode(node)},readdir(path){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var readdir=FS.checkOpExists(node.node_ops.readdir,54);return readdir(node)},unlink(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,false);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.unlink){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.unlink(parent,name);FS.destroyNode(node)},readlink(path){var lookup=FS.lookupPath(path);var link=lookup.node;if(!link){throw new FS.ErrnoError(44)}if(!link.node_ops.readlink){throw new FS.ErrnoError(28)}return link.node_ops.readlink(link)},stat(path,dontFollow){var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;var getattr=FS.checkOpExists(node.node_ops.getattr,63);return getattr(node)},fstat(fd){var stream=FS.getStreamChecked(fd);var node=stream.node;var getattr=stream.stream_ops.getattr;var arg=getattr?stream:node;getattr??=node.node_ops.getattr;FS.checkOpExists(getattr,63);return getattr(arg)},lstat(path){return FS.stat(path,true)},doChmod(stream,node,mode,dontFollow){FS.doSetAttr(stream,node,{mode:mode&4095|node.mode&~4095,ctime:Date.now(),dontFollow})},chmod(path,mode,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChmod(null,node,mode,dontFollow)},lchmod(path,mode){FS.chmod(path,mode,true)},fchmod(fd,mode){var stream=FS.getStreamChecked(fd);FS.doChmod(stream,stream.node,mode,false)},doChown(stream,node,dontFollow){FS.doSetAttr(stream,node,{timestamp:Date.now(),dontFollow})},chown(path,uid,gid,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChown(null,node,dontFollow)},lchown(path,uid,gid){FS.chown(path,uid,gid,true)},fchown(fd,uid,gid){var stream=FS.getStreamChecked(fd);FS.doChown(stream,stream.node,false)},doTruncate(stream,node,len){if(FS.isDir(node.mode)){throw new FS.ErrnoError(31)}if(!FS.isFile(node.mode)){throw new FS.ErrnoError(28)}var errCode=FS.nodePermissions(node,"w");if(errCode){throw new FS.ErrnoError(errCode)}FS.doSetAttr(stream,node,{size:len,timestamp:Date.now()})},truncate(path,len){if(len<0){throw new FS.ErrnoError(28)}var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:true});node=lookup.node}else{node=path}FS.doTruncate(null,node,len)},ftruncate(fd,len){var stream=FS.getStreamChecked(fd);if(len<0||(stream.flags&2097155)===0){throw new FS.ErrnoError(28)}FS.doTruncate(stream,stream.node,len)},utime(path,atime,mtime){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var setattr=FS.checkOpExists(node.node_ops.setattr,63);setattr(node,{atime,mtime})},open(path,flags,mode=438){if(path===""){throw new FS.ErrnoError(44)}flags=typeof flags=="string"?FS_modeStringToFlags(flags):flags;if(flags&64){mode=mode&4095|32768}else{mode=0}var node;var isDirPath;if(typeof path=="object"){node=path}else{isDirPath=path.endsWith("/");var lookup=FS.lookupPath(path,{follow:!(flags&131072),noent_okay:true});node=lookup.node;path=lookup.path}var created=false;if(flags&64){if(node){if(flags&128){throw new FS.ErrnoError(20)}}else if(isDirPath){throw new FS.ErrnoError(31)}else{node=FS.mknod(path,mode|511,0);created=true}}if(!node){throw new FS.ErrnoError(44)}if(FS.isChrdev(node.mode)){flags&=~512}if(flags&65536&&!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}if(!created){var errCode=FS.mayOpen(node,flags);if(errCode){throw new FS.ErrnoError(errCode)}}if(flags&512&&!created){FS.truncate(node,0)}flags&=~(128|512|131072);var stream=FS.createStream({node,path:FS.getPath(node),flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(created){FS.chmod(node,mode&511)}if(Module["logReadFiles"]&&!(flags&1)){if(!(path in FS.readFiles)){FS.readFiles[path]=1}}return stream},close(stream){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(stream.getdents)stream.getdents=null;try{if(stream.stream_ops.close){stream.stream_ops.close(stream)}}catch(e){throw e}finally{FS.closeStream(stream.fd)}stream.fd=null},isClosed(stream){return stream.fd===null},llseek(stream,offset,whence){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(!stream.seekable||!stream.stream_ops.llseek){throw new FS.ErrnoError(70)}if(whence!=0&&whence!=1&&whence!=2){throw new FS.ErrnoError(28)}stream.position=stream.stream_ops.llseek(stream,offset,whence);stream.ungotten=[];return stream.position},read(stream,buffer,offset,length,position){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.read){throw new FS.ErrnoError(28)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesRead=stream.stream_ops.read(stream,buffer,offset,length,position);if(!seeking)stream.position+=bytesRead;return bytesRead},write(stream,buffer,offset,length,position,canOwn){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.write){throw new FS.ErrnoError(28)}if(stream.seekable&&stream.flags&1024){FS.llseek(stream,0,2)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesWritten=stream.stream_ops.write(stream,buffer,offset,length,position,canOwn);if(!seeking)stream.position+=bytesWritten;return bytesWritten},mmap(stream,length,position,prot,flags){if((prot&2)!==0&&(flags&2)===0&&(stream.flags&2097155)!==2){throw new FS.ErrnoError(2)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(2)}if(!stream.stream_ops.mmap){throw new FS.ErrnoError(43)}if(!length){throw new FS.ErrnoError(28)}return stream.stream_ops.mmap(stream,length,position,prot,flags)},msync(stream,buffer,offset,length,mmapFlags){if(!stream.stream_ops.msync){return 0}return stream.stream_ops.msync(stream,buffer,offset,length,mmapFlags)},ioctl(stream,cmd,arg){if(!stream.stream_ops.ioctl){throw new FS.ErrnoError(59)}return stream.stream_ops.ioctl(stream,cmd,arg)},readFile(path,opts={}){opts.flags=opts.flags||0;opts.encoding=opts.encoding||"binary";if(opts.encoding!=="utf8"&&opts.encoding!=="binary"){abort(`Invalid encoding type "${opts.encoding}"`)}var stream=FS.open(path,opts.flags);var stat=FS.stat(path);var length=stat.size;var buf=new Uint8Array(length);FS.read(stream,buf,0,length,0);if(opts.encoding==="utf8"){buf=UTF8ArrayToString(buf)}FS.close(stream);return buf},writeFile(path,data,opts={}){opts.flags=opts.flags||577;var stream=FS.open(path,opts.flags,opts.mode);if(typeof data=="string"){data=new Uint8Array(intArrayFromString(data,true))}if(ArrayBuffer.isView(data)){FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn)}else{abort("Unsupported data type")}FS.close(stream)},cwd:()=>FS.currentPath,chdir(path){var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null){throw new FS.ErrnoError(44)}if(!FS.isDir(lookup.node.mode)){throw new FS.ErrnoError(54)}var errCode=FS.nodePermissions(lookup.node,"x");if(errCode){throw new FS.ErrnoError(errCode)}FS.currentPath=lookup.path},createDefaultDirectories(){FS.mkdir("/tmp");FS.mkdir("/home");FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length,pos)=>length,llseek:()=>0});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var randomBuffer=new Uint8Array(1024),randomLeft=0;var randomByte=()=>{if(randomLeft===0){randomFill(randomBuffer);randomLeft=randomBuffer.byteLength}return randomBuffer[--randomLeft]};FS.createDevice("/dev","random",randomByte);FS.createDevice("/dev","urandom",randomByte);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount(){var node=FS.createNode(proc_self,"fd",16895,73);node.stream_ops={llseek:MEMFS.stream_ops.llseek};node.node_ops={lookup(parent,name){var fd=+name;var stream=FS.getStreamChecked(fd);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path},id:fd+1};ret.parent=ret;return ret},readdir(){return Array.from(FS.streams.entries()).filter(([k,v])=>v).map(([k,v])=>k.toString())}};return node}},{},"/proc/self/fd")},createStandardStreams(input,output,error){if(input){FS.createDevice("/dev","stdin",input)}else{FS.symlink("/dev/tty","/dev/stdin")}if(output){FS.createDevice("/dev","stdout",null,output)}else{FS.symlink("/dev/tty","/dev/stdout")}if(error){FS.createDevice("/dev","stderr",null,error)}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},staticInit(){FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={MEMFS}},init(input,output,error){FS.initialized=true;input??=Module["stdin"];output??=Module["stdout"];error??=Module["stderr"];FS.createStandardStreams(input,output,error)},quit(){FS.initialized=false;for(var stream of FS.streams){if(stream){FS.close(stream)}}},findObject(path,dontResolveLastLink){var ret=FS.analyzePath(path,dontResolveLastLink);if(!ret.exists){return null}return ret.object},analyzePath(path,dontResolveLastLink){try{var lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});path=lookup.path}catch(e){}var ret={isRoot:false,exists:false,error:0,name:null,path:null,object:null,parentExists:false,parentPath:null,parentObject:null};try{var lookup=FS.lookupPath(path,{parent:true});ret.parentExists=true;ret.parentPath=lookup.path;ret.parentObject=lookup.node;ret.name=PATH.basename(path);lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});ret.exists=true;ret.path=lookup.path;ret.object=lookup.node;ret.name=lookup.node.name;ret.isRoot=lookup.path==="/"}catch(e){ret.error=e.errno}return ret},createPath(parent,path,canRead,canWrite){parent=typeof parent=="string"?parent:FS.getPath(parent);var parts=path.split("/").reverse();while(parts.length){var part=parts.pop();if(!part)continue;var current=PATH.join2(parent,part);try{FS.mkdir(current)}catch(e){if(e.errno!=20)throw e}parent=current}return current},createFile(parent,name,properties,canRead,canWrite){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(canRead,canWrite);return FS.create(path,mode)},createDataFile(parent,name,data,canRead,canWrite,canOwn){var path=name;if(parent){parent=typeof parent=="string"?parent:FS.getPath(parent);path=name?PATH.join2(parent,name):parent}var mode=FS_getMode(canRead,canWrite);var node=FS.create(path,mode);if(data){if(typeof data=="string"){var arr=new Array(data.length);for(var i=0,len=data.length;i<len;++i)arr[i]=data.charCodeAt(i);data=arr}FS.chmod(node,mode|146);var stream=FS.open(node,577);FS.write(stream,data,0,data.length,0,canOwn);FS.close(stream);FS.chmod(node,mode)}},createDevice(parent,name,input,output){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(!!input,!!output);FS.createDevice.major??=64;var dev=FS.makedev(FS.createDevice.major++,0);FS.registerDevice(dev,{open(stream){stream.seekable=false},close(stream){if(output?.buffer?.length){output(10)}},read(stream,buffer,offset,length,pos){var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=input()}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){for(var i=0;i<length;i++){try{output(buffer[offset+i])}catch(e){throw new FS.ErrnoError(29)}}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}});return FS.mkdev(path,mode,dev)},forceLoadFile(obj){if(obj.isDevice||obj.isFolder||obj.link||obj.contents)return true;if(globalThis.XMLHttpRequest){abort("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.")}else{try{obj.contents=readBinary(obj.url)}catch(e){throw new FS.ErrnoError(29)}}},createLazyFile(parent,name,url,canRead,canWrite){class LazyUint8Array{lengthKnown=false;chunks=[];get(idx){if(idx>this.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]}setDataGetter(getter){this.getter=getter}cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)abort("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)abort("only "+datalength+" bytes available! programmer error!");var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}return intArrayFromString(xhr.responseText||"",true)};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]=="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]=="undefined")abort("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true}get length(){if(!this.lengthKnown){this.cacheLength()}return this._length}get chunkSize(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}if(globalThis.XMLHttpRequest){if(!ENVIRONMENT_IS_WORKER)abort("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var lazyArray=new LazyUint8Array;var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};for(const[key,fn]of Object.entries(node.stream_ops)){stream_ops[key]=(...args)=>{FS.forceLoadFile(node);return fn(...args)}}function writeChunks(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i<size;i++){buffer[offset+i]=contents[position+i]}}else{for(var i=0;i<size;i++){buffer[offset+i]=contents.get(position+i)}}return size}stream_ops.read=(stream,buffer,offset,length,position)=>{FS.forceLoadFile(node);return writeChunks(stream,buffer,offset,length,position)};stream_ops.mmap=(stream,length,position,prot,flags)=>{FS.forceLoadFile(node);var ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}writeChunks(stream,HEAP8,ptr,length,position);return{ptr,allocated:true}};node.stream_ops=stream_ops;return node}};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";var SYSCALLS={calculateAt(dirfd,path,allowEmpty){if(PATH.isAbs(path)){return path}var dir;if(dirfd===-100){dir=FS.cwd()}else{var dirstream=SYSCALLS.getStreamFromFD(dirfd);dir=dirstream.path}if(path.length==0){if(!allowEmpty){throw new FS.ErrnoError(44)}return dir}return dir+"/"+path},writeStat(buf,stat){HEAPU32[buf>>2]=stat.dev;HEAPU32[buf+4>>2]=stat.mode;HEAPU32[buf+8>>2]=stat.nlink;HEAPU32[buf+12>>2]=stat.uid;HEAPU32[buf+16>>2]=stat.gid;HEAPU32[buf+20>>2]=stat.rdev;HEAP64[buf+24>>3]=BigInt(stat.size);HEAP32[buf+32>>2]=4096;HEAP32[buf+36>>2]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();HEAP64[buf+40>>3]=BigInt(Math.floor(atime/1e3));HEAPU32[buf+48>>2]=atime%1e3*1e3*1e3;HEAP64[buf+56>>3]=BigInt(Math.floor(mtime/1e3));HEAPU32[buf+64>>2]=mtime%1e3*1e3*1e3;HEAP64[buf+72>>3]=BigInt(Math.floor(ctime/1e3));HEAPU32[buf+80>>2]=ctime%1e3*1e3*1e3;HEAP64[buf+88>>3]=BigInt(stat.ino);return 0},writeStatFs(buf,stats){HEAPU32[buf+4>>2]=stats.bsize;HEAPU32[buf+60>>2]=stats.bsize;HEAP64[buf+8>>3]=BigInt(stats.blocks);HEAP64[buf+16>>3]=BigInt(stats.bfree);HEAP64[buf+24>>3]=BigInt(stats.bavail);HEAP64[buf+32>>3]=BigInt(stats.files);HEAP64[buf+40>>3]=BigInt(stats.ffree);HEAPU32[buf+48>>2]=stats.fsid;HEAPU32[buf+64>>2]=stats.flags;HEAPU32[buf+56>>2]=stats.namelen},doMsync(addr,stream,len,flags,offset){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}if(flags&2){return 0}var buffer=HEAPU8.slice(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},getStreamFromFD(fd){var stream=FS.getStreamChecked(fd);return stream},varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=syscallGetVarargI();if(arg<0){return-28}while(FS.streams[arg]){arg++}var newStream;newStream=FS.dupStream(stream,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=syscallGetVarargI();stream.flags|=arg;return 0}case 12:{var arg=syscallGetVarargP();var offset=0;HEAP16[arg+offset>>1]=2;return 0}case 13:case 14:return 0}return-28}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:{if(!stream.tty)return-59;return 0}case 21505:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcgets){var termios=stream.tty.ops.ioctl_tcgets(stream);var argp=syscallGetVarargP();HEAP32[argp>>2]=termios.c_iflag||0;HEAP32[argp+4>>2]=termios.c_oflag||0;HEAP32[argp+8>>2]=termios.c_cflag||0;HEAP32[argp+12>>2]=termios.c_lflag||0;for(var i=0;i<32;i++){HEAP8[argp+i+17]=termios.c_cc[i]||0}return 0}return 0}case 21510:case 21511:case 21512:{if(!stream.tty)return-59;return 0}case 21506:case 21507:case 21508:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcsets){var argp=syscallGetVarargP();var c_iflag=HEAP32[argp>>2];var c_oflag=HEAP32[argp+4>>2];var c_cflag=HEAP32[argp+8>>2];var c_lflag=HEAP32[argp+12>>2];var c_cc=[];for(var i=0;i<32;i++){c_cc.push(HEAP8[argp+i+17])}return stream.tty.ops.ioctl_tcsets(stream.tty,op,{c_iflag,c_oflag,c_cflag,c_lflag,c_cc})}return 0}case 21519:{if(!stream.tty)return-59;var argp=syscallGetVarargP();HEAP32[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21537:case 21531:{var argp=syscallGetVarargP();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tiocgwinsz){var winsize=stream.tty.ops.ioctl_tiocgwinsz(stream.tty);var argp=syscallGetVarargP();HEAP16[argp>>1]=winsize[0];HEAP16[argp+2>>1]=winsize[1]}return 0}case 21524:{if(!stream.tty)return-59;return 0}case 21515:{if(!stream.tty)return-59;return 0}default:return-28}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_openat(dirfd,path,flags,varargs){SYSCALLS.varargs=varargs;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);var mode=varargs?syscallGetVarargI():0;return FS.open(path,flags,mode).fd}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __abort_js=()=>abort("");var structRegistrations={};var runDestructors=destructors=>{while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}};function readPointer(pointer){return this.fromWireType(HEAPU32[pointer>>2])}var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var InternalError=class InternalError extends Error{constructor(message){super(message);this.name="InternalError"}};var throwInternalError=message=>{throw new InternalError(message)};var whenDependentTypesAreResolved=(myTypes,dependentTypes,getTypeConverters)=>{myTypes.forEach(type=>typeDependencies[type]=dependentTypes);function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i<myTypes.length;++i){registerType(myTypes[i],myTypeConverters[i])}}var typeConverters=new Array(dependentTypes.length);var unregisteredTypes=[];var registered=0;for(let[i,dt]of dependentTypes.entries()){if(registeredTypes.hasOwnProperty(dt)){typeConverters[i]=registeredTypes[dt]}else{unregisteredTypes.push(dt);if(!awaitingDependencies.hasOwnProperty(dt)){awaitingDependencies[dt]=[]}awaitingDependencies[dt].push(()=>{typeConverters[i]=registeredTypes[dt];++registered;if(registered===unregisteredTypes.length){onComplete(typeConverters)}})}}if(0===unregisteredTypes.length){onComplete(typeConverters)}};var __embind_finalize_value_object=structType=>{var reg=structRegistrations[structType];delete structRegistrations[structType];var rawConstructor=reg.rawConstructor;var rawDestructor=reg.rawDestructor;var fieldRecords=reg.fields;var fieldTypes=fieldRecords.map(field=>field.getterReturnType).concat(fieldRecords.map(field=>field.setterArgumentType));whenDependentTypesAreResolved([structType],fieldTypes,fieldTypes=>{var fields={};for(var[i,field]of fieldRecords.entries()){const getterReturnType=fieldTypes[i];const getter=field.getter;const getterContext=field.getterContext;const setterArgumentType=fieldTypes[i+fieldRecords.length];const setter=field.setter;const setterContext=field.setterContext;fields[field.fieldName]={read:ptr=>getterReturnType.fromWireType(getter(getterContext,ptr)),write:(ptr,o)=>{var destructors=[];setter(setterContext,ptr,setterArgumentType.toWireType(destructors,o));runDestructors(destructors)},optional:getterReturnType.optional}}return[{name:reg.name,fromWireType:ptr=>{var rv={};for(var i in fields){rv[i]=fields[i].read(ptr)}rawDestructor(ptr);return rv},toWireType:(destructors,o)=>{for(var fieldName in fields){if(!(fieldName in o)&&!fields[fieldName].optional){throw new TypeError(`Missing field: "${fieldName}"`)}}var ptr=rawConstructor();for(fieldName in fields){fields[fieldName].write(ptr,o[fieldName])}if(destructors!==null){destructors.push(rawDestructor,ptr)}return ptr},readValueFromPointer:readPointer,destructorFunction:rawDestructor}]})};var AsciiToString=ptr=>{var str="";while(1){var ch=HEAPU8[ptr++];if(!ch)return str;str+=String.fromCharCode(ch)}};var BindingError=class BindingError extends Error{constructor(message){super(message);this.name="BindingError"}};var throwBindingError=message=>{throw new BindingError(message)};function sharedRegisterType(rawType,registeredInstance,options={}){var name=registeredInstance.name;if(!rawType){throwBindingError(`type "${name}" must have a positive integer typeid pointer`)}if(registeredTypes.hasOwnProperty(rawType)){if(options.ignoreDuplicateRegistrations){return}else{throwBindingError(`Cannot register type '${name}' twice`)}}registeredTypes[rawType]=registeredInstance;delete typeDependencies[rawType];if(awaitingDependencies.hasOwnProperty(rawType)){var callbacks=awaitingDependencies[rawType];delete awaitingDependencies[rawType];callbacks.forEach(cb=>cb())}}function registerType(rawType,registeredInstance,options={}){return sharedRegisterType(rawType,registeredInstance,options)}var integerReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?pointer=>HEAP8[pointer]:pointer=>HEAPU8[pointer];case 2:return signed?pointer=>HEAP16[pointer>>1]:pointer=>HEAPU16[pointer>>1];case 4:return signed?pointer=>HEAP32[pointer>>2]:pointer=>HEAPU32[pointer>>2];case 8:return signed?pointer=>HEAP64[pointer>>3]:pointer=>HEAPU64[pointer>>3];default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};var __embind_register_bigint=(primitiveType,name,size,minRange,maxRange)=>{name=AsciiToString(name);const isUnsignedType=minRange===0n;let fromWireType=value=>value;if(isUnsignedType){const bitSize=size*8;fromWireType=value=>BigInt.asUintN(bitSize,value);maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>{if(typeof value=="number"){value=BigInt(value)}return value},readValueFromPointer:integerReadValueFromPointer(name,size,!isUnsignedType),destructorFunction:null})};var __embind_register_bool=(rawType,name,trueValue,falseValue)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:function(wt){return!!wt},toWireType:function(destructors,o){return o?trueValue:falseValue},readValueFromPointer:function(pointer){return this.fromWireType(HEAPU8[pointer])},destructorFunction:null})};var shallowCopyInternalPointer=o=>({count:o.count,deleteScheduled:o.deleteScheduled,preservePointerOnDelete:o.preservePointerOnDelete,ptr:o.ptr,ptrType:o.ptrType,smartPtr:o.smartPtr,smartPtrType:o.smartPtrType});var throwInstanceAlreadyDeleted=obj=>{function getInstanceTypeName(handle){return handle.$$.ptrType.registeredClass.name}throwBindingError(getInstanceTypeName(obj)+" instance already deleted")};var finalizationRegistry=false;var detachFinalizer=handle=>{};var runDestructor=$$=>{if($$.smartPtr){$$.smartPtrType.rawDestructor($$.smartPtr)}else{$$.ptrType.registeredClass.rawDestructor($$.ptr)}};var releaseClassHandle=$$=>{$$.count.value-=1;var toDelete=0===$$.count.value;if(toDelete){runDestructor($$)}};var attachFinalizer=handle=>{if(!globalThis.FinalizationRegistry){attachFinalizer=handle=>handle;return handle}finalizationRegistry=new FinalizationRegistry(info=>{releaseClassHandle(info.$$)});attachFinalizer=handle=>{var $$=handle.$$;var hasSmartPtr=!!$$.smartPtr;if(hasSmartPtr){var info={$$};finalizationRegistry.register(handle,info,handle)}return handle};detachFinalizer=handle=>finalizationRegistry.unregister(handle);return attachFinalizer(handle)};var deletionQueue=[];var flushPendingDeletes=()=>{while(deletionQueue.length){var obj=deletionQueue.pop();obj.$$.deleteScheduled=false;obj["delete"]()}};var delayFunction;var init_ClassHandle=()=>{let proto=ClassHandle.prototype;Object.assign(proto,{isAliasOf(other){if(!(this instanceof ClassHandle)){return false}if(!(other instanceof ClassHandle)){return false}var leftClass=this.$$.ptrType.registeredClass;var left=this.$$.ptr;other.$$=other.$$;var rightClass=other.$$.ptrType.registeredClass;var right=other.$$.ptr;while(leftClass.baseClass){left=leftClass.upcast(left);leftClass=leftClass.baseClass}while(rightClass.baseClass){right=rightClass.upcast(right);rightClass=rightClass.baseClass}return leftClass===rightClass&&left===right},clone(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.preservePointerOnDelete){this.$$.count.value+=1;return this}else{var clone=attachFinalizer(Object.create(Object.getPrototypeOf(this),{$$:{value:shallowCopyInternalPointer(this.$$)}}));clone.$$.count.value+=1;clone.$$.deleteScheduled=false;return clone}},delete(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}detachFinalizer(this);releaseClassHandle(this.$$);if(!this.$$.preservePointerOnDelete){this.$$.smartPtr=undefined;this.$$.ptr=undefined}},isDeleted(){return!this.$$.ptr},deleteLater(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}deletionQueue.push(this);if(deletionQueue.length===1&&delayFunction){delayFunction(flushPendingDeletes)}this.$$.deleteScheduled=true;return this}});const symbolDispose=Symbol.dispose;if(symbolDispose){proto[symbolDispose]=proto["delete"]}};function ClassHandle(){}var createNamedFunction=(name,func)=>Object.defineProperty(func,"name",{value:name});var registeredPointers={};var ensureOverloadTable=(proto,methodName,humanName)=>{if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(...args){if(!proto[methodName].overloadTable.hasOwnProperty(args.length)){throwBindingError(`Function '${humanName}' called with an invalid number of arguments (${args.length}) - expects one of (${proto[methodName].overloadTable})!`)}return proto[methodName].overloadTable[args.length].apply(this,args)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}};var exposePublicSymbol=(name,value,numArguments)=>{if(Module.hasOwnProperty(name)){if(undefined===numArguments||undefined!==Module[name].overloadTable&&undefined!==Module[name].overloadTable[numArguments]){throwBindingError(`Cannot register public name '${name}' twice`)}ensureOverloadTable(Module,name,name);if(Module[name].overloadTable.hasOwnProperty(numArguments)){throwBindingError(`Cannot register multiple overloads of a function with the same number of arguments (${numArguments})!`)}Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var char_0=48;var char_9=57;var makeLegalFunctionName=name=>{name=name.replace(/[^a-zA-Z0-9_]/g,"$");var f=name.charCodeAt(0);if(f>=char_0&&f<=char_9){return`_${name}`}return name};function RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast){this.name=name;this.constructor=constructor;this.instancePrototype=instancePrototype;this.rawDestructor=rawDestructor;this.baseClass=baseClass;this.getActualType=getActualType;this.upcast=upcast;this.downcast=downcast;this.pureVirtualFunctions=[]}var upcastPointer=(ptr,ptrClass,desiredClass)=>{while(ptrClass!==desiredClass){if(!ptrClass.upcast){throwBindingError(`Expected null or instance of ${desiredClass.name}, got an instance of ${ptrClass.name}`)}ptr=ptrClass.upcast(ptr);ptrClass=ptrClass.baseClass}return ptr};var embindRepr=v=>{if(v===null){return"null"}var t=typeof v;if(t==="object"||t==="array"||t==="function"){return v.toString()}else{return""+v}};function constNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}return 0}if(!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function genericPointerToWireType(destructors,handle){var ptr;if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}if(this.isSmartPointer){ptr=this.rawConstructor();if(destructors!==null){destructors.push(this.rawDestructor,ptr)}return ptr}else{return 0}}if(!handle||!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}if(!this.isConst&&handle.$$.ptrType.isConst){throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name} to parameter type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);if(this.isSmartPointer){if(undefined===handle.$$.smartPtr){throwBindingError("Passing raw pointer to smart pointer is illegal")}switch(this.sharingPolicy){case 0:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name} to parameter type ${this.name}`)}break;case 1:ptr=handle.$$.smartPtr;break;case 2:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{var clonedHandle=handle["clone"]();ptr=this.rawShare(ptr,Emval.toHandle(()=>clonedHandle["delete"]()));if(destructors!==null){destructors.push(this.rawDestructor,ptr)}}break;default:throwBindingError("Unsupported sharing policy")}}return ptr}function nonConstNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}return 0}if(!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}if(handle.$$.ptrType.isConst){throwBindingError(`Cannot convert argument of type ${handle.$$.ptrType.name} to parameter type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}var downcastPointer=(ptr,ptrClass,desiredClass)=>{if(ptrClass===desiredClass){return ptr}if(undefined===desiredClass.baseClass){return null}var rv=downcastPointer(ptr,ptrClass,desiredClass.baseClass);if(rv===null){return null}return desiredClass.downcast(rv)};var registeredInstances={};var getBasestPointer=(class_,ptr)=>{if(ptr===undefined){throwBindingError("ptr should not be undefined")}while(class_.baseClass){ptr=class_.upcast(ptr);class_=class_.baseClass}return ptr};var getInheritedInstance=(class_,ptr)=>{ptr=getBasestPointer(class_,ptr);return registeredInstances[ptr]};var makeClassHandle=(prototype,record)=>{if(!record.ptrType||!record.ptr){throwInternalError("makeClassHandle requires ptr and ptrType")}var hasSmartPtrType=!!record.smartPtrType;var hasSmartPtr=!!record.smartPtr;if(hasSmartPtrType!==hasSmartPtr){throwInternalError("Both smartPtrType and smartPtr must be specified")}record.count={value:1};return attachFinalizer(Object.create(prototype,{$$:{value:record,writable:true}}))};function RegisteredPointer_fromWireType(ptr){var rawPointer=this.getPointee(ptr);if(!rawPointer){this.destructor(ptr);return null}var registeredInstance=getInheritedInstance(this.registeredClass,rawPointer);if(undefined!==registeredInstance){if(0===registeredInstance.$$.count.value){registeredInstance.$$.ptr=rawPointer;registeredInstance.$$.smartPtr=ptr;return registeredInstance["clone"]()}else{var rv=registeredInstance["clone"]();this.destructor(ptr);return rv}}function makeDefaultHandle(){if(this.isSmartPointer){return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:rawPointer,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this,ptr})}}var actualType=this.registeredClass.getActualType(rawPointer);var registeredPointerRecord=registeredPointers[actualType];if(!registeredPointerRecord){return makeDefaultHandle.call(this)}var toType;if(this.isConst){toType=registeredPointerRecord.constPointerType}else{toType=registeredPointerRecord.pointerType}var dp=downcastPointer(rawPointer,this.registeredClass,toType.registeredClass);if(dp===null){return makeDefaultHandle.call(this)}if(this.isSmartPointer){return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp})}}var init_RegisteredPointer=()=>{Object.assign(RegisteredPointer.prototype,{getPointee(ptr){if(this.rawGetPointee){ptr=this.rawGetPointee(ptr)}return ptr},destructor(ptr){this.rawDestructor?.(ptr)},readValueFromPointer:readPointer,fromWireType:RegisteredPointer_fromWireType})};function RegisteredPointer(name,registeredClass,isReference,isConst,isSmartPointer,pointeeType,sharingPolicy,rawGetPointee,rawConstructor,rawShare,rawDestructor){this.name=name;this.registeredClass=registeredClass;this.isReference=isReference;this.isConst=isConst;this.isSmartPointer=isSmartPointer;this.pointeeType=pointeeType;this.sharingPolicy=sharingPolicy;this.rawGetPointee=rawGetPointee;this.rawConstructor=rawConstructor;this.rawShare=rawShare;this.rawDestructor=rawDestructor;if(!isSmartPointer&®isteredClass.baseClass===undefined){if(isConst){this.toWireType=constNoSmartPtrRawPointerToWireType;this.destructorFunction=null}else{this.toWireType=nonConstNoSmartPtrRawPointerToWireType;this.destructorFunction=null}}else{this.toWireType=genericPointerToWireType}}var replacePublicSymbol=(name,value,numArguments)=>{if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistent public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};var embind__requireFunction=(signature,rawFunction,isAsync=false)=>{signature=AsciiToString(signature);function makeDynCaller(){var rtn=getWasmTableEntry(rawFunction);return rtn}var fp=makeDynCaller();if(typeof fp!="function"){throwBindingError(`unknown function pointer with signature ${signature}: ${rawFunction}`)}return fp};class UnboundTypeError extends Error{}var getTypeName=type=>{var ptr=___getTypeName(type);var rv=AsciiToString(ptr);_free(ptr);return rv};var throwUnboundTypeError=(message,types)=>{var unboundTypes=[];var seen={};function visit(type){if(seen[type]){return}if(registeredTypes[type]){return}if(typeDependencies[type]){typeDependencies[type].forEach(visit);return}unboundTypes.push(type);seen[type]=true}types.forEach(visit);throw new UnboundTypeError(`${message}: `+unboundTypes.map(getTypeName).join([", "]))};var __embind_register_class=(rawType,rawPointerType,rawConstPointerType,baseClassRawType,getActualTypeSignature,getActualType,upcastSignature,upcast,downcastSignature,downcast,name,destructorSignature,rawDestructor)=>{name=AsciiToString(name);getActualType=embind__requireFunction(getActualTypeSignature,getActualType);upcast&&=embind__requireFunction(upcastSignature,upcast);downcast&&=embind__requireFunction(downcastSignature,downcast);rawDestructor=embind__requireFunction(destructorSignature,rawDestructor);var legalFunctionName=makeLegalFunctionName(name);exposePublicSymbol(legalFunctionName,function(){throwUnboundTypeError(`Cannot construct ${name} due to unbound types`,[baseClassRawType])});whenDependentTypesAreResolved([rawType,rawPointerType,rawConstPointerType],baseClassRawType?[baseClassRawType]:[],base=>{base=base[0];var baseClass;var basePrototype;if(baseClassRawType){baseClass=base.registeredClass;basePrototype=baseClass.instancePrototype}else{basePrototype=ClassHandle.prototype}var constructor=createNamedFunction(name,function(...args){if(Object.getPrototypeOf(this)!==instancePrototype){throw new BindingError(`Use 'new' to construct ${name}`)}if(undefined===registeredClass.constructor_body){throw new BindingError(`${name} has no accessible constructor`)}var body=registeredClass.constructor_body[args.length];if(undefined===body){throw new BindingError(`Tried to invoke ctor of ${name} with invalid number of parameters (${args.length}) - expected (${Object.keys(registeredClass.constructor_body).toString()}) parameters instead!`)}return body.apply(this,args)});var instancePrototype=Object.create(basePrototype,{constructor:{value:constructor}});constructor.prototype=instancePrototype;var registeredClass=new RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast);if(registeredClass.baseClass){registeredClass.baseClass.__derivedClasses??=[];registeredClass.baseClass.__derivedClasses.push(registeredClass)}var referenceConverter=new RegisteredPointer(name,registeredClass,true,false,false);var pointerConverter=new RegisteredPointer(name+"*",registeredClass,false,false,false);var constPointerConverter=new RegisteredPointer(name+" const*",registeredClass,false,true,false);registeredPointers[rawType]={pointerType:pointerConverter,constPointerType:constPointerConverter};replacePublicSymbol(legalFunctionName,constructor);return[referenceConverter,pointerConverter,constPointerConverter]})};var heap32VectorToArray=(count,firstElement)=>{var array=[];for(var i=0;i<count;i++){array.push(HEAPU32[firstElement+i*4>>2])}return array};function usesDestructorStack(argTypes){for(var i=1;i<argTypes.length;++i){if(argTypes[i]!==null&&argTypes[i].destructorFunction===undefined){return true}}return false}function craftInvokerFunction(humanName,argTypes,classType,cppInvokerFunc,cppTargetFunc,isAsync){var argCount=argTypes.length;if(argCount<2){throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!")}var isClassMethodFunc=argTypes[1]!==null&&classType!==null;var needsDestructorStack=usesDestructorStack(argTypes);var returns=!argTypes[0].isVoid;var expectedArgCount=argCount-2;var argsWired=new Array(expectedArgCount);var invokerFuncArgs=[];var destructors=[];var invokerFn=function(...args){destructors.length=0;var thisWired;invokerFuncArgs.length=isClassMethodFunc?2:1;invokerFuncArgs[0]=cppTargetFunc;if(isClassMethodFunc){thisWired=argTypes[1].toWireType(destructors,this);invokerFuncArgs[1]=thisWired}for(var i=0;i<expectedArgCount;++i){argsWired[i]=argTypes[i+2].toWireType(destructors,args[i]);invokerFuncArgs.push(argsWired[i])}var rv=cppInvokerFunc(...invokerFuncArgs);function onDone(rv){if(needsDestructorStack){runDestructors(destructors)}else{for(var i=isClassMethodFunc?1:2;i<argTypes.length;i++){var param=i===1?thisWired:argsWired[i-2];if(argTypes[i].destructorFunction!==null){argTypes[i].destructorFunction(param)}}}if(returns){return argTypes[0].fromWireType(rv)}}return onDone(rv)};return createNamedFunction(humanName,invokerFn)}var __embind_register_class_constructor=(rawClassType,argCount,rawArgTypesAddr,invokerSignature,invoker,rawConstructor)=>{var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);invoker=embind__requireFunction(invokerSignature,invoker);whenDependentTypesAreResolved([],[rawClassType],classType=>{classType=classType[0];var humanName=`constructor ${classType.name}`;if(undefined===classType.registeredClass.constructor_body){classType.registeredClass.constructor_body=[]}if(undefined!==classType.registeredClass.constructor_body[argCount-1]){throw new BindingError(`Cannot register multiple constructors with identical number of parameters (${argCount-1}) for class '${classType.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`)}classType.registeredClass.constructor_body[argCount-1]=()=>{throwUnboundTypeError(`Cannot construct ${classType.name} due to unbound types`,rawArgTypes)};whenDependentTypesAreResolved([],rawArgTypes,argTypes=>{argTypes.splice(1,0,null);classType.registeredClass.constructor_body[argCount-1]=craftInvokerFunction(humanName,argTypes,null,invoker,rawConstructor);return[]});return[]})};var getFunctionName=signature=>{signature=signature.trim();const argsIndex=signature.indexOf("(");if(argsIndex===-1)return signature;return signature.slice(0,argsIndex)};var __embind_register_class_function=(rawClassType,methodName,argCount,rawArgTypesAddr,invokerSignature,rawInvoker,context,isPureVirtual,isAsync,isNonnullReturn)=>{var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);methodName=AsciiToString(methodName);methodName=getFunctionName(methodName);rawInvoker=embind__requireFunction(invokerSignature,rawInvoker,isAsync);whenDependentTypesAreResolved([],[rawClassType],classType=>{classType=classType[0];var humanName=`${classType.name}.${methodName}`;if(methodName.startsWith("@@")){methodName=Symbol[methodName.substring(2)]}if(isPureVirtual){classType.registeredClass.pureVirtualFunctions.push(methodName)}function unboundTypesHandler(){throwUnboundTypeError(`Cannot call ${humanName} due to unbound types`,rawArgTypes)}var proto=classType.registeredClass.instancePrototype;var method=proto[methodName];if(undefined===method||undefined===method.overloadTable&&method.className!==classType.name&&method.argCount===argCount-2){unboundTypesHandler.argCount=argCount-2;unboundTypesHandler.className=classType.name;proto[methodName]=unboundTypesHandler}else{ensureOverloadTable(proto,methodName,humanName);proto[methodName].overloadTable[argCount-2]=unboundTypesHandler}whenDependentTypesAreResolved([],rawArgTypes,argTypes=>{var memberFunction=craftInvokerFunction(humanName,argTypes,classType,rawInvoker,context,isAsync);if(undefined===proto[methodName].overloadTable){memberFunction.argCount=argCount-2;proto[methodName]=memberFunction}else{proto[methodName].overloadTable[argCount-2]=memberFunction}return[]});return[]})};var emval_freelist=[];var emval_handles=[0,1,,1,null,1,true,1,false,1];var __emval_decref=handle=>{if(handle>9&&0===--emval_handles[handle+1]){emval_handles[handle]=undefined;emval_freelist.push(handle)}};var Emval={toValue:handle=>{if(!handle){throwBindingError(`Cannot use deleted val. handle = ${handle}`)}return emval_handles[handle]},toHandle:value=>{switch(value){case undefined:return 2;case null:return 4;case true:return 6;case false:return 8;default:{const handle=emval_freelist.pop()||emval_handles.length;emval_handles[handle]=value;emval_handles[handle+1]=1;return handle}}}};var EmValType={name:"emscripten::val",fromWireType:handle=>{var rv=Emval.toValue(handle);__emval_decref(handle);return rv},toWireType:(destructors,value)=>Emval.toHandle(value),readValueFromPointer:readPointer,destructorFunction:null};var __embind_register_emval=rawType=>registerType(rawType,EmValType);var enumReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?function(pointer){return this.fromWireType(HEAP8[pointer])}:function(pointer){return this.fromWireType(HEAPU8[pointer])};case 2:return signed?function(pointer){return this.fromWireType(HEAP16[pointer>>1])}:function(pointer){return this.fromWireType(HEAPU16[pointer>>1])};case 4:return signed?function(pointer){return this.fromWireType(HEAP32[pointer>>2])}:function(pointer){return this.fromWireType(HEAPU32[pointer>>2])};default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};function getEnumValueType(rawValueType){return rawValueType===0?"object":rawValueType===1?"number":"string"}var __embind_register_enum=(rawType,name,size,isSigned,rawValueType)=>{name=AsciiToString(name);const valueType=getEnumValueType(rawValueType);switch(valueType){case"object":{function ctor(){}ctor.values={};registerType(rawType,{name,constructor:ctor,valueType,fromWireType:function(c){return this.constructor.values[c]},toWireType:(destructors,c)=>c.value,readValueFromPointer:enumReadValueFromPointer(name,size,isSigned),destructorFunction:null});exposePublicSymbol(name,ctor);break}case"number":{var keysMap={};registerType(rawType,{name,keysMap,valueType,fromWireType:c=>c,toWireType:(destructors,c)=>c,readValueFromPointer:enumReadValueFromPointer(name,size,isSigned),destructorFunction:null});exposePublicSymbol(name,keysMap);delete Module[name].argCount;break}case"string":{var valuesMap={};var reverseMap={};var keysMap={};registerType(rawType,{name,valuesMap,reverseMap,keysMap,valueType,fromWireType:function(c){return this.reverseMap[c]},toWireType:function(destructors,c){return this.valuesMap[c]},readValueFromPointer:enumReadValueFromPointer(name,size,isSigned),destructorFunction:null});exposePublicSymbol(name,keysMap);delete Module[name].argCount;break}}};var requireRegisteredType=(rawType,humanName)=>{var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(`${humanName} has unknown type ${getTypeName(rawType)}`)}return impl};var __embind_register_enum_value=(rawEnumType,name,enumValue)=>{var enumType=requireRegisteredType(rawEnumType,"enum");name=AsciiToString(name);switch(enumType.valueType){case"object":{var Enum=enumType.constructor;var Value=Object.create(enumType.constructor.prototype,{value:{value:enumValue},constructor:{value:createNamedFunction(`${enumType.name}_${name}`,function(){})}});Enum.values[enumValue]=Value;Enum[name]=Value;break}case"number":{enumType.keysMap[name]=enumValue;break}case"string":{enumType.valuesMap[name]=enumValue;enumType.reverseMap[enumValue]=name;enumType.keysMap[name]=name;break}}};var floatReadValueFromPointer=(name,width)=>{switch(width){case 4:return function(pointer){return this.fromWireType(HEAPF32[pointer>>2])};case 8:return function(pointer){return this.fromWireType(HEAPF64[pointer>>3])};default:throw new TypeError(`invalid float width (${width}): ${name}`)}};var __embind_register_float=(rawType,name,size)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:value=>value,toWireType:(destructors,value)=>value,readValueFromPointer:floatReadValueFromPointer(name,size),destructorFunction:null})};var __embind_register_function=(name,argCount,rawArgTypesAddr,signature,rawInvoker,fn,isAsync,isNonnullReturn)=>{var argTypes=heap32VectorToArray(argCount,rawArgTypesAddr);name=AsciiToString(name);name=getFunctionName(name);rawInvoker=embind__requireFunction(signature,rawInvoker,isAsync);exposePublicSymbol(name,function(){throwUnboundTypeError(`Cannot call ${name} due to unbound types`,argTypes)},argCount-1);whenDependentTypesAreResolved([],argTypes,argTypes=>{var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));replacePublicSymbol(name,craftInvokerFunction(name,invokerArgsArray,null,rawInvoker,fn,isAsync),argCount-1);return[]})};var __embind_register_integer=(primitiveType,name,size,minRange,maxRange)=>{name=AsciiToString(name);const isUnsignedType=minRange===0;let fromWireType=value=>value;if(isUnsignedType){var bitshift=32-8*size;fromWireType=value=>value<<bitshift>>>bitshift;maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>value,readValueFromPointer:integerReadValueFromPointer(name,size,minRange!==0),destructorFunction:null})};var installIndexedIterator=(proto,sizeMethodName,getMethodName)=>{const makeIterator=(size,getValue)=>{let index=0;return{next(){if(index>=size){return{done:true}}const current=index;index++;const value=getValue(current);return{value,done:false}},[Symbol.iterator](){return this}}};if(!proto[Symbol.iterator]){proto[Symbol.iterator]=function(){const size=this[sizeMethodName]();return makeIterator(size,i=>this[getMethodName](i))}}};var __embind_register_iterable=(rawClassType,rawElementType,sizeMethodName,getMethodName)=>{sizeMethodName=AsciiToString(sizeMethodName);getMethodName=AsciiToString(getMethodName);whenDependentTypesAreResolved([],[rawClassType,rawElementType],types=>{const classType=types[0];installIndexedIterator(classType.registeredClass.instancePrototype,sizeMethodName,getMethodName);return[]})};var __embind_register_memory_view=(rawType,dataTypeIndex,name)=>{var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){var size=HEAPU32[handle>>2];var data=HEAPU32[handle+4>>2];return new TA(HEAP8.buffer,data,size)}name=AsciiToString(name);registerType(rawType,{name,fromWireType:decodeMemoryView,readValueFromPointer:decodeMemoryView},{ignoreDuplicateRegistrations:true})};var EmValOptionalType=Object.assign({optional:true},EmValType);var __embind_register_optional=(rawOptionalType,rawType)=>{registerType(rawOptionalType,EmValOptionalType)};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var __embind_register_std_string=(rawType,name)=>{name=AsciiToString(name);var stdStringIsUTF8=true;registerType(rawType,{name,fromWireType(value){var length=HEAPU32[value>>2];var payload=value+4;var str;if(stdStringIsUTF8){str=UTF8ToString(payload,length,true)}else{str="";for(var i=0;i<length;++i){str+=String.fromCharCode(HEAPU8[payload+i])}}_free(value);return str},toWireType(destructors,value){if(value instanceof ArrayBuffer){value=new Uint8Array(value)}var length;var valueIsOfTypeString=typeof value=="string";if(!(valueIsOfTypeString||ArrayBuffer.isView(value)&&value.BYTES_PER_ELEMENT==1)){throwBindingError("Cannot pass non-string to std::string")}if(stdStringIsUTF8&&valueIsOfTypeString){length=lengthBytesUTF8(value)}else{length=value.length}var base=_malloc(4+length+1);var ptr=base+4;HEAPU32[base>>2]=length;if(valueIsOfTypeString){if(stdStringIsUTF8){stringToUTF8(value,ptr,length+1)}else{for(var i=0;i<length;++i){var charCode=value.charCodeAt(i);if(charCode>255){_free(base);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+i]=charCode}}}else{HEAPU8.set(value,ptr)}if(destructors!==null){destructors.push(_free,base)}return base},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var UTF16Decoder=globalThis.TextDecoder?new TextDecoder("utf-16le"):undefined;var UTF16ToString=(ptr,maxBytesToRead,ignoreNul)=>{var idx=ptr>>1;var endIdx=findStringEnd(HEAPU16,idx,maxBytesToRead/2,ignoreNul);if(endIdx-idx>16&&UTF16Decoder)return UTF16Decoder.decode(HEAPU16.subarray(idx,endIdx));var str="";for(var i=idx;i<endIdx;++i){var codeUnit=HEAPU16[i];str+=String.fromCharCode(codeUnit)}return str};var stringToUTF16=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite<str.length*2?maxBytesToWrite/2:str.length;for(var i=0;i<numCharsToWrite;++i){var codeUnit=str.charCodeAt(i);HEAP16[outPtr>>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr};var lengthBytesUTF16=str=>str.length*2;var UTF32ToString=(ptr,maxBytesToRead,ignoreNul)=>{var str="";var startIdx=ptr>>2;for(var i=0;!(i>=maxBytesToRead/4);i++){var utf32=HEAPU32[startIdx+i];if(!utf32&&!ignoreNul)break;str+=String.fromCodePoint(utf32)}return str};var stringToUTF32=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535){i++}HEAP32[outPtr>>2]=codePoint;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr};var lengthBytesUTF32=str=>{var len=0;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535){i++}len+=4}return len};var __embind_register_std_wstring=(rawType,charSize,name)=>{name=AsciiToString(name);var decodeString,encodeString,lengthBytesUTF;if(charSize===2){decodeString=UTF16ToString;encodeString=stringToUTF16;lengthBytesUTF=lengthBytesUTF16}else{decodeString=UTF32ToString;encodeString=stringToUTF32;lengthBytesUTF=lengthBytesUTF32}registerType(rawType,{name,fromWireType:value=>{var length=HEAPU32[value>>2];var str=decodeString(value+4,length*charSize,true);_free(value);return str},toWireType:(destructors,value)=>{if(!(typeof value=="string")){throwBindingError(`Cannot pass non-string to C++ string type ${name}`)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length/charSize;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var __embind_register_value_object=(rawType,name,constructorSignature,rawConstructor,destructorSignature,rawDestructor)=>{structRegistrations[rawType]={name:AsciiToString(name),rawConstructor:embind__requireFunction(constructorSignature,rawConstructor),rawDestructor:embind__requireFunction(destructorSignature,rawDestructor),fields:[]}};var __embind_register_value_object_field=(structType,fieldName,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext)=>{structRegistrations[structType].fields.push({fieldName:AsciiToString(fieldName),getterReturnType,getter:embind__requireFunction(getterSignature,getter),getterContext,setterArgumentType,setter:embind__requireFunction(setterSignature,setter),setterContext})};var __embind_register_void=(rawType,name)=>{name=AsciiToString(name);registerType(rawType,{isVoid:true,name,fromWireType:()=>undefined,toWireType:(destructors,o)=>undefined})};var runtimeKeepaliveCounter=0;var __emscripten_runtime_keepalive_clear=()=>{noExitRuntime=false;runtimeKeepaliveCounter=0};var emval_methodCallers=[];var emval_addMethodCaller=caller=>{var id=emval_methodCallers.length;emval_methodCallers.push(caller);return id};var emval_lookupTypes=(argCount,argTypes)=>{var a=new Array(argCount);for(var i=0;i<argCount;++i){a[i]=requireRegisteredType(HEAPU32[argTypes+i*4>>2],`parameter ${i}`)}return a};var emval_returnValue=(toReturnWire,destructorsRef,handle)=>{var destructors=[];var result=toReturnWire(destructors,handle);if(destructors.length){HEAPU32[destructorsRef>>2]=Emval.toHandle(destructors)}return result};var emval_symbols={};var getStringOrSymbol=address=>{var symbol=emval_symbols[address];if(symbol===undefined){return AsciiToString(address)}return symbol};var __emval_create_invoker=(argCount,argTypesPtr,kind)=>{var GenericWireTypeSize=8;var[retType,...argTypes]=emval_lookupTypes(argCount,argTypesPtr);var toReturnWire=retType.toWireType.bind(retType);var argFromPtr=argTypes.map(type=>type.readValueFromPointer.bind(type));argCount--;var argN=new Array(argCount);var invokerFunction=(handle,methodName,destructorsRef,args)=>{var offset=0;for(var i=0;i<argCount;++i){argN[i]=argFromPtr[i](args+offset);offset+=GenericWireTypeSize}var rv;switch(kind){case 0:rv=Emval.toValue(handle).apply(null,argN);break;case 2:rv=Reflect.construct(Emval.toValue(handle),argN);break;case 3:rv=argN[0];break;case 1:rv=Emval.toValue(handle)[getStringOrSymbol(methodName)](...argN);break}return emval_returnValue(toReturnWire,destructorsRef,rv)};var functionName=`methodCaller<(${argTypes.map(t=>t.name)}) => ${retType.name}>`;return emval_addMethodCaller(createNamedFunction(functionName,invokerFunction))};var __emval_invoke=(caller,handle,methodName,destructorsRef,args)=>emval_methodCallers[caller](handle,methodName,destructorsRef,args);var __emval_new_array=()=>Emval.toHandle([]);var __emval_new_cstring=v=>Emval.toHandle(getStringOrSymbol(v));var __emval_new_object=()=>Emval.toHandle({});var __emval_run_destructors=handle=>{var destructors=Emval.toValue(handle);runDestructors(destructors);__emval_decref(handle)};var __emval_set_property=(handle,key,value)=>{handle=Emval.toValue(handle);key=Emval.toValue(key);value=Emval.toValue(value);handle[key]=value};var timers={};var handleException=e=>{if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)};var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;var maybeExit=()=>{if(!keepRuntimeAlive()){try{_exit(EXITSTATUS)}catch(e){handleException(e)}}};var callUserCallback=func=>{if(ABORT){return}try{return func()}catch(e){handleException(e)}finally{maybeExit()}};var _emscripten_get_now=()=>performance.now();var __setitimer_js=(which,timeout_ms)=>{if(timers[which]){clearTimeout(timers[which].id);delete timers[which]}if(!timeout_ms)return 0;var id=setTimeout(()=>{delete timers[which];callUserCallback(()=>__emscripten_timeout(which,_emscripten_get_now()))},timeout_ms);timers[which]={id,timeout_ms};return 0};var __tzset_js=(timezone,daylight,std_name,dst_name)=>{var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);HEAPU32[timezone>>2]=stdTimezoneOffset*60;HEAP32[daylight>>2]=Number(winterOffset!=summerOffset);var extractZone=timezoneOffset=>{var sign=timezoneOffset>=0?"-":"+";var absOffset=Math.abs(timezoneOffset);var hours=String(Math.floor(absOffset/60)).padStart(2,"0");var minutes=String(absOffset%60).padStart(2,"0");return`UTC${sign}${hours}${minutes}`};var winterName=extractZone(winterOffset);var summerName=extractZone(summerOffset);if(summerOffset<winterOffset){stringToUTF8(winterName,std_name,17);stringToUTF8(summerName,dst_name,17)}else{stringToUTF8(winterName,dst_name,17);stringToUTF8(summerName,std_name,17)}};var _emscripten_date_now=()=>Date.now();var nowIsMonotonic=1;var checkWasiClock=clock_id=>clock_id>=0&&clock_id<=3;var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function _clock_time_get(clk_id,ignored_precision,ptime){ignored_precision=bigintToI53Checked(ignored_precision);if(!checkWasiClock(clk_id)){return 28}var now;if(clk_id===0){now=_emscripten_date_now()}else if(nowIsMonotonic){now=_emscripten_get_now()}else{return 52}var nsec=Math.round(now*1e3*1e3);HEAP64[ptime>>3]=BigInt(nsec);return 0}var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var GLctx;var webgl_enable_ANGLE_instanced_arrays=ctx=>{var ext=ctx.getExtension("ANGLE_instanced_arrays");if(ext){ctx["vertexAttribDivisor"]=(index,divisor)=>ext["vertexAttribDivisorANGLE"](index,divisor);ctx["drawArraysInstanced"]=(mode,first,count,primcount)=>ext["drawArraysInstancedANGLE"](mode,first,count,primcount);ctx["drawElementsInstanced"]=(mode,count,type,indices,primcount)=>ext["drawElementsInstancedANGLE"](mode,count,type,indices,primcount);return 1}};var webgl_enable_OES_vertex_array_object=ctx=>{var ext=ctx.getExtension("OES_vertex_array_object");if(ext){ctx["createVertexArray"]=()=>ext["createVertexArrayOES"]();ctx["deleteVertexArray"]=vao=>ext["deleteVertexArrayOES"](vao);ctx["bindVertexArray"]=vao=>ext["bindVertexArrayOES"](vao);ctx["isVertexArray"]=vao=>ext["isVertexArrayOES"](vao);return 1}};var webgl_enable_WEBGL_draw_buffers=ctx=>{var ext=ctx.getExtension("WEBGL_draw_buffers");if(ext){ctx["drawBuffers"]=(n,bufs)=>ext["drawBuffersWEBGL"](n,bufs);return 1}};var webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance=ctx=>!!(ctx.dibvbi=ctx.getExtension("WEBGL_draw_instanced_base_vertex_base_instance"));var webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance=ctx=>!!(ctx.mdibvbi=ctx.getExtension("WEBGL_multi_draw_instanced_base_vertex_base_instance"));var webgl_enable_EXT_polygon_offset_clamp=ctx=>!!(ctx.extPolygonOffsetClamp=ctx.getExtension("EXT_polygon_offset_clamp"));var webgl_enable_EXT_clip_control=ctx=>!!(ctx.extClipControl=ctx.getExtension("EXT_clip_control"));var webgl_enable_WEBGL_polygon_mode=ctx=>!!(ctx.webglPolygonMode=ctx.getExtension("WEBGL_polygon_mode"));var webgl_enable_WEBGL_multi_draw=ctx=>!!(ctx.multiDrawWebgl=ctx.getExtension("WEBGL_multi_draw"));var getEmscriptenSupportedExtensions=ctx=>{var supportedExtensions=["ANGLE_instanced_arrays","EXT_blend_minmax","EXT_disjoint_timer_query","EXT_frag_depth","EXT_shader_texture_lod","EXT_sRGB","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","WEBGL_color_buffer_float","WEBGL_depth_texture","WEBGL_draw_buffers","EXT_color_buffer_float","EXT_conservative_depth","EXT_disjoint_timer_query_webgl2","EXT_texture_norm16","NV_shader_noperspective_interpolation","WEBGL_clip_cull_distance","EXT_clip_control","EXT_color_buffer_half_float","EXT_depth_clamp","EXT_float_blend","EXT_polygon_offset_clamp","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","KHR_parallel_shader_compile","OES_texture_float_linear","WEBGL_blend_func_extended","WEBGL_compressed_texture_astc","WEBGL_compressed_texture_etc","WEBGL_compressed_texture_etc1","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_lose_context","WEBGL_multi_draw","WEBGL_polygon_mode"];return(ctx.getSupportedExtensions()||[]).filter(ext=>supportedExtensions.includes(ext))};var registerPreMainLoop=f=>{typeof MainLoop!="undefined"&&MainLoop.preMainLoop.push(f)};var GL={counter:1,buffers:[],mappedBuffers:{},programs:[],framebuffers:[],renderbuffers:[],textures:[],shaders:[],vaos:[],contexts:[],offscreenCanvases:{},queries:[],samplers:[],transformFeedbacks:[],syncs:[],byteSizeByTypeRoot:5120,byteSizeByType:[1,1,2,2,4,4,4,2,3,4,8],stringCache:{},stringiCache:{},unpackAlignment:4,unpackRowLength:0,recordError:errorCode=>{if(!GL.lastError){GL.lastError=errorCode}},getNewId:table=>{var ret=GL.counter++;for(var i=table.length;i<ret;i++){table[i]=null}while(table[ret]){ret=GL.counter++}return ret},genObject:(n,buffers,createFunction,objectTable)=>{for(var i=0;i<n;i++){var buffer=GLctx[createFunction]();var id=buffer&&GL.getNewId(objectTable);if(buffer){buffer.name=id;objectTable[id]=buffer}else{GL.recordError(1282)}HEAP32[buffers+i*4>>2]=id}},MAX_TEMP_BUFFER_SIZE:2097152,numTempVertexBuffersPerSize:64,log2ceilLookup:i=>32-Math.clz32(i===0?0:i-1),generateTempBuffers:(quads,context)=>{var largestIndex=GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);context.tempVertexBufferCounters1=[];context.tempVertexBufferCounters2=[];context.tempVertexBufferCounters1.length=context.tempVertexBufferCounters2.length=largestIndex+1;context.tempVertexBuffers1=[];context.tempVertexBuffers2=[];context.tempVertexBuffers1.length=context.tempVertexBuffers2.length=largestIndex+1;context.tempIndexBuffers=[];context.tempIndexBuffers.length=largestIndex+1;for(var i=0;i<=largestIndex;++i){context.tempIndexBuffers[i]=null;context.tempVertexBufferCounters1[i]=context.tempVertexBufferCounters2[i]=0;var ringbufferLength=GL.numTempVertexBuffersPerSize;context.tempVertexBuffers1[i]=[];context.tempVertexBuffers2[i]=[];var ringbuffer1=context.tempVertexBuffers1[i];var ringbuffer2=context.tempVertexBuffers2[i];ringbuffer1.length=ringbuffer2.length=ringbufferLength;for(var j=0;j<ringbufferLength;++j){ringbuffer1[j]=ringbuffer2[j]=null}}if(quads){context.tempQuadIndexBuffer=GLctx.createBuffer();context.GLctx.bindBuffer(34963,context.tempQuadIndexBuffer);var numIndexes=GL.MAX_TEMP_BUFFER_SIZE>>1;var quadIndexes=new Uint16Array(numIndexes);var i=0,v=0;while(1){quadIndexes[i++]=v;if(i>=numIndexes)break;quadIndexes[i++]=v+1;if(i>=numIndexes)break;quadIndexes[i++]=v+2;if(i>=numIndexes)break;quadIndexes[i++]=v;if(i>=numIndexes)break;quadIndexes[i++]=v+2;if(i>=numIndexes)break;quadIndexes[i++]=v+3;if(i>=numIndexes)break;v+=4}context.GLctx.bufferData(34963,quadIndexes,35044);context.GLctx.bindBuffer(34963,null)}},getTempVertexBuffer:sizeBytes=>{var idx=GL.log2ceilLookup(sizeBytes);var ringbuffer=GL.currentContext.tempVertexBuffers1[idx];var nextFreeBufferIndex=GL.currentContext.tempVertexBufferCounters1[idx];GL.currentContext.tempVertexBufferCounters1[idx]=GL.currentContext.tempVertexBufferCounters1[idx]+1&GL.numTempVertexBuffersPerSize-1;var vbo=ringbuffer[nextFreeBufferIndex];if(vbo){return vbo}var prevVBO=GLctx.getParameter(34964);ringbuffer[nextFreeBufferIndex]=GLctx.createBuffer();GLctx.bindBuffer(34962,ringbuffer[nextFreeBufferIndex]);GLctx.bufferData(34962,1<<idx,35048);GLctx.bindBuffer(34962,prevVBO);return ringbuffer[nextFreeBufferIndex]},getTempIndexBuffer:sizeBytes=>{var idx=GL.log2ceilLookup(sizeBytes);var ibo=GL.currentContext.tempIndexBuffers[idx];if(ibo){return ibo}var prevIBO=GLctx.getParameter(34965);GL.currentContext.tempIndexBuffers[idx]=GLctx.createBuffer();GLctx.bindBuffer(34963,GL.currentContext.tempIndexBuffers[idx]);GLctx.bufferData(34963,1<<idx,35048);GLctx.bindBuffer(34963,prevIBO);return GL.currentContext.tempIndexBuffers[idx]},newRenderingFrameStarted:()=>{if(!GL.currentContext){return}var vb=GL.currentContext.tempVertexBuffers1;GL.currentContext.tempVertexBuffers1=GL.currentContext.tempVertexBuffers2;GL.currentContext.tempVertexBuffers2=vb;vb=GL.currentContext.tempVertexBufferCounters1;GL.currentContext.tempVertexBufferCounters1=GL.currentContext.tempVertexBufferCounters2;GL.currentContext.tempVertexBufferCounters2=vb;var largestIndex=GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);for(var i=0;i<=largestIndex;++i){GL.currentContext.tempVertexBufferCounters1[i]=0}},getSource:(shader,count,string,length)=>{var source="";for(var i=0;i<count;++i){var len=length?HEAPU32[length+i*4>>2]:undefined;source+=UTF8ToString(HEAPU32[string+i*4>>2],len)}return source},calcBufLength:(size,type,stride,count)=>{if(stride>0){return count*stride}var typeSize=GL.byteSizeByType[type-GL.byteSizeByTypeRoot];return size*typeSize*count},usedTempBuffers:[],preDrawHandleClientVertexAttribBindings:count=>{GL.resetBufferBinding=false;for(var i=0;i<GL.currentContext.maxVertexAttribs;++i){var cb=GL.currentContext.clientBuffers[i];if(!cb.clientside||!cb.enabled)continue;GL.resetBufferBinding=true;var size=GL.calcBufLength(cb.size,cb.type,cb.stride,count);var buf=GL.getTempVertexBuffer(size);GLctx.bindBuffer(34962,buf);GLctx.bufferSubData(34962,0,HEAPU8.subarray(cb.ptr,cb.ptr+size));cb.vertexAttribPointerAdaptor.call(GLctx,i,cb.size,cb.type,cb.normalized,cb.stride,0)}},postDrawHandleClientVertexAttribBindings:()=>{if(GL.resetBufferBinding){GLctx.bindBuffer(34962,GL.buffers[GLctx.currentArrayBufferBinding])}},createContext:(canvas,webGLContextAttributes)=>{if(!canvas.getContextSafariWebGL2Fixed){canvas.getContextSafariWebGL2Fixed=canvas.getContext;function fixedGetContext(ver,attrs){var gl=canvas.getContextSafariWebGL2Fixed(ver,attrs);return ver=="webgl"==gl instanceof WebGLRenderingContext?gl:null}canvas.getContext=fixedGetContext}var ctx=webGLContextAttributes.majorVersion>1?canvas.getContext("webgl2",webGLContextAttributes):canvas.getContext("webgl",webGLContextAttributes);if(!ctx)return 0;var handle=GL.registerContext(ctx,webGLContextAttributes);return handle},registerContext:(ctx,webGLContextAttributes)=>{var handle=GL.getNewId(GL.contexts);var context={handle,attributes:webGLContextAttributes,version:webGLContextAttributes.majorVersion,GLctx:ctx};if(ctx.canvas)ctx.canvas.GLctxObject=context;GL.contexts[handle]=context;if(typeof webGLContextAttributes.enableExtensionsByDefault=="undefined"||webGLContextAttributes.enableExtensionsByDefault){GL.initExtensions(context)}context.maxVertexAttribs=context.GLctx.getParameter(34921);context.clientBuffers=[];for(var i=0;i<context.maxVertexAttribs;i++){context.clientBuffers[i]={enabled:false,clientside:false,size:0,type:0,normalized:0,stride:0,ptr:0,vertexAttribPointerAdaptor:null}}GL.generateTempBuffers(false,context);return handle},makeContextCurrent:contextHandle=>{GL.currentContext=GL.contexts[contextHandle];Module["ctx"]=GLctx=GL.currentContext?.GLctx;return!(contextHandle&&!GLctx)},getContext:contextHandle=>GL.contexts[contextHandle],deleteContext:contextHandle=>{if(GL.currentContext===GL.contexts[contextHandle]){GL.currentContext=null}if(typeof JSEvents=="object"){JSEvents.removeAllHandlersOnTarget(GL.contexts[contextHandle].GLctx.canvas)}if(GL.contexts[contextHandle]?.GLctx.canvas){GL.contexts[contextHandle].GLctx.canvas.GLctxObject=undefined}GL.contexts[contextHandle]=null},initExtensions:context=>{context||=GL.currentContext;if(context.initExtensionsDone)return;context.initExtensionsDone=true;var GLctx=context.GLctx;webgl_enable_WEBGL_multi_draw(GLctx);webgl_enable_EXT_polygon_offset_clamp(GLctx);webgl_enable_EXT_clip_control(GLctx);webgl_enable_WEBGL_polygon_mode(GLctx);webgl_enable_ANGLE_instanced_arrays(GLctx);webgl_enable_OES_vertex_array_object(GLctx);webgl_enable_WEBGL_draw_buffers(GLctx);webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance(GLctx);webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance(GLctx);if(context.version>=2){GLctx.disjointTimerQueryExt=GLctx.getExtension("EXT_disjoint_timer_query_webgl2")}if(context.version<2||!GLctx.disjointTimerQueryExt){GLctx.disjointTimerQueryExt=GLctx.getExtension("EXT_disjoint_timer_query")}for(var ext of getEmscriptenSupportedExtensions(GLctx)){if(!ext.includes("lose_context")&&!ext.includes("debug")){GLctx.getExtension(ext)}}}};var webglPowerPreferences=["default","low-power","high-performance"];var maybeCStringToJsString=cString=>cString>2?UTF8ToString(cString):cString;var specialHTMLTargets=[0,document,window];var findEventTarget=target=>{target=maybeCStringToJsString(target);var domElement=specialHTMLTargets[target]||document.querySelector(target);return domElement};var findCanvasEventTarget=findEventTarget;var _emscripten_webgl_do_create_context=(target,attributes)=>{var attr32=attributes>>2;var powerPreference=HEAP32[attr32+(8>>2)];var contextAttributes={alpha:!!HEAP8[attributes+0],depth:!!HEAP8[attributes+1],stencil:!!HEAP8[attributes+2],antialias:!!HEAP8[attributes+3],premultipliedAlpha:!!HEAP8[attributes+4],preserveDrawingBuffer:!!HEAP8[attributes+5],powerPreference:webglPowerPreferences[powerPreference],failIfMajorPerformanceCaveat:!!HEAP8[attributes+12],majorVersion:HEAP32[attr32+(16>>2)],minorVersion:HEAP32[attr32+(20>>2)],enableExtensionsByDefault:HEAP8[attributes+24],explicitSwapControl:HEAP8[attributes+25],proxyContextToMainThread:HEAP32[attr32+(28>>2)],renderViaOffscreenBackBuffer:HEAP8[attributes+32]};var canvas=findCanvasEventTarget(target);if(!canvas){return 0}if(contextAttributes.explicitSwapControl){return 0}var contextHandle=GL.createContext(canvas,contextAttributes);return contextHandle};var _emscripten_webgl_create_context=_emscripten_webgl_do_create_context;var _emscripten_webgl_destroy_context=contextHandle=>{if(GL.currentContext==contextHandle)GL.currentContext=0;GL.deleteContext(contextHandle)};var _emscripten_webgl_make_context_current=contextHandle=>{var success=GL.makeContextCurrent(contextHandle);return success?0:-5};var ENV={};var getExecutableName=()=>thisProgram||"./this.program";var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8";var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:lang,_:getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(`${x}=${env[x]}`)}getEnvStrings.strings=strings}return getEnvStrings.strings};var _environ_get=(__environ,environ_buf)=>{var bufSize=0;var envp=0;for(var string of getEnvStrings()){var ptr=environ_buf+bufSize;HEAPU32[__environ+envp>>2]=ptr;bufSize+=stringToUTF8(string,ptr,Infinity)+1;envp+=4}return 0};var _environ_sizes_get=(penviron_count,penviron_buf_size)=>{var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;for(var string of strings){bufSize+=lengthBytesUTF8(string)+1}HEAPU32[penviron_buf_size>>2]=bufSize;return 0};function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doReadv=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len)break;if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_read(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doReadv(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}function _fd_seek(fd,offset,whence,newOffset){offset=bigintToI53Checked(offset);try{if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);HEAP64[newOffset>>3]=BigInt(stream.position);if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doWritev=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len){break}if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_write(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doWritev(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var _emscripten_glActiveTexture=x0=>GLctx.activeTexture(x0);var _glActiveTexture=_emscripten_glActiveTexture;var _emscripten_glAttachShader=(program,shader)=>{GLctx.attachShader(GL.programs[program],GL.shaders[shader])};var _glAttachShader=_emscripten_glAttachShader;var _emscripten_glBindAttribLocation=(program,index,name)=>{GLctx.bindAttribLocation(GL.programs[program],index,UTF8ToString(name))};var _glBindAttribLocation=_emscripten_glBindAttribLocation;var _emscripten_glBindBuffer=(target,buffer)=>{if(buffer&&!GL.buffers[buffer]){var b=GLctx.createBuffer();b.name=buffer;GL.buffers[buffer]=b}if(target==34962){GLctx.currentArrayBufferBinding=buffer}else if(target==34963){GLctx.currentElementArrayBufferBinding=buffer}if(target==35051){GLctx.currentPixelPackBufferBinding=buffer}else if(target==35052){GLctx.currentPixelUnpackBufferBinding=buffer}GLctx.bindBuffer(target,GL.buffers[buffer])};var _glBindBuffer=_emscripten_glBindBuffer;var _emscripten_glBindFramebuffer=(target,framebuffer)=>{GLctx.bindFramebuffer(target,GL.framebuffers[framebuffer])};var _glBindFramebuffer=_emscripten_glBindFramebuffer;var _emscripten_glBindTexture=(target,texture)=>{GLctx.bindTexture(target,GL.textures[texture])};var _glBindTexture=_emscripten_glBindTexture;var _emscripten_glBindVertexArray=vao=>{GLctx.bindVertexArray(GL.vaos[vao]);var ibo=GLctx.getParameter(34965);GLctx.currentElementArrayBufferBinding=ibo?ibo.name|0:0};var _glBindVertexArray=_emscripten_glBindVertexArray;var _emscripten_glBlendFunc=(x0,x1)=>GLctx.blendFunc(x0,x1);var _glBlendFunc=_emscripten_glBlendFunc;var _emscripten_glBlendFuncSeparate=(x0,x1,x2,x3)=>GLctx.blendFuncSeparate(x0,x1,x2,x3);var _glBlendFuncSeparate=_emscripten_glBlendFuncSeparate;var _emscripten_glBufferData=(target,size,data,usage)=>{if(GL.currentContext.version>=2){if(data&&size){GLctx.bufferData(target,HEAPU8,usage,data,size)}else{GLctx.bufferData(target,size,usage)}return}GLctx.bufferData(target,data?HEAPU8.subarray(data,data+size):size,usage)};var _glBufferData=_emscripten_glBufferData;var _emscripten_glBufferSubData=(target,offset,size,data)=>{if(GL.currentContext.version>=2){size&&GLctx.bufferSubData(target,offset,HEAPU8,data,size);return}GLctx.bufferSubData(target,offset,HEAPU8.subarray(data,data+size))};var _glBufferSubData=_emscripten_glBufferSubData;var _emscripten_glCheckFramebufferStatus=x0=>GLctx.checkFramebufferStatus(x0);var _glCheckFramebufferStatus=_emscripten_glCheckFramebufferStatus;var _emscripten_glClear=x0=>GLctx.clear(x0);var _glClear=_emscripten_glClear;var _emscripten_glClearColor=(x0,x1,x2,x3)=>GLctx.clearColor(x0,x1,x2,x3);var _glClearColor=_emscripten_glClearColor;var _emscripten_glClearStencil=x0=>GLctx.clearStencil(x0);var _glClearStencil=_emscripten_glClearStencil;var _emscripten_glColorMask=(red,green,blue,alpha)=>{GLctx.colorMask(!!red,!!green,!!blue,!!alpha)};var _glColorMask=_emscripten_glColorMask;var _emscripten_glCompileShader=shader=>{GLctx.compileShader(GL.shaders[shader])};var _glCompileShader=_emscripten_glCompileShader;var _emscripten_glCreateProgram=()=>{var id=GL.getNewId(GL.programs);var program=GLctx.createProgram();program.name=id;program.maxUniformLength=program.maxAttributeLength=program.maxUniformBlockNameLength=0;program.uniformIdCounter=1;GL.programs[id]=program;return id};var _glCreateProgram=_emscripten_glCreateProgram;var _emscripten_glCreateShader=shaderType=>{var id=GL.getNewId(GL.shaders);GL.shaders[id]=GLctx.createShader(shaderType);return id};var _glCreateShader=_emscripten_glCreateShader;var _emscripten_glDeleteBuffers=(n,buffers)=>{for(var i=0;i<n;i++){var id=HEAP32[buffers+i*4>>2];var buffer=GL.buffers[id];if(!buffer)continue;GLctx.deleteBuffer(buffer);buffer.name=0;GL.buffers[id]=null;if(id==GLctx.currentArrayBufferBinding)GLctx.currentArrayBufferBinding=0;if(id==GLctx.currentElementArrayBufferBinding)GLctx.currentElementArrayBufferBinding=0;if(id==GLctx.currentPixelPackBufferBinding)GLctx.currentPixelPackBufferBinding=0;if(id==GLctx.currentPixelUnpackBufferBinding)GLctx.currentPixelUnpackBufferBinding=0}};var _glDeleteBuffers=_emscripten_glDeleteBuffers;var _emscripten_glDeleteFramebuffers=(n,framebuffers)=>{for(var i=0;i<n;++i){var id=HEAP32[framebuffers+i*4>>2];var framebuffer=GL.framebuffers[id];if(!framebuffer)continue;GLctx.deleteFramebuffer(framebuffer);framebuffer.name=0;GL.framebuffers[id]=null}};var _glDeleteFramebuffers=_emscripten_glDeleteFramebuffers;var _emscripten_glDeleteProgram=id=>{if(!id)return;var program=GL.programs[id];if(!program){GL.recordError(1281);return}GLctx.deleteProgram(program);program.name=0;GL.programs[id]=null};var _glDeleteProgram=_emscripten_glDeleteProgram;var _emscripten_glDeleteShader=id=>{if(!id)return;var shader=GL.shaders[id];if(!shader){GL.recordError(1281);return}GLctx.deleteShader(shader);GL.shaders[id]=null};var _glDeleteShader=_emscripten_glDeleteShader;var _emscripten_glDeleteTextures=(n,textures)=>{for(var i=0;i<n;i++){var id=HEAP32[textures+i*4>>2];var texture=GL.textures[id];if(!texture)continue;GLctx.deleteTexture(texture);texture.name=0;GL.textures[id]=null}};var _glDeleteTextures=_emscripten_glDeleteTextures;var _emscripten_glDeleteVertexArrays=(n,vaos)=>{for(var i=0;i<n;i++){var id=HEAP32[vaos+i*4>>2];GLctx.deleteVertexArray(GL.vaos[id]);GL.vaos[id]=null}};var _glDeleteVertexArrays=_emscripten_glDeleteVertexArrays;var _emscripten_glDisable=x0=>GLctx.disable(x0);var _glDisable=_emscripten_glDisable;var _emscripten_glDrawArrays=(mode,first,count)=>{GL.preDrawHandleClientVertexAttribBindings(first+count);GLctx.drawArrays(mode,first,count);GL.postDrawHandleClientVertexAttribBindings()};var _glDrawArrays=_emscripten_glDrawArrays;var _emscripten_glDrawElements=(mode,count,type,indices)=>{var buf;var vertexes=0;if(!GLctx.currentElementArrayBufferBinding){var size=GL.calcBufLength(1,type,0,count);buf=GL.getTempIndexBuffer(size);GLctx.bindBuffer(34963,buf);GLctx.bufferSubData(34963,0,HEAPU8.subarray(indices,indices+size));if(count>0){for(var i=0;i<GL.currentContext.maxVertexAttribs;++i){var cb=GL.currentContext.clientBuffers[i];if(cb.clientside&&cb.enabled){let arrayClass;switch(type){case 5121:arrayClass=Uint8Array;break;case 5123:arrayClass=Uint16Array;break;case 5125:arrayClass=Uint32Array;break;default:GL.recordError(1282);return}vertexes=new arrayClass(HEAPU8.buffer,indices,count).reduce((max,current)=>Math.max(max,current))+1;break}}}indices=0}GL.preDrawHandleClientVertexAttribBindings(vertexes);GLctx.drawElements(mode,count,type,indices);GL.postDrawHandleClientVertexAttribBindings(count);if(!GLctx.currentElementArrayBufferBinding){GLctx.bindBuffer(34963,null)}};var _glDrawElements=_emscripten_glDrawElements;var _emscripten_glEnable=x0=>GLctx.enable(x0);var _glEnable=_emscripten_glEnable;var _emscripten_glEnableVertexAttribArray=index=>{var cb=GL.currentContext.clientBuffers[index];cb.enabled=true;GLctx.enableVertexAttribArray(index)};var _glEnableVertexAttribArray=_emscripten_glEnableVertexAttribArray;var _emscripten_glFramebufferTexture2D=(target,attachment,textarget,texture,level)=>{GLctx.framebufferTexture2D(target,attachment,textarget,GL.textures[texture],level)};var _glFramebufferTexture2D=_emscripten_glFramebufferTexture2D;var _emscripten_glGenBuffers=(n,buffers)=>{GL.genObject(n,buffers,"createBuffer",GL.buffers)};var _glGenBuffers=_emscripten_glGenBuffers;var _emscripten_glGenFramebuffers=(n,ids)=>{GL.genObject(n,ids,"createFramebuffer",GL.framebuffers)};var _glGenFramebuffers=_emscripten_glGenFramebuffers;var _emscripten_glGenTextures=(n,textures)=>{GL.genObject(n,textures,"createTexture",GL.textures)};var _glGenTextures=_emscripten_glGenTextures;var _emscripten_glGenVertexArrays=(n,arrays)=>{GL.genObject(n,arrays,"createVertexArray",GL.vaos)};var _glGenVertexArrays=_emscripten_glGenVertexArrays;var _emscripten_glGenerateMipmap=x0=>GLctx.generateMipmap(x0);var _glGenerateMipmap=_emscripten_glGenerateMipmap;var _emscripten_glGetAttribLocation=(program,name)=>GLctx.getAttribLocation(GL.programs[program],UTF8ToString(name));var _glGetAttribLocation=_emscripten_glGetAttribLocation;var _emscripten_glGetError=()=>{var error=GLctx.getError()||GL.lastError;GL.lastError=0;return error};var _glGetError=_emscripten_glGetError;var writeI53ToI64=(ptr,num)=>{HEAPU32[ptr>>2]=num;var lower=HEAPU32[ptr>>2];HEAPU32[ptr+4>>2]=(num-lower)/4294967296};var webglGetExtensions=()=>{var exts=getEmscriptenSupportedExtensions(GLctx);exts=exts.concat(exts.map(e=>"GL_"+e));return exts};var emscriptenWebGLGet=(name_,p,type)=>{if(!p){GL.recordError(1281);return}var ret=undefined;switch(name_){case 36346:ret=1;break;case 36344:if(type!=0&&type!=1){GL.recordError(1280)}return;case 34814:case 36345:ret=0;break;case 34466:var formats=GLctx.getParameter(34467);ret=formats?formats.length:0;break;case 33309:if(GL.currentContext.version<2){GL.recordError(1282);return}ret=webglGetExtensions().length;break;case 33307:case 33308:if(GL.currentContext.version<2){GL.recordError(1280);return}ret=name_==33307?3:0;break}if(ret===undefined){var result=GLctx.getParameter(name_);switch(typeof result){case"number":ret=result;break;case"boolean":ret=result?1:0;break;case"string":GL.recordError(1280);return;case"object":if(result===null){switch(name_){case 34964:case 35725:case 34965:case 36006:case 36007:case 32873:case 34229:case 36662:case 36663:case 35053:case 35055:case 36010:case 35097:case 35869:case 32874:case 36389:case 35983:case 35368:case 34068:{ret=0;break}default:{GL.recordError(1280);return}}}else if(result instanceof Float32Array||result instanceof Uint32Array||result instanceof Int32Array||result instanceof Array){for(var i=0;i<result.length;++i){switch(type){case 0:HEAP32[p+i*4>>2]=result[i];break;case 2:HEAPF32[p+i*4>>2]=result[i];break;case 4:HEAP8[p+i]=result[i]?1:0;break}}return}else{try{ret=result.name|0}catch(e){GL.recordError(1280);err(`GL_INVALID_ENUM in glGet${type}v: Unknown object returned from WebGL getParameter(${name_})! (error: ${e})`);return}}break;default:GL.recordError(1280);err(`GL_INVALID_ENUM in glGet${type}v: Native code calling glGet${type}v(${name_}) and it returns ${result} of type ${typeof result}!`);return}}switch(type){case 1:writeI53ToI64(p,ret);break;case 0:HEAP32[p>>2]=ret;break;case 2:HEAPF32[p>>2]=ret;break;case 4:HEAP8[p]=ret?1:0;break}};var _emscripten_glGetIntegerv=(name_,p)=>emscriptenWebGLGet(name_,p,0);var _glGetIntegerv=_emscripten_glGetIntegerv;var _emscripten_glGetProgramInfoLog=(program,maxLength,length,infoLog)=>{var log=GLctx.getProgramInfoLog(GL.programs[program]);if(log===null)log="(unknown error)";var numBytesWrittenExclNull=maxLength>0&&infoLog?stringToUTF8(log,infoLog,maxLength):0;if(length)HEAP32[length>>2]=numBytesWrittenExclNull};var _glGetProgramInfoLog=_emscripten_glGetProgramInfoLog;var _emscripten_glGetProgramiv=(program,pname,p)=>{if(!p){GL.recordError(1281);return}if(program>=GL.counter){GL.recordError(1281);return}program=GL.programs[program];if(pname==35716){var log=GLctx.getProgramInfoLog(program);if(log===null)log="(unknown error)";HEAP32[p>>2]=log.length+1}else if(pname==35719){if(!program.maxUniformLength){var numActiveUniforms=GLctx.getProgramParameter(program,35718);for(var i=0;i<numActiveUniforms;++i){program.maxUniformLength=Math.max(program.maxUniformLength,GLctx.getActiveUniform(program,i).name.length+1)}}HEAP32[p>>2]=program.maxUniformLength}else if(pname==35722){if(!program.maxAttributeLength){var numActiveAttributes=GLctx.getProgramParameter(program,35721);for(var i=0;i<numActiveAttributes;++i){program.maxAttributeLength=Math.max(program.maxAttributeLength,GLctx.getActiveAttrib(program,i).name.length+1)}}HEAP32[p>>2]=program.maxAttributeLength}else if(pname==35381){if(!program.maxUniformBlockNameLength){var numActiveUniformBlocks=GLctx.getProgramParameter(program,35382);for(var i=0;i<numActiveUniformBlocks;++i){program.maxUniformBlockNameLength=Math.max(program.maxUniformBlockNameLength,GLctx.getActiveUniformBlockName(program,i).length+1)}}HEAP32[p>>2]=program.maxUniformBlockNameLength}else{HEAP32[p>>2]=GLctx.getProgramParameter(program,pname)}};var _glGetProgramiv=_emscripten_glGetProgramiv;var _emscripten_glGetShaderInfoLog=(shader,maxLength,length,infoLog)=>{var log=GLctx.getShaderInfoLog(GL.shaders[shader]);if(log===null)log="(unknown error)";var numBytesWrittenExclNull=maxLength>0&&infoLog?stringToUTF8(log,infoLog,maxLength):0;if(length)HEAP32[length>>2]=numBytesWrittenExclNull};var _glGetShaderInfoLog=_emscripten_glGetShaderInfoLog;var _emscripten_glGetShaderiv=(shader,pname,p)=>{if(!p){GL.recordError(1281);return}if(pname==35716){var log=GLctx.getShaderInfoLog(GL.shaders[shader]);if(log===null)log="(unknown error)";var logLength=log?log.length+1:0;HEAP32[p>>2]=logLength}else if(pname==35720){var source=GLctx.getShaderSource(GL.shaders[shader]);var sourceLength=source?source.length+1:0;HEAP32[p>>2]=sourceLength}else{HEAP32[p>>2]=GLctx.getShaderParameter(GL.shaders[shader],pname)}};var _glGetShaderiv=_emscripten_glGetShaderiv;var stringToNewUTF8=str=>{var size=lengthBytesUTF8(str)+1;var ret=_malloc(size);if(ret)stringToUTF8(str,ret,size);return ret};var _emscripten_glGetString=name_=>{var ret=GL.stringCache[name_];if(!ret){switch(name_){case 7939:ret=stringToNewUTF8(webglGetExtensions().join(" "));break;case 7936:case 7937:case 37445:case 37446:var s=GLctx.getParameter(name_);if(!s){GL.recordError(1280)}ret=s?stringToNewUTF8(s):0;break;case 7938:var webGLVersion=GLctx.getParameter(7938);var glVersion=`OpenGL ES 2.0 (${webGLVersion})`;if(GL.currentContext.version>=2)glVersion=`OpenGL ES 3.0 (${webGLVersion})`;ret=stringToNewUTF8(glVersion);break;case 35724:var glslVersion=GLctx.getParameter(35724);var ver_re=/^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/;var ver_num=glslVersion.match(ver_re);if(ver_num!==null){if(ver_num[1].length==3)ver_num[1]=ver_num[1]+"0";glslVersion=`OpenGL ES GLSL ES ${ver_num[1]} (${glslVersion})`}ret=stringToNewUTF8(glslVersion);break;default:GL.recordError(1280)}GL.stringCache[name_]=ret}return ret};var _glGetString=_emscripten_glGetString;var jstoi_q=str=>parseInt(str);var webglGetLeftBracePos=name=>name.slice(-1)=="]"&&name.lastIndexOf("[");var webglPrepareUniformLocationsBeforeFirstUse=program=>{var uniformLocsById=program.uniformLocsById,uniformSizeAndIdsByName=program.uniformSizeAndIdsByName,i,j;if(!uniformLocsById){program.uniformLocsById=uniformLocsById={};program.uniformArrayNamesById={};var numActiveUniforms=GLctx.getProgramParameter(program,35718);for(i=0;i<numActiveUniforms;++i){var u=GLctx.getActiveUniform(program,i);var nm=u.name;var sz=u.size;var lb=webglGetLeftBracePos(nm);var arrayName=lb>0?nm.slice(0,lb):nm;var id=program.uniformIdCounter;program.uniformIdCounter+=sz;uniformSizeAndIdsByName[arrayName]=[sz,id];for(j=0;j<sz;++j){uniformLocsById[id]=j;program.uniformArrayNamesById[id++]=arrayName}}}};var _emscripten_glGetUniformLocation=(program,name)=>{name=UTF8ToString(name);if(program=GL.programs[program]){webglPrepareUniformLocationsBeforeFirstUse(program);var uniformLocsById=program.uniformLocsById;var arrayIndex=0;var uniformBaseName=name;var leftBrace=webglGetLeftBracePos(name);if(leftBrace>0){arrayIndex=jstoi_q(name.slice(leftBrace+1))>>>0;uniformBaseName=name.slice(0,leftBrace)}var sizeAndId=program.uniformSizeAndIdsByName[uniformBaseName];if(sizeAndId&&arrayIndex<sizeAndId[0]){arrayIndex+=sizeAndId[1];if(uniformLocsById[arrayIndex]=uniformLocsById[arrayIndex]||GLctx.getUniformLocation(program,name)){return arrayIndex}}}else{GL.recordError(1281)}return-1};var _glGetUniformLocation=_emscripten_glGetUniformLocation;var _emscripten_glLinkProgram=program=>{program=GL.programs[program];GLctx.linkProgram(program);program.uniformLocsById=0;program.uniformSizeAndIdsByName={}};var _glLinkProgram=_emscripten_glLinkProgram;var _emscripten_glPixelStorei=(pname,param)=>{if(pname==3317){GL.unpackAlignment=param}else if(pname==3314){GL.unpackRowLength=param}GLctx.pixelStorei(pname,param)};var _glPixelStorei=_emscripten_glPixelStorei;var _emscripten_glScissor=(x0,x1,x2,x3)=>GLctx.scissor(x0,x1,x2,x3);var _glScissor=_emscripten_glScissor;var _emscripten_glShaderSource=(shader,count,string,length)=>{var source=GL.getSource(shader,count,string,length);GLctx.shaderSource(GL.shaders[shader],source)};var _glShaderSource=_emscripten_glShaderSource;var _emscripten_glStencilFunc=(x0,x1,x2)=>GLctx.stencilFunc(x0,x1,x2);var _glStencilFunc=_emscripten_glStencilFunc;var _emscripten_glStencilMask=x0=>GLctx.stencilMask(x0);var _glStencilMask=_emscripten_glStencilMask;var _emscripten_glStencilOp=(x0,x1,x2)=>GLctx.stencilOp(x0,x1,x2);var _glStencilOp=_emscripten_glStencilOp;var computeUnpackAlignedImageSize=(width,height,sizePerPixel)=>{function roundedToNextMultipleOf(x,y){return x+y-1&-y}var plainRowSize=(GL.unpackRowLength||width)*sizePerPixel;var alignedRowSize=roundedToNextMultipleOf(plainRowSize,GL.unpackAlignment);return height*alignedRowSize};var colorChannelsInGlTextureFormat=format=>{var colorChannels={5:3,6:4,8:2,29502:3,29504:4,26917:2,26918:2,29846:3,29847:4};return colorChannels[format-6402]||1};var heapObjectForWebGLType=type=>{type-=5120;if(type==0)return HEAP8;if(type==1)return HEAPU8;if(type==2)return HEAP16;if(type==4)return HEAP32;if(type==6)return HEAPF32;if(type==5||type==28922||type==28520||type==30779||type==30782)return HEAPU32;return HEAPU16};var toTypedArrayIndex=(pointer,heap)=>pointer>>>31-Math.clz32(heap.BYTES_PER_ELEMENT);var emscriptenWebGLGetTexPixelData=(type,format,width,height,pixels,internalFormat)=>{var heap=heapObjectForWebGLType(type);var sizePerPixel=colorChannelsInGlTextureFormat(format)*heap.BYTES_PER_ELEMENT;var bytes=computeUnpackAlignedImageSize(width,height,sizePerPixel);return heap.subarray(toTypedArrayIndex(pixels,heap),toTypedArrayIndex(pixels+bytes,heap))};var _emscripten_glTexImage2D=(target,level,internalFormat,width,height,border,format,type,pixels)=>{if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding){GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,pixels);return}if(pixels){var heap=heapObjectForWebGLType(type);var index=toTypedArrayIndex(pixels,heap);GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,heap,index);return}}var pixelData=pixels?emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,internalFormat):null;GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,pixelData)};var _glTexImage2D=_emscripten_glTexImage2D;var _emscripten_glTexParameteri=(x0,x1,x2)=>GLctx.texParameteri(x0,x1,x2);var _glTexParameteri=_emscripten_glTexParameteri;var _emscripten_glTexSubImage2D=(target,level,xoffset,yoffset,width,height,format,type,pixels)=>{if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding){GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixels);return}if(pixels){var heap=heapObjectForWebGLType(type);GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,heap,toTypedArrayIndex(pixels,heap));return}}var pixelData=pixels?emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,0):null;GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixelData)};var _glTexSubImage2D=_emscripten_glTexSubImage2D;var webglGetUniformLocation=location=>{var p=GLctx.currentProgram;if(p){var webglLoc=p.uniformLocsById[location];if(typeof webglLoc=="number"){p.uniformLocsById[location]=webglLoc=GLctx.getUniformLocation(p,p.uniformArrayNamesById[location]+(webglLoc>0?`[${webglLoc}]`:""))}return webglLoc}else{GL.recordError(1282)}};var _emscripten_glUniform1f=(location,v0)=>{GLctx.uniform1f(webglGetUniformLocation(location),v0)};var _glUniform1f=_emscripten_glUniform1f;var _emscripten_glUniform1i=(location,v0)=>{GLctx.uniform1i(webglGetUniformLocation(location),v0)};var _glUniform1i=_emscripten_glUniform1i;var _emscripten_glUniform2f=(location,v0,v1)=>{GLctx.uniform2f(webglGetUniformLocation(location),v0,v1)};var _glUniform2f=_emscripten_glUniform2f;var _emscripten_glUniform3f=(location,v0,v1,v2)=>{GLctx.uniform3f(webglGetUniformLocation(location),v0,v1,v2)};var _glUniform3f=_emscripten_glUniform3f;var _emscripten_glUniform4f=(location,v0,v1,v2,v3)=>{GLctx.uniform4f(webglGetUniformLocation(location),v0,v1,v2,v3)};var _glUniform4f=_emscripten_glUniform4f;var miniTempWebGLFloatBuffers=[];var _emscripten_glUniformMatrix4fv=(location,count,transpose,value)=>{if(GL.currentContext.version>=2){count&&GLctx.uniformMatrix4fv(webglGetUniformLocation(location),!!transpose,HEAPF32,value>>2,count*16);return}if(count<=18){var view=miniTempWebGLFloatBuffers[16*count];var heap=HEAPF32;value=value>>2;count*=16;for(var i=0;i<count;i+=16){var dst=value+i;view[i]=heap[dst];view[i+1]=heap[dst+1];view[i+2]=heap[dst+2];view[i+3]=heap[dst+3];view[i+4]=heap[dst+4];view[i+5]=heap[dst+5];view[i+6]=heap[dst+6];view[i+7]=heap[dst+7];view[i+8]=heap[dst+8];view[i+9]=heap[dst+9];view[i+10]=heap[dst+10];view[i+11]=heap[dst+11];view[i+12]=heap[dst+12];view[i+13]=heap[dst+13];view[i+14]=heap[dst+14];view[i+15]=heap[dst+15]}}else{var view=HEAPF32.subarray(value>>2,value+count*64>>2)}GLctx.uniformMatrix4fv(webglGetUniformLocation(location),!!transpose,view)};var _glUniformMatrix4fv=_emscripten_glUniformMatrix4fv;var _emscripten_glUseProgram=program=>{program=GL.programs[program];GLctx.useProgram(program);GLctx.currentProgram=program};var _glUseProgram=_emscripten_glUseProgram;var _emscripten_glVertexAttribPointer=(index,size,type,normalized,stride,ptr)=>{var cb=GL.currentContext.clientBuffers[index];if(!GLctx.currentArrayBufferBinding){cb.size=size;cb.type=type;cb.normalized=normalized;cb.stride=stride;cb.ptr=ptr;cb.clientside=true;cb.vertexAttribPointerAdaptor=function(index,size,type,normalized,stride,ptr){this.vertexAttribPointer(index,size,type,normalized,stride,ptr)};return}cb.clientside=false;GLctx.vertexAttribPointer(index,size,type,!!normalized,stride,ptr)};var _glVertexAttribPointer=_emscripten_glVertexAttribPointer;var _emscripten_glViewport=(x0,x1,x2,x3)=>GLctx.viewport(x0,x1,x2,x3);var _glViewport=_emscripten_glViewport;var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func(...cArgs);function onDone(ret){if(stack!==0)stackRestore(stack);return convertReturnValue(ret)}ret=onDone(ret);return ret};var cwrap=(ident,returnType,argTypes,opts)=>{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};var FS_createPath=(...args)=>FS.createPath(...args);var FS_unlink=(...args)=>FS.unlink(...args);var FS_createLazyFile=(...args)=>FS.createLazyFile(...args);var FS_createDevice=(...args)=>FS.createDevice(...args);FS.createPreloadedFile=FS_createPreloadedFile;FS.preloadFile=FS_preloadFile;FS.staticInit();init_ClassHandle();init_RegisteredPointer();registerPreMainLoop(()=>GL.newRenderingFrameStarted());var miniTempWebGLFloatBuffersStorage=new Float32Array(288);for(var i=0;i<=288;++i){miniTempWebGLFloatBuffers[i]=miniTempWebGLFloatBuffersStorage.subarray(0,i)}{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["preloadPlugins"])preloadPlugins=Module["preloadPlugins"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["addRunDependency"]=addRunDependency;Module["removeRunDependency"]=removeRunDependency;Module["ccall"]=ccall;Module["cwrap"]=cwrap;Module["FS_preloadFile"]=FS_preloadFile;Module["FS_unlink"]=FS_unlink;Module["FS_createPath"]=FS_createPath;Module["FS_createDevice"]=FS_createDevice;Module["FS"]=FS;Module["FS_createDataFile"]=FS_createDataFile;Module["FS_createLazyFile"]=FS_createLazyFile;Module["GL"]=GL;function callMaterialProvider(materialId,outShaderIdPtr,outBlendModePtr,outUniformBufPtr,outUniformCountPtr){var fn=Module["materialDataProvider"];if(fn){fn(materialId,outShaderIdPtr,outBlendModePtr,outUniformBufPtr,outUniformCountPtr)}else{HEAPU32[outShaderIdPtr>>2]=0;HEAPU32[outBlendModePtr>>2]=0;HEAPU32[outUniformBufPtr>>2]=0;HEAPU32[outUniformCountPtr>>2]=0}}var ___getTypeName,_malloc,_free,__emscripten_timeout,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,memory,__indirect_function_table,wasmMemory,wasmTable;function assignWasmExports(wasmExports){___getTypeName=wasmExports["gb"];_malloc=Module["_malloc"]=wasmExports["hb"];_free=Module["_free"]=wasmExports["ib"];__emscripten_timeout=wasmExports["jb"];__emscripten_stack_restore=wasmExports["lb"];__emscripten_stack_alloc=wasmExports["mb"];_emscripten_stack_get_current=wasmExports["nb"];memory=wasmMemory=wasmExports["eb"];__indirect_function_table=wasmTable=wasmExports["kb"]}var wasmImports={Aa:___syscall_fcntl64,ab:___syscall_ioctl,bb:___syscall_openat,Ea:__abort_js,h:__embind_finalize_value_object,xa:__embind_register_bigint,Sa:__embind_register_bool,ca:__embind_register_class,ta:__embind_register_class_constructor,b:__embind_register_class_function,Qa:__embind_register_emval,E:__embind_register_enum,f:__embind_register_enum_value,wa:__embind_register_float,c:__embind_register_function,G:__embind_register_integer,Ma:__embind_register_iterable,l:__embind_register_memory_view,Na:__embind_register_optional,Ra:__embind_register_std_string,ha:__embind_register_std_wstring,g:__embind_register_value_object,a:__embind_register_value_object_field,Ta:__embind_register_void,Va:__emscripten_runtime_keepalive_clear,N:__emval_create_invoker,C:__emval_decref,M:__emval_invoke,ua:__emval_new_array,X:__emval_new_cstring,va:__emval_new_object,L:__emval_run_destructors,Q:__emval_set_property,Wa:__setitimer_js,Xa:__tzset_js,db:callMaterialProvider,Ba:_clock_time_get,Ca:_emscripten_resize_heap,cb:_emscripten_webgl_create_context,Pa:_emscripten_webgl_destroy_context,ya:_emscripten_webgl_make_context_current,Ya:_environ_get,Za:_environ_sizes_get,za:_fd_close,$a:_fd_read,_a:_fd_seek,Da:_fd_write,u:_glActiveTexture,na:_glAttachShader,Ka:_glBindAttribLocation,d:_glBindBuffer,z:_glBindFramebuffer,m:_glBindTexture,j:_glBindVertexArray,da:_glBlendFunc,y:_glBlendFuncSeparate,o:_glBufferData,A:_glBufferSubData,Fa:_glCheckFramebufferStatus,J:_glClear,ga:_glClearColor,Oa:_glClearStencil,O:_glColorMask,pa:_glCompileShader,La:_glCreateProgram,ra:_glCreateShader,p:_glDeleteBuffers,s:_glDeleteFramebuffers,sa:_glDeleteProgram,I:_glDeleteShader,e:_glDeleteTextures,R:_glDeleteVertexArrays,n:_glDisable,V:_glDrawArrays,F:_glDrawElements,r:_glEnable,x:_glEnableVertexAttribArray,ia:_glFramebufferTexture2D,t:_glGenBuffers,Ga:_glGenFramebuffers,U:_glGenTextures,H:_glGenVertexArrays,Ha:_glGenerateMipmap,_:_glGetAttribLocation,P:_glGetError,ea:_glGetIntegerv,Ia:_glGetProgramInfoLog,ma:_glGetProgramiv,oa:_glGetShaderInfoLog,S:_glGetShaderiv,W:_glGetString,i:_glGetUniformLocation,Ja:_glLinkProgram,ka:_glPixelStorei,fa:_glScissor,qa:_glShaderSource,Z:_glStencilFunc,v:_glStencilMask,Y:_glStencilOp,T:_glTexImage2D,q:_glTexParameteri,ja:_glTexSubImage2D,ba:_glUniform1f,k:_glUniform1i,aa:_glUniform2f,la:_glUniform3f,$:_glUniform4f,D:_glUniformMatrix4fv,B:_glUseProgram,w:_glVertexAttribPointer,K:_glViewport,Ua:_proc_exit};function run(){if(runDependencies>0){dependenciesFulfilled=run;return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=await (createWasm());run();if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})}+var ESEngineModule=(()=>{var _scriptName=globalThis.document?.currentScript?.src;return async function(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_WEB=true;var ENVIRONMENT_IS_WORKER=false;var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{readAsync=async url=>{var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var EXITSTATUS;var readyPromiseResolve,readyPromiseReject;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var HEAP64,HEAPU64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.initialized)FS.init();TTY.init();wasmExports["fb"]();FS.ignorePermissions=false}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject?.(e);throw e}var wasmBinaryFile;function findWasmBinary(){return locateFile("esengine.wxgame.wasm")}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);var noExitRuntime=true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();var syscallGetVarargI=()=>{var ret=HEAP32[+SYSCALLS.varargs>>2];SYSCALLS.varargs+=4;return ret};var syscallGetVarargP=syscallGetVarargI;var PATH={isAbs:path=>path.charAt(0)==="/",splitPath:filename=>{var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:(parts,allowAboveRoot)=>{var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:path=>{var isAbsolute=PATH.isAbs(path),trailingSlash=path.slice(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(p=>!!p),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:path=>{var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.slice(0,-1)}return root+dir},basename:path=>path&&path.match(/([^\/]+|\/)\/*$/)[1],join:(...paths)=>PATH.normalize(paths.join("/")),join2:(l,r)=>PATH.normalize(l+"/"+r)};var initRandomFill=()=>view=>crypto.getRandomValues(view);var randomFill=view=>{(randomFill=initRandomFill())(view)};var PATH_FS={resolve:(...args)=>{var resolvedPath="",resolvedAbsolute=false;for(var i=args.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?args[i]:FS.cwd();if(typeof path!="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=PATH.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).slice(1);to=PATH_FS.resolve(to).slice(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")}};var UTF8Decoder=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var FS_stdin_getChar_buffer=[];var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.codePointAt(i);if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63;i++}}heap[outIdx]=0;return outIdx-startIdx};var intArrayFromString=(stringy,dontAddNull,length)=>{var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array};var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var result=null;if(globalThis.window?.prompt){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else{}if(!result){return null}FS_stdin_getChar_buffer=intArrayFromString(result,true)}return FS_stdin_getChar_buffer.shift()};var TTY={ttys:[],init(){},shutdown(){},register(dev,ops){TTY.ttys[dev]={input:[],output:[],ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close(stream){stream.tty.ops.fsync(stream.tty)},fsync(stream){stream.tty.ops.fsync(stream.tty)},read(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=stream.tty.ops.get_char(stream.tty)}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.put_char){throw new FS.ErrnoError(60)}try{for(var i=0;i<length;i++){stream.tty.ops.put_char(stream.tty,buffer[offset+i])}}catch(e){throw new FS.ErrnoError(29)}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}},default_tty_ops:{get_char(tty){return FS_stdin_getChar()},put_char(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){out(UTF8ArrayToString(tty.output));tty.output=[]}},ioctl_tcgets(tty){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(tty,optional_actions,data){return 0},ioctl_tiocgwinsz(tty){return[24,80]}},default_tty1_ops:{put_char(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){err(UTF8ArrayToString(tty.output));tty.output=[]}}}};var mmapAlloc=size=>{abort()};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",16895,0)},createNode(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}MEMFS.ops_table||={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}};var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=null}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.atime=node.mtime=node.ctime=Date.now();if(parent){parent.contents[name]=node;parent.atime=parent.mtime=parent.ctime=node.atime}return node},getFileDataAsTypedArray(node){if(!node.contents)return new Uint8Array(0);if(node.contents.subarray)return node.contents.subarray(0,node.usedBytes);return new Uint8Array(node.contents)},expandFileStorage(node,newCapacity){var prevCapacity=node.contents?node.contents.length:0;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity<CAPACITY_DOUBLING_MAX?2:1.125)>>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.atime);attr.mtime=new Date(node.mtime);attr.ctime=new Date(node.ctime);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr(node,attr){for(const key of["mode","atime","mtime","ctime"]){if(attr[key]!=null){node[key]=attr[key]}}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup(parent,name){if(!MEMFS.doesNotExistError){MEMFS.doesNotExistError=new FS.ErrnoError(44);MEMFS.doesNotExistError.stack="<generic error, no stack>"}throw MEMFS.doesNotExistError},mknod(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename(old_node,new_dir,new_name){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){if(FS.isDir(old_node.mode)){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}FS.hashRemoveNode(new_node)}delete old_node.parent.contents[old_node.name];new_dir.contents[new_name]=old_node;old_node.name=new_name;new_dir.ctime=new_dir.mtime=old_node.parent.ctime=old_node.parent.mtime=Date.now()},unlink(parent,name){delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},rmdir(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},readdir(node){return[".","..",...Object.keys(node.contents)]},symlink(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i<size;i++)buffer[offset+i]=contents[position+i]}return size},write(stream,buffer,offset,length,position,canOwn){if(buffer.buffer===HEAP8.buffer){canOwn=false}if(!length)return 0;var node=stream.node;node.mtime=node.ctime=Date.now();if(buffer.subarray&&(!node.contents||node.contents.subarray)){if(canOwn){node.contents=buffer.subarray(offset,offset+length);node.usedBytes=length;return length}else if(node.usedBytes===0&&position===0){node.contents=buffer.slice(offset,offset+length);node.usedBytes=length;return length}else if(position+length<=node.usedBytes){node.contents.set(buffer.subarray(offset,offset+length),position);return length}}MEMFS.expandFileStorage(node,position+length);if(node.contents.subarray&&buffer.subarray){node.contents.set(buffer.subarray(offset,offset+length),position)}else{for(var i=0;i<length;i++){node.contents[position+i]=buffer[offset+i]}}node.usedBytes=Math.max(node.usedBytes,position+length);return length},llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(FS.isFile(stream.node.mode)){position+=stream.node.usedBytes}}if(position<0){throw new FS.ErrnoError(28)}return position},mmap(stream,length,position,prot,flags){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}var ptr;var allocated;var contents=stream.node.contents;if(!(flags&2)&&contents&&contents.buffer===HEAP8.buffer){allocated=false;ptr=contents.byteOffset}else{allocated=true;ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}if(contents){if(position>0||position+length<contents.length){if(contents.subarray){contents=contents.subarray(position,position+length)}else{contents=Array.prototype.slice.call(contents,position,position+length)}}HEAP8.set(contents,ptr)}}return{ptr,allocated}},msync(stream,buffer,offset,length,mmapFlags){MEMFS.stream_ops.write(stream,buffer,0,length,offset,false);return 0}}};var FS_modeStringToFlags=str=>{var flagModes={r:0,"r+":2,w:512|64|1,"w+":512|64|2,a:1024|64|1,"a+":1024|64|2};var flags=flagModes[str];if(typeof flags=="undefined"){throw new Error(`Unknown file open mode: ${str}`)}return flags};var FS_getMode=(canRead,canWrite)=>{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode};var asyncLoad=async url=>{var arrayBuffer=await readAsync(url);return new Uint8Array(arrayBuffer)};var FS_createDataFile=(...args)=>FS.createDataFile(...args);var getUniqueRunDependency=id=>id;var runDependencies=0;var dependenciesFulfilled=null;var removeRunDependency=id=>{runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}};var addRunDependency=id=>{runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)};var preloadPlugins=[];var FS_handledByPreloadPlugin=async(byteArray,fullname)=>{if(typeof Browser!="undefined")Browser.init();for(var plugin of preloadPlugins){if(plugin["canHandle"](fullname)){return plugin["handle"](byteArray,fullname)}}return byteArray};var FS_preloadFile=async(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency(`cp ${fullname}`);addRunDependency(dep);try{var byteArray=url;if(typeof url=="string"){byteArray=await asyncLoad(url)}byteArray=await FS_handledByPreloadPlugin(byteArray,fullname);preFinish?.();if(!dontCreateFile){FS_createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}}finally{removeRunDependency(dep)}};var FS_createPreloadedFile=(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{FS_preloadFile(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish).then(onload).catch(onerror)};var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,filesystems:null,syncFSRequests:0,readFiles:{},ErrnoError:class{name="ErrnoError";constructor(errno){this.errno=errno}},FSStream:class{shared={};get object(){return this.node}set object(val){this.node=val}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(val){this.shared.flags=val}get position(){return this.shared.position}set position(val){this.shared.position=val}},FSNode:class{node_ops={};stream_ops={};readMode=292|73;writeMode=146;mounted=null;constructor(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.rdev=rdev;this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(val){val?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(val){val?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return FS.isDir(this.mode)}get isDevice(){return FS.isChrdev(this.mode)}},lookupPath(path,opts={}){if(!path){throw new FS.ErrnoError(44)}opts.follow_mount??=true;if(!PATH.isAbs(path)){path=FS.cwd()+"/"+path}linkloop:for(var nlinks=0;nlinks<40;nlinks++){var parts=path.split("/").filter(p=>!!p);var current=FS.root;var current_path="/";for(var i=0;i<parts.length;i++){var islast=i===parts.length-1;if(islast&&opts.parent){break}if(parts[i]==="."){continue}if(parts[i]===".."){current_path=PATH.dirname(current_path);if(FS.isRoot(current)){path=current_path+"/"+parts.slice(i+1).join("/");nlinks--;continue linkloop}else{current=current.parent}continue}current_path=PATH.join2(current_path,parts[i]);try{current=FS.lookupNode(current,parts[i])}catch(e){if(e?.errno===44&&islast&&opts.noent_okay){return{path:current_path}}throw e}if(FS.isMountpoint(current)&&(!islast||opts.follow_mount)){current=current.mounted.root}if(FS.isLink(current.mode)&&(!islast||opts.follow)){if(!current.node_ops.readlink){throw new FS.ErrnoError(52)}var link=current.node_ops.readlink(current);if(!PATH.isAbs(link)){link=PATH.dirname(current_path)+"/"+link}path=link+"/"+parts.slice(i+1).join("/");continue linkloop}}return{path:current_path,node:current}}throw new FS.ErrnoError(32)},getPath(node){var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?`${mount}/${path}`:mount+path}path=path?`${node.name}/${path}`:node.name;node=node.parent}},hashName(parentid,name){var hash=0;for(var i=0;i<name.length;i++){hash=(hash<<5)-hash+name.charCodeAt(i)|0}return(parentid+hash>>>0)%FS.nameTable.length},hashAddNode(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode(node){FS.hashRemoveNode(node)},isRoot(node){return node===node.parent},isMountpoint(node){return!!node.mounted},isFile(mode){return(mode&61440)===32768},isDir(mode){return(mode&61440)===16384},isLink(mode){return(mode&61440)===40960},isChrdev(mode){return(mode&61440)===8192},isBlkdev(mode){return(mode&61440)===24576},isFIFO(mode){return(mode&61440)===4096},isSocket(mode){return(mode&49152)===49152},flagsToPermissionString(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}else if(perms.includes("w")&&!(node.mode&146)){return 2}else if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup(dir){if(!FS.isDir(dir.mode))return 54;var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate(dir,name){if(!FS.isDir(dir.mode)){return 54}try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else{if(FS.isDir(node.mode)){return 31}}return 0},mayOpen(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}else if(FS.isDir(node.mode)){if(FS.flagsToPermissionString(flags)!=="r"||flags&(512|64)){return 31}}return FS.nodePermissions(node,FS.flagsToPermissionString(flags))},checkOpExists(op,err){if(!op){throw new FS.ErrnoError(err)}return op},MAX_OPEN_FDS:4096,nextfd(){for(var fd=0;fd<=FS.MAX_OPEN_FDS;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStreamChecked(fd){var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}return stream},getStream:fd=>FS.streams[fd],createStream(stream,fd=-1){stream=Object.assign(new FS.FSStream,stream);if(fd==-1){fd=FS.nextfd()}stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream(fd){FS.streams[fd]=null},dupStream(origStream,fd=-1){var stream=FS.createStream(origStream,fd);stream.stream_ops?.dup?.(stream);return stream},doSetAttr(stream,node,attr){var setattr=stream?.stream_ops.setattr;var arg=setattr?stream:node;setattr??=node.node_ops.setattr;FS.checkOpExists(setattr,63);setattr(arg,attr)},chrdev_stream_ops:{open(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;stream.stream_ops.open?.(stream)},llseek(){throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push(...m.mounts)}return mounts},syncfs(populate,callback){if(typeof populate=="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`)}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}for(var mount of mounts){if(mount.type.syncfs){mount.type.syncfs(mount,populate,done)}else{done(null)}}},mount(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type,opts,mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);for(var[hash,current]of Object.entries(FS.nameTable)){while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}}node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup(parent,name){return parent.node_ops.lookup(parent,name)},mknod(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name){throw new FS.ErrnoError(28)}if(name==="."||name===".."){throw new FS.ErrnoError(20)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},statfs(path){return FS.statfsNode(FS.lookupPath(path,{follow:true}).node)},statfsStream(stream){return FS.statfsNode(stream.node)},statfsNode(node){var rtn={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:FS.nextInode,ffree:FS.nextInode-1,fsid:42,flags:2,namelen:255};if(node.node_ops.statfs){Object.assign(rtn,node.node_ops.statfs(node.mount.opts.root))}return rtn},create(path,mode=438){mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir(path,mode=511){mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree(path,mode){var dirs=path.split("/");var d="";for(var dir of dirs){if(!dir)continue;if(d||PATH.isAbs(path))d+="/";d+=dir;try{FS.mkdir(d,mode)}catch(e){if(e.errno!=20)throw e}}},mkdev(path,mode,dev){if(typeof dev=="undefined"){dev=mode;mode=438}mode|=8192;return FS.mknod(path,mode,dev)},symlink(oldpath,newpath){if(!PATH_FS.resolve(oldpath)){throw new FS.ErrnoError(44)}var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.symlink){throw new FS.ErrnoError(63)}return parent.node_ops.symlink(parent,newname,oldpath)},rename(old_path,new_path){var old_dirname=PATH.dirname(old_path);var new_dirname=PATH.dirname(new_path);var old_name=PATH.basename(old_path);var new_name=PATH.basename(new_path);var lookup,old_dir,new_dir;lookup=FS.lookupPath(old_path,{parent:true});old_dir=lookup.node;lookup=FS.lookupPath(new_path,{parent:true});new_dir=lookup.node;if(!old_dir||!new_dir)throw new FS.ErrnoError(44);if(old_dir.mount!==new_dir.mount){throw new FS.ErrnoError(75)}var old_node=FS.lookupNode(old_dir,old_name);var relative=PATH_FS.relative(old_path,new_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(28)}relative=PATH_FS.relative(new_path,old_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(55)}var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(old_node===new_node){return}var isdir=FS.isDir(old_node.mode);var errCode=FS.mayDelete(old_dir,old_name,isdir);if(errCode){throw new FS.ErrnoError(errCode)}errCode=new_node?FS.mayDelete(new_dir,new_name,isdir):FS.mayCreate(new_dir,new_name);if(errCode){throw new FS.ErrnoError(errCode)}if(!old_dir.node_ops.rename){throw new FS.ErrnoError(63)}if(FS.isMountpoint(old_node)||new_node&&FS.isMountpoint(new_node)){throw new FS.ErrnoError(10)}if(new_dir!==old_dir){errCode=FS.nodePermissions(old_dir,"w");if(errCode){throw new FS.ErrnoError(errCode)}}FS.hashRemoveNode(old_node);try{old_dir.node_ops.rename(old_node,new_dir,new_name);old_node.parent=new_dir}catch(e){throw e}finally{FS.hashAddNode(old_node)}},rmdir(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,true);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.rmdir){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.rmdir(parent,name);FS.destroyNode(node)},readdir(path){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var readdir=FS.checkOpExists(node.node_ops.readdir,54);return readdir(node)},unlink(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,false);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.unlink){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.unlink(parent,name);FS.destroyNode(node)},readlink(path){var lookup=FS.lookupPath(path);var link=lookup.node;if(!link){throw new FS.ErrnoError(44)}if(!link.node_ops.readlink){throw new FS.ErrnoError(28)}return link.node_ops.readlink(link)},stat(path,dontFollow){var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;var getattr=FS.checkOpExists(node.node_ops.getattr,63);return getattr(node)},fstat(fd){var stream=FS.getStreamChecked(fd);var node=stream.node;var getattr=stream.stream_ops.getattr;var arg=getattr?stream:node;getattr??=node.node_ops.getattr;FS.checkOpExists(getattr,63);return getattr(arg)},lstat(path){return FS.stat(path,true)},doChmod(stream,node,mode,dontFollow){FS.doSetAttr(stream,node,{mode:mode&4095|node.mode&~4095,ctime:Date.now(),dontFollow})},chmod(path,mode,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChmod(null,node,mode,dontFollow)},lchmod(path,mode){FS.chmod(path,mode,true)},fchmod(fd,mode){var stream=FS.getStreamChecked(fd);FS.doChmod(stream,stream.node,mode,false)},doChown(stream,node,dontFollow){FS.doSetAttr(stream,node,{timestamp:Date.now(),dontFollow})},chown(path,uid,gid,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChown(null,node,dontFollow)},lchown(path,uid,gid){FS.chown(path,uid,gid,true)},fchown(fd,uid,gid){var stream=FS.getStreamChecked(fd);FS.doChown(stream,stream.node,false)},doTruncate(stream,node,len){if(FS.isDir(node.mode)){throw new FS.ErrnoError(31)}if(!FS.isFile(node.mode)){throw new FS.ErrnoError(28)}var errCode=FS.nodePermissions(node,"w");if(errCode){throw new FS.ErrnoError(errCode)}FS.doSetAttr(stream,node,{size:len,timestamp:Date.now()})},truncate(path,len){if(len<0){throw new FS.ErrnoError(28)}var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:true});node=lookup.node}else{node=path}FS.doTruncate(null,node,len)},ftruncate(fd,len){var stream=FS.getStreamChecked(fd);if(len<0||(stream.flags&2097155)===0){throw new FS.ErrnoError(28)}FS.doTruncate(stream,stream.node,len)},utime(path,atime,mtime){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var setattr=FS.checkOpExists(node.node_ops.setattr,63);setattr(node,{atime,mtime})},open(path,flags,mode=438){if(path===""){throw new FS.ErrnoError(44)}flags=typeof flags=="string"?FS_modeStringToFlags(flags):flags;if(flags&64){mode=mode&4095|32768}else{mode=0}var node;var isDirPath;if(typeof path=="object"){node=path}else{isDirPath=path.endsWith("/");var lookup=FS.lookupPath(path,{follow:!(flags&131072),noent_okay:true});node=lookup.node;path=lookup.path}var created=false;if(flags&64){if(node){if(flags&128){throw new FS.ErrnoError(20)}}else if(isDirPath){throw new FS.ErrnoError(31)}else{node=FS.mknod(path,mode|511,0);created=true}}if(!node){throw new FS.ErrnoError(44)}if(FS.isChrdev(node.mode)){flags&=~512}if(flags&65536&&!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}if(!created){var errCode=FS.mayOpen(node,flags);if(errCode){throw new FS.ErrnoError(errCode)}}if(flags&512&&!created){FS.truncate(node,0)}flags&=~(128|512|131072);var stream=FS.createStream({node,path:FS.getPath(node),flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(created){FS.chmod(node,mode&511)}if(Module["logReadFiles"]&&!(flags&1)){if(!(path in FS.readFiles)){FS.readFiles[path]=1}}return stream},close(stream){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(stream.getdents)stream.getdents=null;try{if(stream.stream_ops.close){stream.stream_ops.close(stream)}}catch(e){throw e}finally{FS.closeStream(stream.fd)}stream.fd=null},isClosed(stream){return stream.fd===null},llseek(stream,offset,whence){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(!stream.seekable||!stream.stream_ops.llseek){throw new FS.ErrnoError(70)}if(whence!=0&&whence!=1&&whence!=2){throw new FS.ErrnoError(28)}stream.position=stream.stream_ops.llseek(stream,offset,whence);stream.ungotten=[];return stream.position},read(stream,buffer,offset,length,position){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.read){throw new FS.ErrnoError(28)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesRead=stream.stream_ops.read(stream,buffer,offset,length,position);if(!seeking)stream.position+=bytesRead;return bytesRead},write(stream,buffer,offset,length,position,canOwn){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.write){throw new FS.ErrnoError(28)}if(stream.seekable&&stream.flags&1024){FS.llseek(stream,0,2)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesWritten=stream.stream_ops.write(stream,buffer,offset,length,position,canOwn);if(!seeking)stream.position+=bytesWritten;return bytesWritten},mmap(stream,length,position,prot,flags){if((prot&2)!==0&&(flags&2)===0&&(stream.flags&2097155)!==2){throw new FS.ErrnoError(2)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(2)}if(!stream.stream_ops.mmap){throw new FS.ErrnoError(43)}if(!length){throw new FS.ErrnoError(28)}return stream.stream_ops.mmap(stream,length,position,prot,flags)},msync(stream,buffer,offset,length,mmapFlags){if(!stream.stream_ops.msync){return 0}return stream.stream_ops.msync(stream,buffer,offset,length,mmapFlags)},ioctl(stream,cmd,arg){if(!stream.stream_ops.ioctl){throw new FS.ErrnoError(59)}return stream.stream_ops.ioctl(stream,cmd,arg)},readFile(path,opts={}){opts.flags=opts.flags||0;opts.encoding=opts.encoding||"binary";if(opts.encoding!=="utf8"&&opts.encoding!=="binary"){abort(`Invalid encoding type "${opts.encoding}"`)}var stream=FS.open(path,opts.flags);var stat=FS.stat(path);var length=stat.size;var buf=new Uint8Array(length);FS.read(stream,buf,0,length,0);if(opts.encoding==="utf8"){buf=UTF8ArrayToString(buf)}FS.close(stream);return buf},writeFile(path,data,opts={}){opts.flags=opts.flags||577;var stream=FS.open(path,opts.flags,opts.mode);if(typeof data=="string"){data=new Uint8Array(intArrayFromString(data,true))}if(ArrayBuffer.isView(data)){FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn)}else{abort("Unsupported data type")}FS.close(stream)},cwd:()=>FS.currentPath,chdir(path){var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null){throw new FS.ErrnoError(44)}if(!FS.isDir(lookup.node.mode)){throw new FS.ErrnoError(54)}var errCode=FS.nodePermissions(lookup.node,"x");if(errCode){throw new FS.ErrnoError(errCode)}FS.currentPath=lookup.path},createDefaultDirectories(){FS.mkdir("/tmp");FS.mkdir("/home");FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length,pos)=>length,llseek:()=>0});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var randomBuffer=new Uint8Array(1024),randomLeft=0;var randomByte=()=>{if(randomLeft===0){randomFill(randomBuffer);randomLeft=randomBuffer.byteLength}return randomBuffer[--randomLeft]};FS.createDevice("/dev","random",randomByte);FS.createDevice("/dev","urandom",randomByte);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount(){var node=FS.createNode(proc_self,"fd",16895,73);node.stream_ops={llseek:MEMFS.stream_ops.llseek};node.node_ops={lookup(parent,name){var fd=+name;var stream=FS.getStreamChecked(fd);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path},id:fd+1};ret.parent=ret;return ret},readdir(){return Array.from(FS.streams.entries()).filter(([k,v])=>v).map(([k,v])=>k.toString())}};return node}},{},"/proc/self/fd")},createStandardStreams(input,output,error){if(input){FS.createDevice("/dev","stdin",input)}else{FS.symlink("/dev/tty","/dev/stdin")}if(output){FS.createDevice("/dev","stdout",null,output)}else{FS.symlink("/dev/tty","/dev/stdout")}if(error){FS.createDevice("/dev","stderr",null,error)}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},staticInit(){FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={MEMFS}},init(input,output,error){FS.initialized=true;input??=Module["stdin"];output??=Module["stdout"];error??=Module["stderr"];FS.createStandardStreams(input,output,error)},quit(){FS.initialized=false;for(var stream of FS.streams){if(stream){FS.close(stream)}}},findObject(path,dontResolveLastLink){var ret=FS.analyzePath(path,dontResolveLastLink);if(!ret.exists){return null}return ret.object},analyzePath(path,dontResolveLastLink){try{var lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});path=lookup.path}catch(e){}var ret={isRoot:false,exists:false,error:0,name:null,path:null,object:null,parentExists:false,parentPath:null,parentObject:null};try{var lookup=FS.lookupPath(path,{parent:true});ret.parentExists=true;ret.parentPath=lookup.path;ret.parentObject=lookup.node;ret.name=PATH.basename(path);lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});ret.exists=true;ret.path=lookup.path;ret.object=lookup.node;ret.name=lookup.node.name;ret.isRoot=lookup.path==="/"}catch(e){ret.error=e.errno}return ret},createPath(parent,path,canRead,canWrite){parent=typeof parent=="string"?parent:FS.getPath(parent);var parts=path.split("/").reverse();while(parts.length){var part=parts.pop();if(!part)continue;var current=PATH.join2(parent,part);try{FS.mkdir(current)}catch(e){if(e.errno!=20)throw e}parent=current}return current},createFile(parent,name,properties,canRead,canWrite){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(canRead,canWrite);return FS.create(path,mode)},createDataFile(parent,name,data,canRead,canWrite,canOwn){var path=name;if(parent){parent=typeof parent=="string"?parent:FS.getPath(parent);path=name?PATH.join2(parent,name):parent}var mode=FS_getMode(canRead,canWrite);var node=FS.create(path,mode);if(data){if(typeof data=="string"){var arr=new Array(data.length);for(var i=0,len=data.length;i<len;++i)arr[i]=data.charCodeAt(i);data=arr}FS.chmod(node,mode|146);var stream=FS.open(node,577);FS.write(stream,data,0,data.length,0,canOwn);FS.close(stream);FS.chmod(node,mode)}},createDevice(parent,name,input,output){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(!!input,!!output);FS.createDevice.major??=64;var dev=FS.makedev(FS.createDevice.major++,0);FS.registerDevice(dev,{open(stream){stream.seekable=false},close(stream){if(output?.buffer?.length){output(10)}},read(stream,buffer,offset,length,pos){var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=input()}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){for(var i=0;i<length;i++){try{output(buffer[offset+i])}catch(e){throw new FS.ErrnoError(29)}}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}});return FS.mkdev(path,mode,dev)},forceLoadFile(obj){if(obj.isDevice||obj.isFolder||obj.link||obj.contents)return true;if(globalThis.XMLHttpRequest){abort("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.")}else{try{obj.contents=readBinary(obj.url)}catch(e){throw new FS.ErrnoError(29)}}},createLazyFile(parent,name,url,canRead,canWrite){class LazyUint8Array{lengthKnown=false;chunks=[];get(idx){if(idx>this.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]}setDataGetter(getter){this.getter=getter}cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)abort("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)abort("only "+datalength+" bytes available! programmer error!");var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}return intArrayFromString(xhr.responseText||"",true)};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]=="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]=="undefined")abort("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true}get length(){if(!this.lengthKnown){this.cacheLength()}return this._length}get chunkSize(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}if(globalThis.XMLHttpRequest){if(!ENVIRONMENT_IS_WORKER)abort("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var lazyArray=new LazyUint8Array;var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};for(const[key,fn]of Object.entries(node.stream_ops)){stream_ops[key]=(...args)=>{FS.forceLoadFile(node);return fn(...args)}}function writeChunks(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i<size;i++){buffer[offset+i]=contents[position+i]}}else{for(var i=0;i<size;i++){buffer[offset+i]=contents.get(position+i)}}return size}stream_ops.read=(stream,buffer,offset,length,position)=>{FS.forceLoadFile(node);return writeChunks(stream,buffer,offset,length,position)};stream_ops.mmap=(stream,length,position,prot,flags)=>{FS.forceLoadFile(node);var ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}writeChunks(stream,HEAP8,ptr,length,position);return{ptr,allocated:true}};node.stream_ops=stream_ops;return node}};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";var SYSCALLS={calculateAt(dirfd,path,allowEmpty){if(PATH.isAbs(path)){return path}var dir;if(dirfd===-100){dir=FS.cwd()}else{var dirstream=SYSCALLS.getStreamFromFD(dirfd);dir=dirstream.path}if(path.length==0){if(!allowEmpty){throw new FS.ErrnoError(44)}return dir}return dir+"/"+path},writeStat(buf,stat){HEAPU32[buf>>2]=stat.dev;HEAPU32[buf+4>>2]=stat.mode;HEAPU32[buf+8>>2]=stat.nlink;HEAPU32[buf+12>>2]=stat.uid;HEAPU32[buf+16>>2]=stat.gid;HEAPU32[buf+20>>2]=stat.rdev;HEAP64[buf+24>>3]=BigInt(stat.size);HEAP32[buf+32>>2]=4096;HEAP32[buf+36>>2]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();HEAP64[buf+40>>3]=BigInt(Math.floor(atime/1e3));HEAPU32[buf+48>>2]=atime%1e3*1e3*1e3;HEAP64[buf+56>>3]=BigInt(Math.floor(mtime/1e3));HEAPU32[buf+64>>2]=mtime%1e3*1e3*1e3;HEAP64[buf+72>>3]=BigInt(Math.floor(ctime/1e3));HEAPU32[buf+80>>2]=ctime%1e3*1e3*1e3;HEAP64[buf+88>>3]=BigInt(stat.ino);return 0},writeStatFs(buf,stats){HEAPU32[buf+4>>2]=stats.bsize;HEAPU32[buf+60>>2]=stats.bsize;HEAP64[buf+8>>3]=BigInt(stats.blocks);HEAP64[buf+16>>3]=BigInt(stats.bfree);HEAP64[buf+24>>3]=BigInt(stats.bavail);HEAP64[buf+32>>3]=BigInt(stats.files);HEAP64[buf+40>>3]=BigInt(stats.ffree);HEAPU32[buf+48>>2]=stats.fsid;HEAPU32[buf+64>>2]=stats.flags;HEAPU32[buf+56>>2]=stats.namelen},doMsync(addr,stream,len,flags,offset){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}if(flags&2){return 0}var buffer=HEAPU8.slice(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},getStreamFromFD(fd){var stream=FS.getStreamChecked(fd);return stream},varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=syscallGetVarargI();if(arg<0){return-28}while(FS.streams[arg]){arg++}var newStream;newStream=FS.dupStream(stream,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=syscallGetVarargI();stream.flags|=arg;return 0}case 12:{var arg=syscallGetVarargP();var offset=0;HEAP16[arg+offset>>1]=2;return 0}case 13:case 14:return 0}return-28}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:{if(!stream.tty)return-59;return 0}case 21505:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcgets){var termios=stream.tty.ops.ioctl_tcgets(stream);var argp=syscallGetVarargP();HEAP32[argp>>2]=termios.c_iflag||0;HEAP32[argp+4>>2]=termios.c_oflag||0;HEAP32[argp+8>>2]=termios.c_cflag||0;HEAP32[argp+12>>2]=termios.c_lflag||0;for(var i=0;i<32;i++){HEAP8[argp+i+17]=termios.c_cc[i]||0}return 0}return 0}case 21510:case 21511:case 21512:{if(!stream.tty)return-59;return 0}case 21506:case 21507:case 21508:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcsets){var argp=syscallGetVarargP();var c_iflag=HEAP32[argp>>2];var c_oflag=HEAP32[argp+4>>2];var c_cflag=HEAP32[argp+8>>2];var c_lflag=HEAP32[argp+12>>2];var c_cc=[];for(var i=0;i<32;i++){c_cc.push(HEAP8[argp+i+17])}return stream.tty.ops.ioctl_tcsets(stream.tty,op,{c_iflag,c_oflag,c_cflag,c_lflag,c_cc})}return 0}case 21519:{if(!stream.tty)return-59;var argp=syscallGetVarargP();HEAP32[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21537:case 21531:{var argp=syscallGetVarargP();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tiocgwinsz){var winsize=stream.tty.ops.ioctl_tiocgwinsz(stream.tty);var argp=syscallGetVarargP();HEAP16[argp>>1]=winsize[0];HEAP16[argp+2>>1]=winsize[1]}return 0}case 21524:{if(!stream.tty)return-59;return 0}case 21515:{if(!stream.tty)return-59;return 0}default:return-28}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_openat(dirfd,path,flags,varargs){SYSCALLS.varargs=varargs;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);var mode=varargs?syscallGetVarargI():0;return FS.open(path,flags,mode).fd}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __abort_js=()=>abort("");var structRegistrations={};var runDestructors=destructors=>{while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}};function readPointer(pointer){return this.fromWireType(HEAPU32[pointer>>2])}var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var InternalError=class InternalError extends Error{constructor(message){super(message);this.name="InternalError"}};var throwInternalError=message=>{throw new InternalError(message)};var whenDependentTypesAreResolved=(myTypes,dependentTypes,getTypeConverters)=>{myTypes.forEach(type=>typeDependencies[type]=dependentTypes);function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i<myTypes.length;++i){registerType(myTypes[i],myTypeConverters[i])}}var typeConverters=new Array(dependentTypes.length);var unregisteredTypes=[];var registered=0;for(let[i,dt]of dependentTypes.entries()){if(registeredTypes.hasOwnProperty(dt)){typeConverters[i]=registeredTypes[dt]}else{unregisteredTypes.push(dt);if(!awaitingDependencies.hasOwnProperty(dt)){awaitingDependencies[dt]=[]}awaitingDependencies[dt].push(()=>{typeConverters[i]=registeredTypes[dt];++registered;if(registered===unregisteredTypes.length){onComplete(typeConverters)}})}}if(0===unregisteredTypes.length){onComplete(typeConverters)}};var __embind_finalize_value_object=structType=>{var reg=structRegistrations[structType];delete structRegistrations[structType];var rawConstructor=reg.rawConstructor;var rawDestructor=reg.rawDestructor;var fieldRecords=reg.fields;var fieldTypes=fieldRecords.map(field=>field.getterReturnType).concat(fieldRecords.map(field=>field.setterArgumentType));whenDependentTypesAreResolved([structType],fieldTypes,fieldTypes=>{var fields={};for(var[i,field]of fieldRecords.entries()){const getterReturnType=fieldTypes[i];const getter=field.getter;const getterContext=field.getterContext;const setterArgumentType=fieldTypes[i+fieldRecords.length];const setter=field.setter;const setterContext=field.setterContext;fields[field.fieldName]={read:ptr=>getterReturnType.fromWireType(getter(getterContext,ptr)),write:(ptr,o)=>{var destructors=[];setter(setterContext,ptr,setterArgumentType.toWireType(destructors,o));runDestructors(destructors)},optional:getterReturnType.optional}}return[{name:reg.name,fromWireType:ptr=>{var rv={};for(var i in fields){rv[i]=fields[i].read(ptr)}rawDestructor(ptr);return rv},toWireType:(destructors,o)=>{for(var fieldName in fields){if(!(fieldName in o)&&!fields[fieldName].optional){throw new TypeError(`Missing field: "${fieldName}"`)}}var ptr=rawConstructor();for(fieldName in fields){fields[fieldName].write(ptr,o[fieldName])}if(destructors!==null){destructors.push(rawDestructor,ptr)}return ptr},readValueFromPointer:readPointer,destructorFunction:rawDestructor}]})};var AsciiToString=ptr=>{var str="";while(1){var ch=HEAPU8[ptr++];if(!ch)return str;str+=String.fromCharCode(ch)}};var BindingError=class BindingError extends Error{constructor(message){super(message);this.name="BindingError"}};var throwBindingError=message=>{throw new BindingError(message)};function sharedRegisterType(rawType,registeredInstance,options={}){var name=registeredInstance.name;if(!rawType){throwBindingError(`type "${name}" must have a positive integer typeid pointer`)}if(registeredTypes.hasOwnProperty(rawType)){if(options.ignoreDuplicateRegistrations){return}else{throwBindingError(`Cannot register type '${name}' twice`)}}registeredTypes[rawType]=registeredInstance;delete typeDependencies[rawType];if(awaitingDependencies.hasOwnProperty(rawType)){var callbacks=awaitingDependencies[rawType];delete awaitingDependencies[rawType];callbacks.forEach(cb=>cb())}}function registerType(rawType,registeredInstance,options={}){return sharedRegisterType(rawType,registeredInstance,options)}var integerReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?pointer=>HEAP8[pointer]:pointer=>HEAPU8[pointer];case 2:return signed?pointer=>HEAP16[pointer>>1]:pointer=>HEAPU16[pointer>>1];case 4:return signed?pointer=>HEAP32[pointer>>2]:pointer=>HEAPU32[pointer>>2];case 8:return signed?pointer=>HEAP64[pointer>>3]:pointer=>HEAPU64[pointer>>3];default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};var __embind_register_bigint=(primitiveType,name,size,minRange,maxRange)=>{name=AsciiToString(name);const isUnsignedType=minRange===0n;let fromWireType=value=>value;if(isUnsignedType){const bitSize=size*8;fromWireType=value=>BigInt.asUintN(bitSize,value);maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>{if(typeof value=="number"){value=BigInt(value)}return value},readValueFromPointer:integerReadValueFromPointer(name,size,!isUnsignedType),destructorFunction:null})};var __embind_register_bool=(rawType,name,trueValue,falseValue)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:function(wt){return!!wt},toWireType:function(destructors,o){return o?trueValue:falseValue},readValueFromPointer:function(pointer){return this.fromWireType(HEAPU8[pointer])},destructorFunction:null})};var shallowCopyInternalPointer=o=>({count:o.count,deleteScheduled:o.deleteScheduled,preservePointerOnDelete:o.preservePointerOnDelete,ptr:o.ptr,ptrType:o.ptrType,smartPtr:o.smartPtr,smartPtrType:o.smartPtrType});var throwInstanceAlreadyDeleted=obj=>{function getInstanceTypeName(handle){return handle.$$.ptrType.registeredClass.name}throwBindingError(getInstanceTypeName(obj)+" instance already deleted")};var finalizationRegistry=false;var detachFinalizer=handle=>{};var runDestructor=$$=>{if($$.smartPtr){$$.smartPtrType.rawDestructor($$.smartPtr)}else{$$.ptrType.registeredClass.rawDestructor($$.ptr)}};var releaseClassHandle=$$=>{$$.count.value-=1;var toDelete=0===$$.count.value;if(toDelete){runDestructor($$)}};var attachFinalizer=handle=>{if(!globalThis.FinalizationRegistry){attachFinalizer=handle=>handle;return handle}finalizationRegistry=new FinalizationRegistry(info=>{releaseClassHandle(info.$$)});attachFinalizer=handle=>{var $$=handle.$$;var hasSmartPtr=!!$$.smartPtr;if(hasSmartPtr){var info={$$};finalizationRegistry.register(handle,info,handle)}return handle};detachFinalizer=handle=>finalizationRegistry.unregister(handle);return attachFinalizer(handle)};var deletionQueue=[];var flushPendingDeletes=()=>{while(deletionQueue.length){var obj=deletionQueue.pop();obj.$$.deleteScheduled=false;obj["delete"]()}};var delayFunction;var init_ClassHandle=()=>{let proto=ClassHandle.prototype;Object.assign(proto,{isAliasOf(other){if(!(this instanceof ClassHandle)){return false}if(!(other instanceof ClassHandle)){return false}var leftClass=this.$$.ptrType.registeredClass;var left=this.$$.ptr;other.$$=other.$$;var rightClass=other.$$.ptrType.registeredClass;var right=other.$$.ptr;while(leftClass.baseClass){left=leftClass.upcast(left);leftClass=leftClass.baseClass}while(rightClass.baseClass){right=rightClass.upcast(right);rightClass=rightClass.baseClass}return leftClass===rightClass&&left===right},clone(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.preservePointerOnDelete){this.$$.count.value+=1;return this}else{var clone=attachFinalizer(Object.create(Object.getPrototypeOf(this),{$$:{value:shallowCopyInternalPointer(this.$$)}}));clone.$$.count.value+=1;clone.$$.deleteScheduled=false;return clone}},delete(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}detachFinalizer(this);releaseClassHandle(this.$$);if(!this.$$.preservePointerOnDelete){this.$$.smartPtr=undefined;this.$$.ptr=undefined}},isDeleted(){return!this.$$.ptr},deleteLater(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}deletionQueue.push(this);if(deletionQueue.length===1&&delayFunction){delayFunction(flushPendingDeletes)}this.$$.deleteScheduled=true;return this}});const symbolDispose=Symbol.dispose;if(symbolDispose){proto[symbolDispose]=proto["delete"]}};function ClassHandle(){}var createNamedFunction=(name,func)=>Object.defineProperty(func,"name",{value:name});var registeredPointers={};var ensureOverloadTable=(proto,methodName,humanName)=>{if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(...args){if(!proto[methodName].overloadTable.hasOwnProperty(args.length)){throwBindingError(`Function '${humanName}' called with an invalid number of arguments (${args.length}) - expects one of (${proto[methodName].overloadTable})!`)}return proto[methodName].overloadTable[args.length].apply(this,args)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}};var exposePublicSymbol=(name,value,numArguments)=>{if(Module.hasOwnProperty(name)){if(undefined===numArguments||undefined!==Module[name].overloadTable&&undefined!==Module[name].overloadTable[numArguments]){throwBindingError(`Cannot register public name '${name}' twice`)}ensureOverloadTable(Module,name,name);if(Module[name].overloadTable.hasOwnProperty(numArguments)){throwBindingError(`Cannot register multiple overloads of a function with the same number of arguments (${numArguments})!`)}Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var char_0=48;var char_9=57;var makeLegalFunctionName=name=>{name=name.replace(/[^a-zA-Z0-9_]/g,"$");var f=name.charCodeAt(0);if(f>=char_0&&f<=char_9){return`_${name}`}return name};function RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast){this.name=name;this.constructor=constructor;this.instancePrototype=instancePrototype;this.rawDestructor=rawDestructor;this.baseClass=baseClass;this.getActualType=getActualType;this.upcast=upcast;this.downcast=downcast;this.pureVirtualFunctions=[]}var upcastPointer=(ptr,ptrClass,desiredClass)=>{while(ptrClass!==desiredClass){if(!ptrClass.upcast){throwBindingError(`Expected null or instance of ${desiredClass.name}, got an instance of ${ptrClass.name}`)}ptr=ptrClass.upcast(ptr);ptrClass=ptrClass.baseClass}return ptr};var embindRepr=v=>{if(v===null){return"null"}var t=typeof v;if(t==="object"||t==="array"||t==="function"){return v.toString()}else{return""+v}};function constNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}return 0}if(!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function genericPointerToWireType(destructors,handle){var ptr;if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}if(this.isSmartPointer){ptr=this.rawConstructor();if(destructors!==null){destructors.push(this.rawDestructor,ptr)}return ptr}else{return 0}}if(!handle||!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}if(!this.isConst&&handle.$$.ptrType.isConst){throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name} to parameter type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);if(this.isSmartPointer){if(undefined===handle.$$.smartPtr){throwBindingError("Passing raw pointer to smart pointer is illegal")}switch(this.sharingPolicy){case 0:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name} to parameter type ${this.name}`)}break;case 1:ptr=handle.$$.smartPtr;break;case 2:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{var clonedHandle=handle["clone"]();ptr=this.rawShare(ptr,Emval.toHandle(()=>clonedHandle["delete"]()));if(destructors!==null){destructors.push(this.rawDestructor,ptr)}}break;default:throwBindingError("Unsupported sharing policy")}}return ptr}function nonConstNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}return 0}if(!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}if(handle.$$.ptrType.isConst){throwBindingError(`Cannot convert argument of type ${handle.$$.ptrType.name} to parameter type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}var downcastPointer=(ptr,ptrClass,desiredClass)=>{if(ptrClass===desiredClass){return ptr}if(undefined===desiredClass.baseClass){return null}var rv=downcastPointer(ptr,ptrClass,desiredClass.baseClass);if(rv===null){return null}return desiredClass.downcast(rv)};var registeredInstances={};var getBasestPointer=(class_,ptr)=>{if(ptr===undefined){throwBindingError("ptr should not be undefined")}while(class_.baseClass){ptr=class_.upcast(ptr);class_=class_.baseClass}return ptr};var getInheritedInstance=(class_,ptr)=>{ptr=getBasestPointer(class_,ptr);return registeredInstances[ptr]};var makeClassHandle=(prototype,record)=>{if(!record.ptrType||!record.ptr){throwInternalError("makeClassHandle requires ptr and ptrType")}var hasSmartPtrType=!!record.smartPtrType;var hasSmartPtr=!!record.smartPtr;if(hasSmartPtrType!==hasSmartPtr){throwInternalError("Both smartPtrType and smartPtr must be specified")}record.count={value:1};return attachFinalizer(Object.create(prototype,{$$:{value:record,writable:true}}))};function RegisteredPointer_fromWireType(ptr){var rawPointer=this.getPointee(ptr);if(!rawPointer){this.destructor(ptr);return null}var registeredInstance=getInheritedInstance(this.registeredClass,rawPointer);if(undefined!==registeredInstance){if(0===registeredInstance.$$.count.value){registeredInstance.$$.ptr=rawPointer;registeredInstance.$$.smartPtr=ptr;return registeredInstance["clone"]()}else{var rv=registeredInstance["clone"]();this.destructor(ptr);return rv}}function makeDefaultHandle(){if(this.isSmartPointer){return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:rawPointer,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this,ptr})}}var actualType=this.registeredClass.getActualType(rawPointer);var registeredPointerRecord=registeredPointers[actualType];if(!registeredPointerRecord){return makeDefaultHandle.call(this)}var toType;if(this.isConst){toType=registeredPointerRecord.constPointerType}else{toType=registeredPointerRecord.pointerType}var dp=downcastPointer(rawPointer,this.registeredClass,toType.registeredClass);if(dp===null){return makeDefaultHandle.call(this)}if(this.isSmartPointer){return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp})}}var init_RegisteredPointer=()=>{Object.assign(RegisteredPointer.prototype,{getPointee(ptr){if(this.rawGetPointee){ptr=this.rawGetPointee(ptr)}return ptr},destructor(ptr){this.rawDestructor?.(ptr)},readValueFromPointer:readPointer,fromWireType:RegisteredPointer_fromWireType})};function RegisteredPointer(name,registeredClass,isReference,isConst,isSmartPointer,pointeeType,sharingPolicy,rawGetPointee,rawConstructor,rawShare,rawDestructor){this.name=name;this.registeredClass=registeredClass;this.isReference=isReference;this.isConst=isConst;this.isSmartPointer=isSmartPointer;this.pointeeType=pointeeType;this.sharingPolicy=sharingPolicy;this.rawGetPointee=rawGetPointee;this.rawConstructor=rawConstructor;this.rawShare=rawShare;this.rawDestructor=rawDestructor;if(!isSmartPointer&®isteredClass.baseClass===undefined){if(isConst){this.toWireType=constNoSmartPtrRawPointerToWireType;this.destructorFunction=null}else{this.toWireType=nonConstNoSmartPtrRawPointerToWireType;this.destructorFunction=null}}else{this.toWireType=genericPointerToWireType}}var replacePublicSymbol=(name,value,numArguments)=>{if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistent public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};var embind__requireFunction=(signature,rawFunction,isAsync=false)=>{signature=AsciiToString(signature);function makeDynCaller(){var rtn=getWasmTableEntry(rawFunction);return rtn}var fp=makeDynCaller();if(typeof fp!="function"){throwBindingError(`unknown function pointer with signature ${signature}: ${rawFunction}`)}return fp};class UnboundTypeError extends Error{}var getTypeName=type=>{var ptr=___getTypeName(type);var rv=AsciiToString(ptr);_free(ptr);return rv};var throwUnboundTypeError=(message,types)=>{var unboundTypes=[];var seen={};function visit(type){if(seen[type]){return}if(registeredTypes[type]){return}if(typeDependencies[type]){typeDependencies[type].forEach(visit);return}unboundTypes.push(type);seen[type]=true}types.forEach(visit);throw new UnboundTypeError(`${message}: `+unboundTypes.map(getTypeName).join([", "]))};var __embind_register_class=(rawType,rawPointerType,rawConstPointerType,baseClassRawType,getActualTypeSignature,getActualType,upcastSignature,upcast,downcastSignature,downcast,name,destructorSignature,rawDestructor)=>{name=AsciiToString(name);getActualType=embind__requireFunction(getActualTypeSignature,getActualType);upcast&&=embind__requireFunction(upcastSignature,upcast);downcast&&=embind__requireFunction(downcastSignature,downcast);rawDestructor=embind__requireFunction(destructorSignature,rawDestructor);var legalFunctionName=makeLegalFunctionName(name);exposePublicSymbol(legalFunctionName,function(){throwUnboundTypeError(`Cannot construct ${name} due to unbound types`,[baseClassRawType])});whenDependentTypesAreResolved([rawType,rawPointerType,rawConstPointerType],baseClassRawType?[baseClassRawType]:[],base=>{base=base[0];var baseClass;var basePrototype;if(baseClassRawType){baseClass=base.registeredClass;basePrototype=baseClass.instancePrototype}else{basePrototype=ClassHandle.prototype}var constructor=createNamedFunction(name,function(...args){if(Object.getPrototypeOf(this)!==instancePrototype){throw new BindingError(`Use 'new' to construct ${name}`)}if(undefined===registeredClass.constructor_body){throw new BindingError(`${name} has no accessible constructor`)}var body=registeredClass.constructor_body[args.length];if(undefined===body){throw new BindingError(`Tried to invoke ctor of ${name} with invalid number of parameters (${args.length}) - expected (${Object.keys(registeredClass.constructor_body).toString()}) parameters instead!`)}return body.apply(this,args)});var instancePrototype=Object.create(basePrototype,{constructor:{value:constructor}});constructor.prototype=instancePrototype;var registeredClass=new RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast);if(registeredClass.baseClass){registeredClass.baseClass.__derivedClasses??=[];registeredClass.baseClass.__derivedClasses.push(registeredClass)}var referenceConverter=new RegisteredPointer(name,registeredClass,true,false,false);var pointerConverter=new RegisteredPointer(name+"*",registeredClass,false,false,false);var constPointerConverter=new RegisteredPointer(name+" const*",registeredClass,false,true,false);registeredPointers[rawType]={pointerType:pointerConverter,constPointerType:constPointerConverter};replacePublicSymbol(legalFunctionName,constructor);return[referenceConverter,pointerConverter,constPointerConverter]})};var heap32VectorToArray=(count,firstElement)=>{var array=[];for(var i=0;i<count;i++){array.push(HEAPU32[firstElement+i*4>>2])}return array};function usesDestructorStack(argTypes){for(var i=1;i<argTypes.length;++i){if(argTypes[i]!==null&&argTypes[i].destructorFunction===undefined){return true}}return false}function craftInvokerFunction(humanName,argTypes,classType,cppInvokerFunc,cppTargetFunc,isAsync){var argCount=argTypes.length;if(argCount<2){throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!")}var isClassMethodFunc=argTypes[1]!==null&&classType!==null;var needsDestructorStack=usesDestructorStack(argTypes);var returns=!argTypes[0].isVoid;var expectedArgCount=argCount-2;var argsWired=new Array(expectedArgCount);var invokerFuncArgs=[];var destructors=[];var invokerFn=function(...args){destructors.length=0;var thisWired;invokerFuncArgs.length=isClassMethodFunc?2:1;invokerFuncArgs[0]=cppTargetFunc;if(isClassMethodFunc){thisWired=argTypes[1].toWireType(destructors,this);invokerFuncArgs[1]=thisWired}for(var i=0;i<expectedArgCount;++i){argsWired[i]=argTypes[i+2].toWireType(destructors,args[i]);invokerFuncArgs.push(argsWired[i])}var rv=cppInvokerFunc(...invokerFuncArgs);function onDone(rv){if(needsDestructorStack){runDestructors(destructors)}else{for(var i=isClassMethodFunc?1:2;i<argTypes.length;i++){var param=i===1?thisWired:argsWired[i-2];if(argTypes[i].destructorFunction!==null){argTypes[i].destructorFunction(param)}}}if(returns){return argTypes[0].fromWireType(rv)}}return onDone(rv)};return createNamedFunction(humanName,invokerFn)}var __embind_register_class_constructor=(rawClassType,argCount,rawArgTypesAddr,invokerSignature,invoker,rawConstructor)=>{var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);invoker=embind__requireFunction(invokerSignature,invoker);whenDependentTypesAreResolved([],[rawClassType],classType=>{classType=classType[0];var humanName=`constructor ${classType.name}`;if(undefined===classType.registeredClass.constructor_body){classType.registeredClass.constructor_body=[]}if(undefined!==classType.registeredClass.constructor_body[argCount-1]){throw new BindingError(`Cannot register multiple constructors with identical number of parameters (${argCount-1}) for class '${classType.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`)}classType.registeredClass.constructor_body[argCount-1]=()=>{throwUnboundTypeError(`Cannot construct ${classType.name} due to unbound types`,rawArgTypes)};whenDependentTypesAreResolved([],rawArgTypes,argTypes=>{argTypes.splice(1,0,null);classType.registeredClass.constructor_body[argCount-1]=craftInvokerFunction(humanName,argTypes,null,invoker,rawConstructor);return[]});return[]})};var getFunctionName=signature=>{signature=signature.trim();const argsIndex=signature.indexOf("(");if(argsIndex===-1)return signature;return signature.slice(0,argsIndex)};var __embind_register_class_function=(rawClassType,methodName,argCount,rawArgTypesAddr,invokerSignature,rawInvoker,context,isPureVirtual,isAsync,isNonnullReturn)=>{var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);methodName=AsciiToString(methodName);methodName=getFunctionName(methodName);rawInvoker=embind__requireFunction(invokerSignature,rawInvoker,isAsync);whenDependentTypesAreResolved([],[rawClassType],classType=>{classType=classType[0];var humanName=`${classType.name}.${methodName}`;if(methodName.startsWith("@@")){methodName=Symbol[methodName.substring(2)]}if(isPureVirtual){classType.registeredClass.pureVirtualFunctions.push(methodName)}function unboundTypesHandler(){throwUnboundTypeError(`Cannot call ${humanName} due to unbound types`,rawArgTypes)}var proto=classType.registeredClass.instancePrototype;var method=proto[methodName];if(undefined===method||undefined===method.overloadTable&&method.className!==classType.name&&method.argCount===argCount-2){unboundTypesHandler.argCount=argCount-2;unboundTypesHandler.className=classType.name;proto[methodName]=unboundTypesHandler}else{ensureOverloadTable(proto,methodName,humanName);proto[methodName].overloadTable[argCount-2]=unboundTypesHandler}whenDependentTypesAreResolved([],rawArgTypes,argTypes=>{var memberFunction=craftInvokerFunction(humanName,argTypes,classType,rawInvoker,context,isAsync);if(undefined===proto[methodName].overloadTable){memberFunction.argCount=argCount-2;proto[methodName]=memberFunction}else{proto[methodName].overloadTable[argCount-2]=memberFunction}return[]});return[]})};var emval_freelist=[];var emval_handles=[0,1,,1,null,1,true,1,false,1];var __emval_decref=handle=>{if(handle>9&&0===--emval_handles[handle+1]){emval_handles[handle]=undefined;emval_freelist.push(handle)}};var Emval={toValue:handle=>{if(!handle){throwBindingError(`Cannot use deleted val. handle = ${handle}`)}return emval_handles[handle]},toHandle:value=>{switch(value){case undefined:return 2;case null:return 4;case true:return 6;case false:return 8;default:{const handle=emval_freelist.pop()||emval_handles.length;emval_handles[handle]=value;emval_handles[handle+1]=1;return handle}}}};var EmValType={name:"emscripten::val",fromWireType:handle=>{var rv=Emval.toValue(handle);__emval_decref(handle);return rv},toWireType:(destructors,value)=>Emval.toHandle(value),readValueFromPointer:readPointer,destructorFunction:null};var __embind_register_emval=rawType=>registerType(rawType,EmValType);var enumReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?function(pointer){return this.fromWireType(HEAP8[pointer])}:function(pointer){return this.fromWireType(HEAPU8[pointer])};case 2:return signed?function(pointer){return this.fromWireType(HEAP16[pointer>>1])}:function(pointer){return this.fromWireType(HEAPU16[pointer>>1])};case 4:return signed?function(pointer){return this.fromWireType(HEAP32[pointer>>2])}:function(pointer){return this.fromWireType(HEAPU32[pointer>>2])};default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};function getEnumValueType(rawValueType){return rawValueType===0?"object":rawValueType===1?"number":"string"}var __embind_register_enum=(rawType,name,size,isSigned,rawValueType)=>{name=AsciiToString(name);const valueType=getEnumValueType(rawValueType);switch(valueType){case"object":{function ctor(){}ctor.values={};registerType(rawType,{name,constructor:ctor,valueType,fromWireType:function(c){return this.constructor.values[c]},toWireType:(destructors,c)=>c.value,readValueFromPointer:enumReadValueFromPointer(name,size,isSigned),destructorFunction:null});exposePublicSymbol(name,ctor);break}case"number":{var keysMap={};registerType(rawType,{name,keysMap,valueType,fromWireType:c=>c,toWireType:(destructors,c)=>c,readValueFromPointer:enumReadValueFromPointer(name,size,isSigned),destructorFunction:null});exposePublicSymbol(name,keysMap);delete Module[name].argCount;break}case"string":{var valuesMap={};var reverseMap={};var keysMap={};registerType(rawType,{name,valuesMap,reverseMap,keysMap,valueType,fromWireType:function(c){return this.reverseMap[c]},toWireType:function(destructors,c){return this.valuesMap[c]},readValueFromPointer:enumReadValueFromPointer(name,size,isSigned),destructorFunction:null});exposePublicSymbol(name,keysMap);delete Module[name].argCount;break}}};var requireRegisteredType=(rawType,humanName)=>{var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(`${humanName} has unknown type ${getTypeName(rawType)}`)}return impl};var __embind_register_enum_value=(rawEnumType,name,enumValue)=>{var enumType=requireRegisteredType(rawEnumType,"enum");name=AsciiToString(name);switch(enumType.valueType){case"object":{var Enum=enumType.constructor;var Value=Object.create(enumType.constructor.prototype,{value:{value:enumValue},constructor:{value:createNamedFunction(`${enumType.name}_${name}`,function(){})}});Enum.values[enumValue]=Value;Enum[name]=Value;break}case"number":{enumType.keysMap[name]=enumValue;break}case"string":{enumType.valuesMap[name]=enumValue;enumType.reverseMap[enumValue]=name;enumType.keysMap[name]=name;break}}};var floatReadValueFromPointer=(name,width)=>{switch(width){case 4:return function(pointer){return this.fromWireType(HEAPF32[pointer>>2])};case 8:return function(pointer){return this.fromWireType(HEAPF64[pointer>>3])};default:throw new TypeError(`invalid float width (${width}): ${name}`)}};var __embind_register_float=(rawType,name,size)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:value=>value,toWireType:(destructors,value)=>value,readValueFromPointer:floatReadValueFromPointer(name,size),destructorFunction:null})};var __embind_register_function=(name,argCount,rawArgTypesAddr,signature,rawInvoker,fn,isAsync,isNonnullReturn)=>{var argTypes=heap32VectorToArray(argCount,rawArgTypesAddr);name=AsciiToString(name);name=getFunctionName(name);rawInvoker=embind__requireFunction(signature,rawInvoker,isAsync);exposePublicSymbol(name,function(){throwUnboundTypeError(`Cannot call ${name} due to unbound types`,argTypes)},argCount-1);whenDependentTypesAreResolved([],argTypes,argTypes=>{var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));replacePublicSymbol(name,craftInvokerFunction(name,invokerArgsArray,null,rawInvoker,fn,isAsync),argCount-1);return[]})};var __embind_register_integer=(primitiveType,name,size,minRange,maxRange)=>{name=AsciiToString(name);const isUnsignedType=minRange===0;let fromWireType=value=>value;if(isUnsignedType){var bitshift=32-8*size;fromWireType=value=>value<<bitshift>>>bitshift;maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>value,readValueFromPointer:integerReadValueFromPointer(name,size,minRange!==0),destructorFunction:null})};var installIndexedIterator=(proto,sizeMethodName,getMethodName)=>{const makeIterator=(size,getValue)=>{let index=0;return{next(){if(index>=size){return{done:true}}const current=index;index++;const value=getValue(current);return{value,done:false}},[Symbol.iterator](){return this}}};if(!proto[Symbol.iterator]){proto[Symbol.iterator]=function(){const size=this[sizeMethodName]();return makeIterator(size,i=>this[getMethodName](i))}}};var __embind_register_iterable=(rawClassType,rawElementType,sizeMethodName,getMethodName)=>{sizeMethodName=AsciiToString(sizeMethodName);getMethodName=AsciiToString(getMethodName);whenDependentTypesAreResolved([],[rawClassType,rawElementType],types=>{const classType=types[0];installIndexedIterator(classType.registeredClass.instancePrototype,sizeMethodName,getMethodName);return[]})};var __embind_register_memory_view=(rawType,dataTypeIndex,name)=>{var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){var size=HEAPU32[handle>>2];var data=HEAPU32[handle+4>>2];return new TA(HEAP8.buffer,data,size)}name=AsciiToString(name);registerType(rawType,{name,fromWireType:decodeMemoryView,readValueFromPointer:decodeMemoryView},{ignoreDuplicateRegistrations:true})};var EmValOptionalType=Object.assign({optional:true},EmValType);var __embind_register_optional=(rawOptionalType,rawType)=>{registerType(rawOptionalType,EmValOptionalType)};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var __embind_register_std_string=(rawType,name)=>{name=AsciiToString(name);var stdStringIsUTF8=true;registerType(rawType,{name,fromWireType(value){var length=HEAPU32[value>>2];var payload=value+4;var str;if(stdStringIsUTF8){str=UTF8ToString(payload,length,true)}else{str="";for(var i=0;i<length;++i){str+=String.fromCharCode(HEAPU8[payload+i])}}_free(value);return str},toWireType(destructors,value){if(value instanceof ArrayBuffer){value=new Uint8Array(value)}var length;var valueIsOfTypeString=typeof value=="string";if(!(valueIsOfTypeString||ArrayBuffer.isView(value)&&value.BYTES_PER_ELEMENT==1)){throwBindingError("Cannot pass non-string to std::string")}if(stdStringIsUTF8&&valueIsOfTypeString){length=lengthBytesUTF8(value)}else{length=value.length}var base=_malloc(4+length+1);var ptr=base+4;HEAPU32[base>>2]=length;if(valueIsOfTypeString){if(stdStringIsUTF8){stringToUTF8(value,ptr,length+1)}else{for(var i=0;i<length;++i){var charCode=value.charCodeAt(i);if(charCode>255){_free(base);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+i]=charCode}}}else{HEAPU8.set(value,ptr)}if(destructors!==null){destructors.push(_free,base)}return base},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var UTF16Decoder=globalThis.TextDecoder?new TextDecoder("utf-16le"):undefined;var UTF16ToString=(ptr,maxBytesToRead,ignoreNul)=>{var idx=ptr>>1;var endIdx=findStringEnd(HEAPU16,idx,maxBytesToRead/2,ignoreNul);if(endIdx-idx>16&&UTF16Decoder)return UTF16Decoder.decode(HEAPU16.subarray(idx,endIdx));var str="";for(var i=idx;i<endIdx;++i){var codeUnit=HEAPU16[i];str+=String.fromCharCode(codeUnit)}return str};var stringToUTF16=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite<str.length*2?maxBytesToWrite/2:str.length;for(var i=0;i<numCharsToWrite;++i){var codeUnit=str.charCodeAt(i);HEAP16[outPtr>>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr};var lengthBytesUTF16=str=>str.length*2;var UTF32ToString=(ptr,maxBytesToRead,ignoreNul)=>{var str="";var startIdx=ptr>>2;for(var i=0;!(i>=maxBytesToRead/4);i++){var utf32=HEAPU32[startIdx+i];if(!utf32&&!ignoreNul)break;str+=String.fromCodePoint(utf32)}return str};var stringToUTF32=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535){i++}HEAP32[outPtr>>2]=codePoint;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr};var lengthBytesUTF32=str=>{var len=0;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535){i++}len+=4}return len};var __embind_register_std_wstring=(rawType,charSize,name)=>{name=AsciiToString(name);var decodeString,encodeString,lengthBytesUTF;if(charSize===2){decodeString=UTF16ToString;encodeString=stringToUTF16;lengthBytesUTF=lengthBytesUTF16}else{decodeString=UTF32ToString;encodeString=stringToUTF32;lengthBytesUTF=lengthBytesUTF32}registerType(rawType,{name,fromWireType:value=>{var length=HEAPU32[value>>2];var str=decodeString(value+4,length*charSize,true);_free(value);return str},toWireType:(destructors,value)=>{if(!(typeof value=="string")){throwBindingError(`Cannot pass non-string to C++ string type ${name}`)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length/charSize;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var __embind_register_value_object=(rawType,name,constructorSignature,rawConstructor,destructorSignature,rawDestructor)=>{structRegistrations[rawType]={name:AsciiToString(name),rawConstructor:embind__requireFunction(constructorSignature,rawConstructor),rawDestructor:embind__requireFunction(destructorSignature,rawDestructor),fields:[]}};var __embind_register_value_object_field=(structType,fieldName,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext)=>{structRegistrations[structType].fields.push({fieldName:AsciiToString(fieldName),getterReturnType,getter:embind__requireFunction(getterSignature,getter),getterContext,setterArgumentType,setter:embind__requireFunction(setterSignature,setter),setterContext})};var __embind_register_void=(rawType,name)=>{name=AsciiToString(name);registerType(rawType,{isVoid:true,name,fromWireType:()=>undefined,toWireType:(destructors,o)=>undefined})};var runtimeKeepaliveCounter=0;var __emscripten_runtime_keepalive_clear=()=>{noExitRuntime=false;runtimeKeepaliveCounter=0};var emval_methodCallers=[];var emval_addMethodCaller=caller=>{var id=emval_methodCallers.length;emval_methodCallers.push(caller);return id};var emval_lookupTypes=(argCount,argTypes)=>{var a=new Array(argCount);for(var i=0;i<argCount;++i){a[i]=requireRegisteredType(HEAPU32[argTypes+i*4>>2],`parameter ${i}`)}return a};var emval_returnValue=(toReturnWire,destructorsRef,handle)=>{var destructors=[];var result=toReturnWire(destructors,handle);if(destructors.length){HEAPU32[destructorsRef>>2]=Emval.toHandle(destructors)}return result};var emval_symbols={};var getStringOrSymbol=address=>{var symbol=emval_symbols[address];if(symbol===undefined){return AsciiToString(address)}return symbol};var __emval_create_invoker=(argCount,argTypesPtr,kind)=>{var GenericWireTypeSize=8;var[retType,...argTypes]=emval_lookupTypes(argCount,argTypesPtr);var toReturnWire=retType.toWireType.bind(retType);var argFromPtr=argTypes.map(type=>type.readValueFromPointer.bind(type));argCount--;var argN=new Array(argCount);var invokerFunction=(handle,methodName,destructorsRef,args)=>{var offset=0;for(var i=0;i<argCount;++i){argN[i]=argFromPtr[i](args+offset);offset+=GenericWireTypeSize}var rv;switch(kind){case 0:rv=Emval.toValue(handle).apply(null,argN);break;case 2:rv=Reflect.construct(Emval.toValue(handle),argN);break;case 3:rv=argN[0];break;case 1:rv=Emval.toValue(handle)[getStringOrSymbol(methodName)](...argN);break}return emval_returnValue(toReturnWire,destructorsRef,rv)};var functionName=`methodCaller<(${argTypes.map(t=>t.name)}) => ${retType.name}>`;return emval_addMethodCaller(createNamedFunction(functionName,invokerFunction))};var __emval_invoke=(caller,handle,methodName,destructorsRef,args)=>emval_methodCallers[caller](handle,methodName,destructorsRef,args);var __emval_new_array=()=>Emval.toHandle([]);var __emval_new_cstring=v=>Emval.toHandle(getStringOrSymbol(v));var __emval_new_object=()=>Emval.toHandle({});var __emval_run_destructors=handle=>{var destructors=Emval.toValue(handle);runDestructors(destructors);__emval_decref(handle)};var __emval_set_property=(handle,key,value)=>{handle=Emval.toValue(handle);key=Emval.toValue(key);value=Emval.toValue(value);handle[key]=value};var timers={};var handleException=e=>{if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)};var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;var maybeExit=()=>{if(!keepRuntimeAlive()){try{_exit(EXITSTATUS)}catch(e){handleException(e)}}};var callUserCallback=func=>{if(ABORT){return}try{return func()}catch(e){handleException(e)}finally{maybeExit()}};var _emscripten_get_now=()=>performance.now();var __setitimer_js=(which,timeout_ms)=>{if(timers[which]){clearTimeout(timers[which].id);delete timers[which]}if(!timeout_ms)return 0;var id=setTimeout(()=>{delete timers[which];callUserCallback(()=>__emscripten_timeout(which,_emscripten_get_now()))},timeout_ms);timers[which]={id,timeout_ms};return 0};var __tzset_js=(timezone,daylight,std_name,dst_name)=>{var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);HEAPU32[timezone>>2]=stdTimezoneOffset*60;HEAP32[daylight>>2]=Number(winterOffset!=summerOffset);var extractZone=timezoneOffset=>{var sign=timezoneOffset>=0?"-":"+";var absOffset=Math.abs(timezoneOffset);var hours=String(Math.floor(absOffset/60)).padStart(2,"0");var minutes=String(absOffset%60).padStart(2,"0");return`UTC${sign}${hours}${minutes}`};var winterName=extractZone(winterOffset);var summerName=extractZone(summerOffset);if(summerOffset<winterOffset){stringToUTF8(winterName,std_name,17);stringToUTF8(summerName,dst_name,17)}else{stringToUTF8(winterName,dst_name,17);stringToUTF8(summerName,std_name,17)}};var _emscripten_date_now=()=>Date.now();var nowIsMonotonic=1;var checkWasiClock=clock_id=>clock_id>=0&&clock_id<=3;var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function _clock_time_get(clk_id,ignored_precision,ptime){ignored_precision=bigintToI53Checked(ignored_precision);if(!checkWasiClock(clk_id)){return 28}var now;if(clk_id===0){now=_emscripten_date_now()}else if(nowIsMonotonic){now=_emscripten_get_now()}else{return 52}var nsec=Math.round(now*1e3*1e3);HEAP64[ptime>>3]=BigInt(nsec);return 0}var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var GLctx;var webgl_enable_ANGLE_instanced_arrays=ctx=>{var ext=ctx.getExtension("ANGLE_instanced_arrays");if(ext){ctx["vertexAttribDivisor"]=(index,divisor)=>ext["vertexAttribDivisorANGLE"](index,divisor);ctx["drawArraysInstanced"]=(mode,first,count,primcount)=>ext["drawArraysInstancedANGLE"](mode,first,count,primcount);ctx["drawElementsInstanced"]=(mode,count,type,indices,primcount)=>ext["drawElementsInstancedANGLE"](mode,count,type,indices,primcount);return 1}};var webgl_enable_OES_vertex_array_object=ctx=>{var ext=ctx.getExtension("OES_vertex_array_object");if(ext){ctx["createVertexArray"]=()=>ext["createVertexArrayOES"]();ctx["deleteVertexArray"]=vao=>ext["deleteVertexArrayOES"](vao);ctx["bindVertexArray"]=vao=>ext["bindVertexArrayOES"](vao);ctx["isVertexArray"]=vao=>ext["isVertexArrayOES"](vao);return 1}};var webgl_enable_WEBGL_draw_buffers=ctx=>{var ext=ctx.getExtension("WEBGL_draw_buffers");if(ext){ctx["drawBuffers"]=(n,bufs)=>ext["drawBuffersWEBGL"](n,bufs);return 1}};var webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance=ctx=>!!(ctx.dibvbi=ctx.getExtension("WEBGL_draw_instanced_base_vertex_base_instance"));var webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance=ctx=>!!(ctx.mdibvbi=ctx.getExtension("WEBGL_multi_draw_instanced_base_vertex_base_instance"));var webgl_enable_EXT_polygon_offset_clamp=ctx=>!!(ctx.extPolygonOffsetClamp=ctx.getExtension("EXT_polygon_offset_clamp"));var webgl_enable_EXT_clip_control=ctx=>!!(ctx.extClipControl=ctx.getExtension("EXT_clip_control"));var webgl_enable_WEBGL_polygon_mode=ctx=>!!(ctx.webglPolygonMode=ctx.getExtension("WEBGL_polygon_mode"));var webgl_enable_WEBGL_multi_draw=ctx=>!!(ctx.multiDrawWebgl=ctx.getExtension("WEBGL_multi_draw"));var getEmscriptenSupportedExtensions=ctx=>{var supportedExtensions=["ANGLE_instanced_arrays","EXT_blend_minmax","EXT_disjoint_timer_query","EXT_frag_depth","EXT_shader_texture_lod","EXT_sRGB","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","WEBGL_color_buffer_float","WEBGL_depth_texture","WEBGL_draw_buffers","EXT_color_buffer_float","EXT_conservative_depth","EXT_disjoint_timer_query_webgl2","EXT_texture_norm16","NV_shader_noperspective_interpolation","WEBGL_clip_cull_distance","EXT_clip_control","EXT_color_buffer_half_float","EXT_depth_clamp","EXT_float_blend","EXT_polygon_offset_clamp","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","KHR_parallel_shader_compile","OES_texture_float_linear","WEBGL_blend_func_extended","WEBGL_compressed_texture_astc","WEBGL_compressed_texture_etc","WEBGL_compressed_texture_etc1","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_lose_context","WEBGL_multi_draw","WEBGL_polygon_mode"];return(ctx.getSupportedExtensions()||[]).filter(ext=>supportedExtensions.includes(ext))};var registerPreMainLoop=f=>{typeof MainLoop!="undefined"&&MainLoop.preMainLoop.push(f)};var GL={counter:1,buffers:[],mappedBuffers:{},programs:[],framebuffers:[],renderbuffers:[],textures:[],shaders:[],vaos:[],contexts:[],offscreenCanvases:{},queries:[],samplers:[],transformFeedbacks:[],syncs:[],byteSizeByTypeRoot:5120,byteSizeByType:[1,1,2,2,4,4,4,2,3,4,8],stringCache:{},stringiCache:{},unpackAlignment:4,unpackRowLength:0,recordError:errorCode=>{if(!GL.lastError){GL.lastError=errorCode}},getNewId:table=>{var ret=GL.counter++;for(var i=table.length;i<ret;i++){table[i]=null}while(table[ret]){ret=GL.counter++}return ret},genObject:(n,buffers,createFunction,objectTable)=>{for(var i=0;i<n;i++){var buffer=GLctx[createFunction]();var id=buffer&&GL.getNewId(objectTable);if(buffer){buffer.name=id;objectTable[id]=buffer}else{GL.recordError(1282)}HEAP32[buffers+i*4>>2]=id}},MAX_TEMP_BUFFER_SIZE:2097152,numTempVertexBuffersPerSize:64,log2ceilLookup:i=>32-Math.clz32(i===0?0:i-1),generateTempBuffers:(quads,context)=>{var largestIndex=GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);context.tempVertexBufferCounters1=[];context.tempVertexBufferCounters2=[];context.tempVertexBufferCounters1.length=context.tempVertexBufferCounters2.length=largestIndex+1;context.tempVertexBuffers1=[];context.tempVertexBuffers2=[];context.tempVertexBuffers1.length=context.tempVertexBuffers2.length=largestIndex+1;context.tempIndexBuffers=[];context.tempIndexBuffers.length=largestIndex+1;for(var i=0;i<=largestIndex;++i){context.tempIndexBuffers[i]=null;context.tempVertexBufferCounters1[i]=context.tempVertexBufferCounters2[i]=0;var ringbufferLength=GL.numTempVertexBuffersPerSize;context.tempVertexBuffers1[i]=[];context.tempVertexBuffers2[i]=[];var ringbuffer1=context.tempVertexBuffers1[i];var ringbuffer2=context.tempVertexBuffers2[i];ringbuffer1.length=ringbuffer2.length=ringbufferLength;for(var j=0;j<ringbufferLength;++j){ringbuffer1[j]=ringbuffer2[j]=null}}if(quads){context.tempQuadIndexBuffer=GLctx.createBuffer();context.GLctx.bindBuffer(34963,context.tempQuadIndexBuffer);var numIndexes=GL.MAX_TEMP_BUFFER_SIZE>>1;var quadIndexes=new Uint16Array(numIndexes);var i=0,v=0;while(1){quadIndexes[i++]=v;if(i>=numIndexes)break;quadIndexes[i++]=v+1;if(i>=numIndexes)break;quadIndexes[i++]=v+2;if(i>=numIndexes)break;quadIndexes[i++]=v;if(i>=numIndexes)break;quadIndexes[i++]=v+2;if(i>=numIndexes)break;quadIndexes[i++]=v+3;if(i>=numIndexes)break;v+=4}context.GLctx.bufferData(34963,quadIndexes,35044);context.GLctx.bindBuffer(34963,null)}},getTempVertexBuffer:sizeBytes=>{var idx=GL.log2ceilLookup(sizeBytes);var ringbuffer=GL.currentContext.tempVertexBuffers1[idx];var nextFreeBufferIndex=GL.currentContext.tempVertexBufferCounters1[idx];GL.currentContext.tempVertexBufferCounters1[idx]=GL.currentContext.tempVertexBufferCounters1[idx]+1&GL.numTempVertexBuffersPerSize-1;var vbo=ringbuffer[nextFreeBufferIndex];if(vbo){return vbo}var prevVBO=GLctx.getParameter(34964);ringbuffer[nextFreeBufferIndex]=GLctx.createBuffer();GLctx.bindBuffer(34962,ringbuffer[nextFreeBufferIndex]);GLctx.bufferData(34962,1<<idx,35048);GLctx.bindBuffer(34962,prevVBO);return ringbuffer[nextFreeBufferIndex]},getTempIndexBuffer:sizeBytes=>{var idx=GL.log2ceilLookup(sizeBytes);var ibo=GL.currentContext.tempIndexBuffers[idx];if(ibo){return ibo}var prevIBO=GLctx.getParameter(34965);GL.currentContext.tempIndexBuffers[idx]=GLctx.createBuffer();GLctx.bindBuffer(34963,GL.currentContext.tempIndexBuffers[idx]);GLctx.bufferData(34963,1<<idx,35048);GLctx.bindBuffer(34963,prevIBO);return GL.currentContext.tempIndexBuffers[idx]},newRenderingFrameStarted:()=>{if(!GL.currentContext){return}var vb=GL.currentContext.tempVertexBuffers1;GL.currentContext.tempVertexBuffers1=GL.currentContext.tempVertexBuffers2;GL.currentContext.tempVertexBuffers2=vb;vb=GL.currentContext.tempVertexBufferCounters1;GL.currentContext.tempVertexBufferCounters1=GL.currentContext.tempVertexBufferCounters2;GL.currentContext.tempVertexBufferCounters2=vb;var largestIndex=GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);for(var i=0;i<=largestIndex;++i){GL.currentContext.tempVertexBufferCounters1[i]=0}},getSource:(shader,count,string,length)=>{var source="";for(var i=0;i<count;++i){var len=length?HEAPU32[length+i*4>>2]:undefined;source+=UTF8ToString(HEAPU32[string+i*4>>2],len)}return source},calcBufLength:(size,type,stride,count)=>{if(stride>0){return count*stride}var typeSize=GL.byteSizeByType[type-GL.byteSizeByTypeRoot];return size*typeSize*count},usedTempBuffers:[],preDrawHandleClientVertexAttribBindings:count=>{GL.resetBufferBinding=false;for(var i=0;i<GL.currentContext.maxVertexAttribs;++i){var cb=GL.currentContext.clientBuffers[i];if(!cb.clientside||!cb.enabled)continue;GL.resetBufferBinding=true;var size=GL.calcBufLength(cb.size,cb.type,cb.stride,count);var buf=GL.getTempVertexBuffer(size);GLctx.bindBuffer(34962,buf);GLctx.bufferSubData(34962,0,HEAPU8.subarray(cb.ptr,cb.ptr+size));cb.vertexAttribPointerAdaptor.call(GLctx,i,cb.size,cb.type,cb.normalized,cb.stride,0)}},postDrawHandleClientVertexAttribBindings:()=>{if(GL.resetBufferBinding){GLctx.bindBuffer(34962,GL.buffers[GLctx.currentArrayBufferBinding])}},createContext:(canvas,webGLContextAttributes)=>{if(!canvas.getContextSafariWebGL2Fixed){canvas.getContextSafariWebGL2Fixed=canvas.getContext;function fixedGetContext(ver,attrs){var gl=canvas.getContextSafariWebGL2Fixed(ver,attrs);return ver=="webgl"==gl instanceof WebGLRenderingContext?gl:null}canvas.getContext=fixedGetContext}var ctx=webGLContextAttributes.majorVersion>1?canvas.getContext("webgl2",webGLContextAttributes):canvas.getContext("webgl",webGLContextAttributes);if(!ctx)return 0;var handle=GL.registerContext(ctx,webGLContextAttributes);return handle},registerContext:(ctx,webGLContextAttributes)=>{var handle=GL.getNewId(GL.contexts);var context={handle,attributes:webGLContextAttributes,version:webGLContextAttributes.majorVersion,GLctx:ctx};if(ctx.canvas)ctx.canvas.GLctxObject=context;GL.contexts[handle]=context;if(typeof webGLContextAttributes.enableExtensionsByDefault=="undefined"||webGLContextAttributes.enableExtensionsByDefault){GL.initExtensions(context)}context.maxVertexAttribs=context.GLctx.getParameter(34921);context.clientBuffers=[];for(var i=0;i<context.maxVertexAttribs;i++){context.clientBuffers[i]={enabled:false,clientside:false,size:0,type:0,normalized:0,stride:0,ptr:0,vertexAttribPointerAdaptor:null}}GL.generateTempBuffers(false,context);return handle},makeContextCurrent:contextHandle=>{GL.currentContext=GL.contexts[contextHandle];Module["ctx"]=GLctx=GL.currentContext?.GLctx;return!(contextHandle&&!GLctx)},getContext:contextHandle=>GL.contexts[contextHandle],deleteContext:contextHandle=>{if(GL.currentContext===GL.contexts[contextHandle]){GL.currentContext=null}if(typeof JSEvents=="object"){JSEvents.removeAllHandlersOnTarget(GL.contexts[contextHandle].GLctx.canvas)}if(GL.contexts[contextHandle]?.GLctx.canvas){GL.contexts[contextHandle].GLctx.canvas.GLctxObject=undefined}GL.contexts[contextHandle]=null},initExtensions:context=>{context||=GL.currentContext;if(context.initExtensionsDone)return;context.initExtensionsDone=true;var GLctx=context.GLctx;webgl_enable_WEBGL_multi_draw(GLctx);webgl_enable_EXT_polygon_offset_clamp(GLctx);webgl_enable_EXT_clip_control(GLctx);webgl_enable_WEBGL_polygon_mode(GLctx);webgl_enable_ANGLE_instanced_arrays(GLctx);webgl_enable_OES_vertex_array_object(GLctx);webgl_enable_WEBGL_draw_buffers(GLctx);webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance(GLctx);webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance(GLctx);if(context.version>=2){GLctx.disjointTimerQueryExt=GLctx.getExtension("EXT_disjoint_timer_query_webgl2")}if(context.version<2||!GLctx.disjointTimerQueryExt){GLctx.disjointTimerQueryExt=GLctx.getExtension("EXT_disjoint_timer_query")}for(var ext of getEmscriptenSupportedExtensions(GLctx)){if(!ext.includes("lose_context")&&!ext.includes("debug")){GLctx.getExtension(ext)}}}};var webglPowerPreferences=["default","low-power","high-performance"];var maybeCStringToJsString=cString=>cString>2?UTF8ToString(cString):cString;var specialHTMLTargets=[0,document,window];var findEventTarget=target=>{target=maybeCStringToJsString(target);var domElement=specialHTMLTargets[target]||document.querySelector(target);return domElement};var findCanvasEventTarget=findEventTarget;var _emscripten_webgl_do_create_context=(target,attributes)=>{var attr32=attributes>>2;var powerPreference=HEAP32[attr32+(8>>2)];var contextAttributes={alpha:!!HEAP8[attributes+0],depth:!!HEAP8[attributes+1],stencil:!!HEAP8[attributes+2],antialias:!!HEAP8[attributes+3],premultipliedAlpha:!!HEAP8[attributes+4],preserveDrawingBuffer:!!HEAP8[attributes+5],powerPreference:webglPowerPreferences[powerPreference],failIfMajorPerformanceCaveat:!!HEAP8[attributes+12],majorVersion:HEAP32[attr32+(16>>2)],minorVersion:HEAP32[attr32+(20>>2)],enableExtensionsByDefault:HEAP8[attributes+24],explicitSwapControl:HEAP8[attributes+25],proxyContextToMainThread:HEAP32[attr32+(28>>2)],renderViaOffscreenBackBuffer:HEAP8[attributes+32]};var canvas=findCanvasEventTarget(target);if(!canvas){return 0}if(contextAttributes.explicitSwapControl){return 0}var contextHandle=GL.createContext(canvas,contextAttributes);return contextHandle};var _emscripten_webgl_create_context=_emscripten_webgl_do_create_context;var _emscripten_webgl_destroy_context=contextHandle=>{if(GL.currentContext==contextHandle)GL.currentContext=0;GL.deleteContext(contextHandle)};var _emscripten_webgl_make_context_current=contextHandle=>{var success=GL.makeContextCurrent(contextHandle);return success?0:-5};var ENV={};var getExecutableName=()=>thisProgram||"./this.program";var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8";var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:lang,_:getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(`${x}=${env[x]}`)}getEnvStrings.strings=strings}return getEnvStrings.strings};var _environ_get=(__environ,environ_buf)=>{var bufSize=0;var envp=0;for(var string of getEnvStrings()){var ptr=environ_buf+bufSize;HEAPU32[__environ+envp>>2]=ptr;bufSize+=stringToUTF8(string,ptr,Infinity)+1;envp+=4}return 0};var _environ_sizes_get=(penviron_count,penviron_buf_size)=>{var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;for(var string of strings){bufSize+=lengthBytesUTF8(string)+1}HEAPU32[penviron_buf_size>>2]=bufSize;return 0};function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doReadv=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len)break;if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_read(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doReadv(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}function _fd_seek(fd,offset,whence,newOffset){offset=bigintToI53Checked(offset);try{if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);HEAP64[newOffset>>3]=BigInt(stream.position);if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doWritev=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len){break}if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_write(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doWritev(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var _emscripten_glActiveTexture=x0=>GLctx.activeTexture(x0);var _glActiveTexture=_emscripten_glActiveTexture;var _emscripten_glAttachShader=(program,shader)=>{GLctx.attachShader(GL.programs[program],GL.shaders[shader])};var _glAttachShader=_emscripten_glAttachShader;var _emscripten_glBindAttribLocation=(program,index,name)=>{GLctx.bindAttribLocation(GL.programs[program],index,UTF8ToString(name))};var _glBindAttribLocation=_emscripten_glBindAttribLocation;var _emscripten_glBindBuffer=(target,buffer)=>{if(buffer&&!GL.buffers[buffer]){var b=GLctx.createBuffer();b.name=buffer;GL.buffers[buffer]=b}if(target==34962){GLctx.currentArrayBufferBinding=buffer}else if(target==34963){GLctx.currentElementArrayBufferBinding=buffer}if(target==35051){GLctx.currentPixelPackBufferBinding=buffer}else if(target==35052){GLctx.currentPixelUnpackBufferBinding=buffer}GLctx.bindBuffer(target,GL.buffers[buffer])};var _glBindBuffer=_emscripten_glBindBuffer;var _emscripten_glBindFramebuffer=(target,framebuffer)=>{GLctx.bindFramebuffer(target,GL.framebuffers[framebuffer])};var _glBindFramebuffer=_emscripten_glBindFramebuffer;var _emscripten_glBindTexture=(target,texture)=>{GLctx.bindTexture(target,GL.textures[texture])};var _glBindTexture=_emscripten_glBindTexture;var _emscripten_glBindVertexArray=vao=>{GLctx.bindVertexArray(GL.vaos[vao]);var ibo=GLctx.getParameter(34965);GLctx.currentElementArrayBufferBinding=ibo?ibo.name|0:0};var _glBindVertexArray=_emscripten_glBindVertexArray;var _emscripten_glBlendFunc=(x0,x1)=>GLctx.blendFunc(x0,x1);var _glBlendFunc=_emscripten_glBlendFunc;var _emscripten_glBlendFuncSeparate=(x0,x1,x2,x3)=>GLctx.blendFuncSeparate(x0,x1,x2,x3);var _glBlendFuncSeparate=_emscripten_glBlendFuncSeparate;var _emscripten_glBufferData=(target,size,data,usage)=>{if(GL.currentContext.version>=2){if(data&&size){GLctx.bufferData(target,HEAPU8,usage,data,size)}else{GLctx.bufferData(target,size,usage)}return}GLctx.bufferData(target,data?HEAPU8.subarray(data,data+size):size,usage)};var _glBufferData=_emscripten_glBufferData;var _emscripten_glBufferSubData=(target,offset,size,data)=>{if(GL.currentContext.version>=2){size&&GLctx.bufferSubData(target,offset,HEAPU8,data,size);return}GLctx.bufferSubData(target,offset,HEAPU8.subarray(data,data+size))};var _glBufferSubData=_emscripten_glBufferSubData;var _emscripten_glCheckFramebufferStatus=x0=>GLctx.checkFramebufferStatus(x0);var _glCheckFramebufferStatus=_emscripten_glCheckFramebufferStatus;var _emscripten_glClear=x0=>GLctx.clear(x0);var _glClear=_emscripten_glClear;var _emscripten_glClearColor=(x0,x1,x2,x3)=>GLctx.clearColor(x0,x1,x2,x3);var _glClearColor=_emscripten_glClearColor;var _emscripten_glClearStencil=x0=>GLctx.clearStencil(x0);var _glClearStencil=_emscripten_glClearStencil;var _emscripten_glColorMask=(red,green,blue,alpha)=>{GLctx.colorMask(!!red,!!green,!!blue,!!alpha)};var _glColorMask=_emscripten_glColorMask;var _emscripten_glCompileShader=shader=>{GLctx.compileShader(GL.shaders[shader])};var _glCompileShader=_emscripten_glCompileShader;var _emscripten_glCreateProgram=()=>{var id=GL.getNewId(GL.programs);var program=GLctx.createProgram();program.name=id;program.maxUniformLength=program.maxAttributeLength=program.maxUniformBlockNameLength=0;program.uniformIdCounter=1;GL.programs[id]=program;return id};var _glCreateProgram=_emscripten_glCreateProgram;var _emscripten_glCreateShader=shaderType=>{var id=GL.getNewId(GL.shaders);GL.shaders[id]=GLctx.createShader(shaderType);return id};var _glCreateShader=_emscripten_glCreateShader;var _emscripten_glDeleteBuffers=(n,buffers)=>{for(var i=0;i<n;i++){var id=HEAP32[buffers+i*4>>2];var buffer=GL.buffers[id];if(!buffer)continue;GLctx.deleteBuffer(buffer);buffer.name=0;GL.buffers[id]=null;if(id==GLctx.currentArrayBufferBinding)GLctx.currentArrayBufferBinding=0;if(id==GLctx.currentElementArrayBufferBinding)GLctx.currentElementArrayBufferBinding=0;if(id==GLctx.currentPixelPackBufferBinding)GLctx.currentPixelPackBufferBinding=0;if(id==GLctx.currentPixelUnpackBufferBinding)GLctx.currentPixelUnpackBufferBinding=0}};var _glDeleteBuffers=_emscripten_glDeleteBuffers;var _emscripten_glDeleteFramebuffers=(n,framebuffers)=>{for(var i=0;i<n;++i){var id=HEAP32[framebuffers+i*4>>2];var framebuffer=GL.framebuffers[id];if(!framebuffer)continue;GLctx.deleteFramebuffer(framebuffer);framebuffer.name=0;GL.framebuffers[id]=null}};var _glDeleteFramebuffers=_emscripten_glDeleteFramebuffers;var _emscripten_glDeleteProgram=id=>{if(!id)return;var program=GL.programs[id];if(!program){GL.recordError(1281);return}GLctx.deleteProgram(program);program.name=0;GL.programs[id]=null};var _glDeleteProgram=_emscripten_glDeleteProgram;var _emscripten_glDeleteShader=id=>{if(!id)return;var shader=GL.shaders[id];if(!shader){GL.recordError(1281);return}GLctx.deleteShader(shader);GL.shaders[id]=null};var _glDeleteShader=_emscripten_glDeleteShader;var _emscripten_glDeleteTextures=(n,textures)=>{for(var i=0;i<n;i++){var id=HEAP32[textures+i*4>>2];var texture=GL.textures[id];if(!texture)continue;GLctx.deleteTexture(texture);texture.name=0;GL.textures[id]=null}};var _glDeleteTextures=_emscripten_glDeleteTextures;var _emscripten_glDeleteVertexArrays=(n,vaos)=>{for(var i=0;i<n;i++){var id=HEAP32[vaos+i*4>>2];GLctx.deleteVertexArray(GL.vaos[id]);GL.vaos[id]=null}};var _glDeleteVertexArrays=_emscripten_glDeleteVertexArrays;var _emscripten_glDisable=x0=>GLctx.disable(x0);var _glDisable=_emscripten_glDisable;var _emscripten_glDrawArrays=(mode,first,count)=>{GL.preDrawHandleClientVertexAttribBindings(first+count);GLctx.drawArrays(mode,first,count);GL.postDrawHandleClientVertexAttribBindings()};var _glDrawArrays=_emscripten_glDrawArrays;var _emscripten_glDrawElements=(mode,count,type,indices)=>{var buf;var vertexes=0;if(!GLctx.currentElementArrayBufferBinding){var size=GL.calcBufLength(1,type,0,count);buf=GL.getTempIndexBuffer(size);GLctx.bindBuffer(34963,buf);GLctx.bufferSubData(34963,0,HEAPU8.subarray(indices,indices+size));if(count>0){for(var i=0;i<GL.currentContext.maxVertexAttribs;++i){var cb=GL.currentContext.clientBuffers[i];if(cb.clientside&&cb.enabled){let arrayClass;switch(type){case 5121:arrayClass=Uint8Array;break;case 5123:arrayClass=Uint16Array;break;case 5125:arrayClass=Uint32Array;break;default:GL.recordError(1282);return}vertexes=new arrayClass(HEAPU8.buffer,indices,count).reduce((max,current)=>Math.max(max,current))+1;break}}}indices=0}GL.preDrawHandleClientVertexAttribBindings(vertexes);GLctx.drawElements(mode,count,type,indices);GL.postDrawHandleClientVertexAttribBindings(count);if(!GLctx.currentElementArrayBufferBinding){GLctx.bindBuffer(34963,null)}};var _glDrawElements=_emscripten_glDrawElements;var _emscripten_glEnable=x0=>GLctx.enable(x0);var _glEnable=_emscripten_glEnable;var _emscripten_glEnableVertexAttribArray=index=>{var cb=GL.currentContext.clientBuffers[index];cb.enabled=true;GLctx.enableVertexAttribArray(index)};var _glEnableVertexAttribArray=_emscripten_glEnableVertexAttribArray;var _emscripten_glFramebufferTexture2D=(target,attachment,textarget,texture,level)=>{GLctx.framebufferTexture2D(target,attachment,textarget,GL.textures[texture],level)};var _glFramebufferTexture2D=_emscripten_glFramebufferTexture2D;var _emscripten_glGenBuffers=(n,buffers)=>{GL.genObject(n,buffers,"createBuffer",GL.buffers)};var _glGenBuffers=_emscripten_glGenBuffers;var _emscripten_glGenFramebuffers=(n,ids)=>{GL.genObject(n,ids,"createFramebuffer",GL.framebuffers)};var _glGenFramebuffers=_emscripten_glGenFramebuffers;var _emscripten_glGenTextures=(n,textures)=>{GL.genObject(n,textures,"createTexture",GL.textures)};var _glGenTextures=_emscripten_glGenTextures;var _emscripten_glGenVertexArrays=(n,arrays)=>{GL.genObject(n,arrays,"createVertexArray",GL.vaos)};var _glGenVertexArrays=_emscripten_glGenVertexArrays;var _emscripten_glGenerateMipmap=x0=>GLctx.generateMipmap(x0);var _glGenerateMipmap=_emscripten_glGenerateMipmap;var _emscripten_glGetAttribLocation=(program,name)=>GLctx.getAttribLocation(GL.programs[program],UTF8ToString(name));var _glGetAttribLocation=_emscripten_glGetAttribLocation;var _emscripten_glGetError=()=>{var error=GLctx.getError()||GL.lastError;GL.lastError=0;return error};var _glGetError=_emscripten_glGetError;var writeI53ToI64=(ptr,num)=>{HEAPU32[ptr>>2]=num;var lower=HEAPU32[ptr>>2];HEAPU32[ptr+4>>2]=(num-lower)/4294967296};var webglGetExtensions=()=>{var exts=getEmscriptenSupportedExtensions(GLctx);exts=exts.concat(exts.map(e=>"GL_"+e));return exts};var emscriptenWebGLGet=(name_,p,type)=>{if(!p){GL.recordError(1281);return}var ret=undefined;switch(name_){case 36346:ret=1;break;case 36344:if(type!=0&&type!=1){GL.recordError(1280)}return;case 34814:case 36345:ret=0;break;case 34466:var formats=GLctx.getParameter(34467);ret=formats?formats.length:0;break;case 33309:if(GL.currentContext.version<2){GL.recordError(1282);return}ret=webglGetExtensions().length;break;case 33307:case 33308:if(GL.currentContext.version<2){GL.recordError(1280);return}ret=name_==33307?3:0;break}if(ret===undefined){var result=GLctx.getParameter(name_);switch(typeof result){case"number":ret=result;break;case"boolean":ret=result?1:0;break;case"string":GL.recordError(1280);return;case"object":if(result===null){switch(name_){case 34964:case 35725:case 34965:case 36006:case 36007:case 32873:case 34229:case 36662:case 36663:case 35053:case 35055:case 36010:case 35097:case 35869:case 32874:case 36389:case 35983:case 35368:case 34068:{ret=0;break}default:{GL.recordError(1280);return}}}else if(result instanceof Float32Array||result instanceof Uint32Array||result instanceof Int32Array||result instanceof Array){for(var i=0;i<result.length;++i){switch(type){case 0:HEAP32[p+i*4>>2]=result[i];break;case 2:HEAPF32[p+i*4>>2]=result[i];break;case 4:HEAP8[p+i]=result[i]?1:0;break}}return}else{try{ret=result.name|0}catch(e){GL.recordError(1280);err(`GL_INVALID_ENUM in glGet${type}v: Unknown object returned from WebGL getParameter(${name_})! (error: ${e})`);return}}break;default:GL.recordError(1280);err(`GL_INVALID_ENUM in glGet${type}v: Native code calling glGet${type}v(${name_}) and it returns ${result} of type ${typeof result}!`);return}}switch(type){case 1:writeI53ToI64(p,ret);break;case 0:HEAP32[p>>2]=ret;break;case 2:HEAPF32[p>>2]=ret;break;case 4:HEAP8[p]=ret?1:0;break}};var _emscripten_glGetIntegerv=(name_,p)=>emscriptenWebGLGet(name_,p,0);var _glGetIntegerv=_emscripten_glGetIntegerv;var _emscripten_glGetProgramInfoLog=(program,maxLength,length,infoLog)=>{var log=GLctx.getProgramInfoLog(GL.programs[program]);if(log===null)log="(unknown error)";var numBytesWrittenExclNull=maxLength>0&&infoLog?stringToUTF8(log,infoLog,maxLength):0;if(length)HEAP32[length>>2]=numBytesWrittenExclNull};var _glGetProgramInfoLog=_emscripten_glGetProgramInfoLog;var _emscripten_glGetProgramiv=(program,pname,p)=>{if(!p){GL.recordError(1281);return}if(program>=GL.counter){GL.recordError(1281);return}program=GL.programs[program];if(pname==35716){var log=GLctx.getProgramInfoLog(program);if(log===null)log="(unknown error)";HEAP32[p>>2]=log.length+1}else if(pname==35719){if(!program.maxUniformLength){var numActiveUniforms=GLctx.getProgramParameter(program,35718);for(var i=0;i<numActiveUniforms;++i){program.maxUniformLength=Math.max(program.maxUniformLength,GLctx.getActiveUniform(program,i).name.length+1)}}HEAP32[p>>2]=program.maxUniformLength}else if(pname==35722){if(!program.maxAttributeLength){var numActiveAttributes=GLctx.getProgramParameter(program,35721);for(var i=0;i<numActiveAttributes;++i){program.maxAttributeLength=Math.max(program.maxAttributeLength,GLctx.getActiveAttrib(program,i).name.length+1)}}HEAP32[p>>2]=program.maxAttributeLength}else if(pname==35381){if(!program.maxUniformBlockNameLength){var numActiveUniformBlocks=GLctx.getProgramParameter(program,35382);for(var i=0;i<numActiveUniformBlocks;++i){program.maxUniformBlockNameLength=Math.max(program.maxUniformBlockNameLength,GLctx.getActiveUniformBlockName(program,i).length+1)}}HEAP32[p>>2]=program.maxUniformBlockNameLength}else{HEAP32[p>>2]=GLctx.getProgramParameter(program,pname)}};var _glGetProgramiv=_emscripten_glGetProgramiv;var _emscripten_glGetShaderInfoLog=(shader,maxLength,length,infoLog)=>{var log=GLctx.getShaderInfoLog(GL.shaders[shader]);if(log===null)log="(unknown error)";var numBytesWrittenExclNull=maxLength>0&&infoLog?stringToUTF8(log,infoLog,maxLength):0;if(length)HEAP32[length>>2]=numBytesWrittenExclNull};var _glGetShaderInfoLog=_emscripten_glGetShaderInfoLog;var _emscripten_glGetShaderiv=(shader,pname,p)=>{if(!p){GL.recordError(1281);return}if(pname==35716){var log=GLctx.getShaderInfoLog(GL.shaders[shader]);if(log===null)log="(unknown error)";var logLength=log?log.length+1:0;HEAP32[p>>2]=logLength}else if(pname==35720){var source=GLctx.getShaderSource(GL.shaders[shader]);var sourceLength=source?source.length+1:0;HEAP32[p>>2]=sourceLength}else{HEAP32[p>>2]=GLctx.getShaderParameter(GL.shaders[shader],pname)}};var _glGetShaderiv=_emscripten_glGetShaderiv;var stringToNewUTF8=str=>{var size=lengthBytesUTF8(str)+1;var ret=_malloc(size);if(ret)stringToUTF8(str,ret,size);return ret};var _emscripten_glGetString=name_=>{var ret=GL.stringCache[name_];if(!ret){switch(name_){case 7939:ret=stringToNewUTF8(webglGetExtensions().join(" "));break;case 7936:case 7937:case 37445:case 37446:var s=GLctx.getParameter(name_);if(!s){GL.recordError(1280)}ret=s?stringToNewUTF8(s):0;break;case 7938:var webGLVersion=GLctx.getParameter(7938);var glVersion=`OpenGL ES 2.0 (${webGLVersion})`;if(GL.currentContext.version>=2)glVersion=`OpenGL ES 3.0 (${webGLVersion})`;ret=stringToNewUTF8(glVersion);break;case 35724:var glslVersion=GLctx.getParameter(35724);var ver_re=/^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/;var ver_num=glslVersion.match(ver_re);if(ver_num!==null){if(ver_num[1].length==3)ver_num[1]=ver_num[1]+"0";glslVersion=`OpenGL ES GLSL ES ${ver_num[1]} (${glslVersion})`}ret=stringToNewUTF8(glslVersion);break;default:GL.recordError(1280)}GL.stringCache[name_]=ret}return ret};var _glGetString=_emscripten_glGetString;var jstoi_q=str=>parseInt(str);var webglGetLeftBracePos=name=>name.slice(-1)=="]"&&name.lastIndexOf("[");var webglPrepareUniformLocationsBeforeFirstUse=program=>{var uniformLocsById=program.uniformLocsById,uniformSizeAndIdsByName=program.uniformSizeAndIdsByName,i,j;if(!uniformLocsById){program.uniformLocsById=uniformLocsById={};program.uniformArrayNamesById={};var numActiveUniforms=GLctx.getProgramParameter(program,35718);for(i=0;i<numActiveUniforms;++i){var u=GLctx.getActiveUniform(program,i);var nm=u.name;var sz=u.size;var lb=webglGetLeftBracePos(nm);var arrayName=lb>0?nm.slice(0,lb):nm;var id=program.uniformIdCounter;program.uniformIdCounter+=sz;uniformSizeAndIdsByName[arrayName]=[sz,id];for(j=0;j<sz;++j){uniformLocsById[id]=j;program.uniformArrayNamesById[id++]=arrayName}}}};var _emscripten_glGetUniformLocation=(program,name)=>{name=UTF8ToString(name);if(program=GL.programs[program]){webglPrepareUniformLocationsBeforeFirstUse(program);var uniformLocsById=program.uniformLocsById;var arrayIndex=0;var uniformBaseName=name;var leftBrace=webglGetLeftBracePos(name);if(leftBrace>0){arrayIndex=jstoi_q(name.slice(leftBrace+1))>>>0;uniformBaseName=name.slice(0,leftBrace)}var sizeAndId=program.uniformSizeAndIdsByName[uniformBaseName];if(sizeAndId&&arrayIndex<sizeAndId[0]){arrayIndex+=sizeAndId[1];if(uniformLocsById[arrayIndex]=uniformLocsById[arrayIndex]||GLctx.getUniformLocation(program,name)){return arrayIndex}}}else{GL.recordError(1281)}return-1};var _glGetUniformLocation=_emscripten_glGetUniformLocation;var _emscripten_glLinkProgram=program=>{program=GL.programs[program];GLctx.linkProgram(program);program.uniformLocsById=0;program.uniformSizeAndIdsByName={}};var _glLinkProgram=_emscripten_glLinkProgram;var _emscripten_glPixelStorei=(pname,param)=>{if(pname==3317){GL.unpackAlignment=param}else if(pname==3314){GL.unpackRowLength=param}GLctx.pixelStorei(pname,param)};var _glPixelStorei=_emscripten_glPixelStorei;var _emscripten_glScissor=(x0,x1,x2,x3)=>GLctx.scissor(x0,x1,x2,x3);var _glScissor=_emscripten_glScissor;var _emscripten_glShaderSource=(shader,count,string,length)=>{var source=GL.getSource(shader,count,string,length);GLctx.shaderSource(GL.shaders[shader],source)};var _glShaderSource=_emscripten_glShaderSource;var _emscripten_glStencilFunc=(x0,x1,x2)=>GLctx.stencilFunc(x0,x1,x2);var _glStencilFunc=_emscripten_glStencilFunc;var _emscripten_glStencilMask=x0=>GLctx.stencilMask(x0);var _glStencilMask=_emscripten_glStencilMask;var _emscripten_glStencilOp=(x0,x1,x2)=>GLctx.stencilOp(x0,x1,x2);var _glStencilOp=_emscripten_glStencilOp;var computeUnpackAlignedImageSize=(width,height,sizePerPixel)=>{function roundedToNextMultipleOf(x,y){return x+y-1&-y}var plainRowSize=(GL.unpackRowLength||width)*sizePerPixel;var alignedRowSize=roundedToNextMultipleOf(plainRowSize,GL.unpackAlignment);return height*alignedRowSize};var colorChannelsInGlTextureFormat=format=>{var colorChannels={5:3,6:4,8:2,29502:3,29504:4,26917:2,26918:2,29846:3,29847:4};return colorChannels[format-6402]||1};var heapObjectForWebGLType=type=>{type-=5120;if(type==0)return HEAP8;if(type==1)return HEAPU8;if(type==2)return HEAP16;if(type==4)return HEAP32;if(type==6)return HEAPF32;if(type==5||type==28922||type==28520||type==30779||type==30782)return HEAPU32;return HEAPU16};var toTypedArrayIndex=(pointer,heap)=>pointer>>>31-Math.clz32(heap.BYTES_PER_ELEMENT);var emscriptenWebGLGetTexPixelData=(type,format,width,height,pixels,internalFormat)=>{var heap=heapObjectForWebGLType(type);var sizePerPixel=colorChannelsInGlTextureFormat(format)*heap.BYTES_PER_ELEMENT;var bytes=computeUnpackAlignedImageSize(width,height,sizePerPixel);return heap.subarray(toTypedArrayIndex(pixels,heap),toTypedArrayIndex(pixels+bytes,heap))};var _emscripten_glTexImage2D=(target,level,internalFormat,width,height,border,format,type,pixels)=>{if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding){GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,pixels);return}if(pixels){var heap=heapObjectForWebGLType(type);var index=toTypedArrayIndex(pixels,heap);GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,heap,index);return}}var pixelData=pixels?emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,internalFormat):null;GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,pixelData)};var _glTexImage2D=_emscripten_glTexImage2D;var _emscripten_glTexParameteri=(x0,x1,x2)=>GLctx.texParameteri(x0,x1,x2);var _glTexParameteri=_emscripten_glTexParameteri;var _emscripten_glTexSubImage2D=(target,level,xoffset,yoffset,width,height,format,type,pixels)=>{if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding){GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixels);return}if(pixels){var heap=heapObjectForWebGLType(type);GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,heap,toTypedArrayIndex(pixels,heap));return}}var pixelData=pixels?emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,0):null;GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixelData)};var _glTexSubImage2D=_emscripten_glTexSubImage2D;var webglGetUniformLocation=location=>{var p=GLctx.currentProgram;if(p){var webglLoc=p.uniformLocsById[location];if(typeof webglLoc=="number"){p.uniformLocsById[location]=webglLoc=GLctx.getUniformLocation(p,p.uniformArrayNamesById[location]+(webglLoc>0?`[${webglLoc}]`:""))}return webglLoc}else{GL.recordError(1282)}};var _emscripten_glUniform1f=(location,v0)=>{GLctx.uniform1f(webglGetUniformLocation(location),v0)};var _glUniform1f=_emscripten_glUniform1f;var _emscripten_glUniform1i=(location,v0)=>{GLctx.uniform1i(webglGetUniformLocation(location),v0)};var _glUniform1i=_emscripten_glUniform1i;var _emscripten_glUniform2f=(location,v0,v1)=>{GLctx.uniform2f(webglGetUniformLocation(location),v0,v1)};var _glUniform2f=_emscripten_glUniform2f;var _emscripten_glUniform3f=(location,v0,v1,v2)=>{GLctx.uniform3f(webglGetUniformLocation(location),v0,v1,v2)};var _glUniform3f=_emscripten_glUniform3f;var _emscripten_glUniform4f=(location,v0,v1,v2,v3)=>{GLctx.uniform4f(webglGetUniformLocation(location),v0,v1,v2,v3)};var _glUniform4f=_emscripten_glUniform4f;var miniTempWebGLFloatBuffers=[];var _emscripten_glUniformMatrix4fv=(location,count,transpose,value)=>{if(GL.currentContext.version>=2){count&&GLctx.uniformMatrix4fv(webglGetUniformLocation(location),!!transpose,HEAPF32,value>>2,count*16);return}if(count<=18){var view=miniTempWebGLFloatBuffers[16*count];var heap=HEAPF32;value=value>>2;count*=16;for(var i=0;i<count;i+=16){var dst=value+i;view[i]=heap[dst];view[i+1]=heap[dst+1];view[i+2]=heap[dst+2];view[i+3]=heap[dst+3];view[i+4]=heap[dst+4];view[i+5]=heap[dst+5];view[i+6]=heap[dst+6];view[i+7]=heap[dst+7];view[i+8]=heap[dst+8];view[i+9]=heap[dst+9];view[i+10]=heap[dst+10];view[i+11]=heap[dst+11];view[i+12]=heap[dst+12];view[i+13]=heap[dst+13];view[i+14]=heap[dst+14];view[i+15]=heap[dst+15]}}else{var view=HEAPF32.subarray(value>>2,value+count*64>>2)}GLctx.uniformMatrix4fv(webglGetUniformLocation(location),!!transpose,view)};var _glUniformMatrix4fv=_emscripten_glUniformMatrix4fv;var _emscripten_glUseProgram=program=>{program=GL.programs[program];GLctx.useProgram(program);GLctx.currentProgram=program};var _glUseProgram=_emscripten_glUseProgram;var _emscripten_glVertexAttribPointer=(index,size,type,normalized,stride,ptr)=>{var cb=GL.currentContext.clientBuffers[index];if(!GLctx.currentArrayBufferBinding){cb.size=size;cb.type=type;cb.normalized=normalized;cb.stride=stride;cb.ptr=ptr;cb.clientside=true;cb.vertexAttribPointerAdaptor=function(index,size,type,normalized,stride,ptr){this.vertexAttribPointer(index,size,type,normalized,stride,ptr)};return}cb.clientside=false;GLctx.vertexAttribPointer(index,size,type,!!normalized,stride,ptr)};var _glVertexAttribPointer=_emscripten_glVertexAttribPointer;var _emscripten_glViewport=(x0,x1,x2,x3)=>GLctx.viewport(x0,x1,x2,x3);var _glViewport=_emscripten_glViewport;var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func(...cArgs);function onDone(ret){if(stack!==0)stackRestore(stack);return convertReturnValue(ret)}ret=onDone(ret);return ret};var cwrap=(ident,returnType,argTypes,opts)=>{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};var FS_createPath=(...args)=>FS.createPath(...args);var FS_unlink=(...args)=>FS.unlink(...args);var FS_createLazyFile=(...args)=>FS.createLazyFile(...args);var FS_createDevice=(...args)=>FS.createDevice(...args);FS.createPreloadedFile=FS_createPreloadedFile;FS.preloadFile=FS_preloadFile;FS.staticInit();init_ClassHandle();init_RegisteredPointer();registerPreMainLoop(()=>GL.newRenderingFrameStarted());var miniTempWebGLFloatBuffersStorage=new Float32Array(288);for(var i=0;i<=288;++i){miniTempWebGLFloatBuffers[i]=miniTempWebGLFloatBuffersStorage.subarray(0,i)}{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["preloadPlugins"])preloadPlugins=Module["preloadPlugins"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["addRunDependency"]=addRunDependency;Module["removeRunDependency"]=removeRunDependency;Module["ccall"]=ccall;Module["cwrap"]=cwrap;Module["FS_preloadFile"]=FS_preloadFile;Module["FS_unlink"]=FS_unlink;Module["FS_createPath"]=FS_createPath;Module["FS_createDevice"]=FS_createDevice;Module["FS"]=FS;Module["FS_createDataFile"]=FS_createDataFile;Module["FS_createLazyFile"]=FS_createLazyFile;Module["GL"]=GL;function callMaterialProvider(materialId,outShaderIdPtr,outBlendModePtr,outUniformBufPtr,outUniformCountPtr){var fn=Module["materialDataProvider"];if(fn){fn(materialId,outShaderIdPtr,outBlendModePtr,outUniformBufPtr,outUniformCountPtr)}else{HEAPU32[outShaderIdPtr>>2]=0;HEAPU32[outBlendModePtr>>2]=0;HEAPU32[outUniformBufPtr>>2]=0;HEAPU32[outUniformCountPtr>>2]=0}}var ___getTypeName,_malloc,_free,__emscripten_timeout,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,memory,__indirect_function_table,wasmMemory,wasmTable;function assignWasmExports(wasmExports){___getTypeName=wasmExports["gb"];_malloc=Module["_malloc"]=wasmExports["hb"];_free=Module["_free"]=wasmExports["ib"];__emscripten_timeout=wasmExports["jb"];__emscripten_stack_restore=wasmExports["lb"];__emscripten_stack_alloc=wasmExports["mb"];_emscripten_stack_get_current=wasmExports["nb"];memory=wasmMemory=wasmExports["eb"];__indirect_function_table=wasmTable=wasmExports["kb"]}var wasmImports={Aa:___syscall_fcntl64,ab:___syscall_ioctl,bb:___syscall_openat,Ea:__abort_js,h:__embind_finalize_value_object,xa:__embind_register_bigint,Sa:__embind_register_bool,ca:__embind_register_class,ta:__embind_register_class_constructor,c:__embind_register_class_function,Qa:__embind_register_emval,E:__embind_register_enum,f:__embind_register_enum_value,wa:__embind_register_float,b:__embind_register_function,G:__embind_register_integer,Ma:__embind_register_iterable,l:__embind_register_memory_view,Na:__embind_register_optional,Ra:__embind_register_std_string,ha:__embind_register_std_wstring,g:__embind_register_value_object,a:__embind_register_value_object_field,Ta:__embind_register_void,Va:__emscripten_runtime_keepalive_clear,N:__emval_create_invoker,C:__emval_decref,M:__emval_invoke,ua:__emval_new_array,X:__emval_new_cstring,va:__emval_new_object,L:__emval_run_destructors,Q:__emval_set_property,Wa:__setitimer_js,Xa:__tzset_js,db:callMaterialProvider,Ba:_clock_time_get,Ca:_emscripten_resize_heap,cb:_emscripten_webgl_create_context,Pa:_emscripten_webgl_destroy_context,ya:_emscripten_webgl_make_context_current,Ya:_environ_get,Za:_environ_sizes_get,za:_fd_close,$a:_fd_read,_a:_fd_seek,Da:_fd_write,u:_glActiveTexture,na:_glAttachShader,Ka:_glBindAttribLocation,d:_glBindBuffer,z:_glBindFramebuffer,m:_glBindTexture,j:_glBindVertexArray,da:_glBlendFunc,y:_glBlendFuncSeparate,o:_glBufferData,A:_glBufferSubData,Fa:_glCheckFramebufferStatus,J:_glClear,ga:_glClearColor,Oa:_glClearStencil,O:_glColorMask,pa:_glCompileShader,La:_glCreateProgram,ra:_glCreateShader,p:_glDeleteBuffers,s:_glDeleteFramebuffers,sa:_glDeleteProgram,I:_glDeleteShader,e:_glDeleteTextures,R:_glDeleteVertexArrays,n:_glDisable,V:_glDrawArrays,F:_glDrawElements,r:_glEnable,x:_glEnableVertexAttribArray,ia:_glFramebufferTexture2D,t:_glGenBuffers,Ga:_glGenFramebuffers,U:_glGenTextures,H:_glGenVertexArrays,Ha:_glGenerateMipmap,_:_glGetAttribLocation,P:_glGetError,ea:_glGetIntegerv,Ia:_glGetProgramInfoLog,ma:_glGetProgramiv,oa:_glGetShaderInfoLog,S:_glGetShaderiv,W:_glGetString,i:_glGetUniformLocation,Ja:_glLinkProgram,ka:_glPixelStorei,fa:_glScissor,qa:_glShaderSource,Z:_glStencilFunc,v:_glStencilMask,Y:_glStencilOp,T:_glTexImage2D,q:_glTexParameteri,ja:_glTexSubImage2D,ba:_glUniform1f,k:_glUniform1i,aa:_glUniform2f,la:_glUniform3f,$:_glUniform4f,D:_glUniformMatrix4fv,B:_glUseProgram,w:_glVertexAttribPointer,K:_glViewport,Ua:_proc_exit};function run(){if(runDependencies>0){dependenciesFulfilled=run;return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=await (createWasm());run();if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})};return moduleRtn}})();if(typeof exports==="object"&&typeof module==="object"){module.exports=ESEngineModule;module.exports.default=ESEngineModule}else if(typeof define==="function"&&define["amd"])define([],()=>ESEngineModule);diff --git a/editor/src/builder/ArtifactBuilder.ts b/editor/src/builder/ArtifactBuilder.tsindex b93e6380c..37b3f263d 100644--- a/editor/src/builder/ArtifactBuilder.ts+++ b/editor/src/builder/ArtifactBuilder.ts@@ -17,7 +17,7 @@ import { getAssetType, toAddressableType } from '../asset/AssetTypes';import { compileMaterials } from './MaterialCompiler';import { convertPrefabAssetRefs, deserializePrefab } from '../prefab';import type { PrefabData } from '../types/PrefabTypes';-import { toBuildPath, getComponentAssetFieldDescriptors, getComponentDefaults } from 'esengine';+import { toBuildPath, getComponentAssetFieldDescriptors, getComponentDefaults, registerAssetBuildTransform } from 'esengine';import { normalizePath, joinPath, isAbsolutePath, getParentDir } from '../utils/path';import { getEsbuildWasmURL } from '../context/EditorContext';import { getSettingsValue } from '../settings';@@ -407,11 +407,9 @@ export function generateAddressableManifest(return { version: '2.0', groups };}-export function convertPrefabWithResolvedRefs(- prefabContent: string,- artifact: BuildArtifact-): string {- const prefab = deserializePrefab(prefabContent);+function transformPrefab(content: string, context: unknown): string {+ const artifact = context as BuildArtifact;+ const prefab = deserializePrefab(content);const converted = convertPrefabAssetRefs(prefab, (value) => {const resolved = isUUID(value)? (artifact.assetLibrary.getPath(value) ?? value)@@ -422,6 +420,39 @@ export function convertPrefabWithResolvedRefs(return JSON.stringify(converted);}+function transformAnimClip(content: string, context: unknown): string {+ const artifact = context as BuildArtifact;+ const data = JSON.parse(content);+ if (!Array.isArray(data.frames)) return content;+ for (const frame of data.frames) {+ if (typeof frame.texture !== 'string') continue;+ const resolved = isUUID(frame.texture)+ ? (artifact.assetLibrary.getPath(frame.texture) ?? frame.texture)+ : frame.texture;+ const buildPath = toBuildPath(resolved);+ const entry = artifact.atlasResult.frameMap.get(resolved)+ ?? artifact.atlasResult.frameMap.get(buildPath);+ if (entry) {+ frame.texture = `atlas_${entry.page}.png`;+ const page = artifact.atlasResult.pages[entry.page];+ frame.atlasFrame = {+ x: entry.frame.x,+ y: entry.frame.y,+ width: entry.frame.width,+ height: entry.frame.height,+ pageWidth: page.width,+ pageHeight: page.height,+ };+ } else {+ frame.texture = buildPath;+ }+ }+ return JSON.stringify(data);+}++registerAssetBuildTransform('prefab', transformPrefab);+registerAssetBuildTransform('anim-clip', transformAnimClip);+function isAtlasCapable(componentType: string): boolean {const defaults = getComponentDefaults(componentType);if (!defaults) return false;diff --git a/editor/src/builder/PlayableEmitter.ts b/editor/src/builder/PlayableEmitter.tsindex ccb584104..2298fa003 100644--- a/editor/src/builder/PlayableEmitter.ts+++ b/editor/src/builder/PlayableEmitter.ts@@ -11,7 +11,7 @@ import { getEditorContext } from '../context/EditorContext';import { findTsFiles, EDITOR_ONLY_DIRS } from '../scripting/ScriptLoader';import { joinPath, getFileExtension, isAbsolutePath, getParentDir, normalizePath, getProjectDir } from '../utils/path';import { isUUID, getComponentRefFields } from '../asset/AssetLibrary';-import { initializeEsbuild, createBuildVirtualFsPlugin, arrayBufferToBase64, generateAddressableManifest, convertPrefabWithResolvedRefs } from './ArtifactBuilder';+import { initializeEsbuild, createBuildVirtualFsPlugin, arrayBufferToBase64, generateAddressableManifest } from './ArtifactBuilder';import { PLAYABLE_HTML_TEMPLATE } from './templates';import type { NativeFS } from '../types/NativeFS';import { getAssetMimeType, getAssetTypeEntry, toBuildPath } from 'esengine';@@ -354,11 +354,12 @@ const __plugins = [${pluginList}];continue;}- if (entry?.editorType === 'prefab') {+ if (entry?.buildTransform) {+ const transform = entry.buildTransform;pending.push(fs.readFile(joinPath(projectDir, relativePath)).then(content => {if (content) {- const json = convertPrefabWithResolvedRefs(content, artifact);+ const json = transform(content, artifact);assets.set(outputPath, `data:application/json;base64,${btoa(json)}`);}})diff --git a/editor/src/builder/WeChatEmitter.ts b/editor/src/builder/WeChatEmitter.tsindex f900f9c99..d2da73940 100644--- a/editor/src/builder/WeChatEmitter.ts+++ b/editor/src/builder/WeChatEmitter.ts@@ -11,7 +11,7 @@ import { getEditorContext } from '../context/EditorContext';import { findTsFiles, EDITOR_ONLY_DIRS } from '../scripting/ScriptLoader';import { joinPath, getProjectDir } from '../utils/path';import { resolveShaderPath } from '../utils/shader';-import { initializeEsbuild, createBuildVirtualFsPlugin, generateAddressableManifest, convertPrefabWithResolvedRefs } from './ArtifactBuilder';+import { initializeEsbuild, createBuildVirtualFsPlugin, generateAddressableManifest } from './ArtifactBuilder';import { generateWeChatGameJs } from './templates';import type { NativeFS } from '../types/NativeFS';import { getWeChatPackOptions, getAssetTypeEntry, toBuildPath } from 'esengine';@@ -366,10 +366,10 @@ export class WeChatEmitter implements PlatformEmitter {const destDir = destPath.substring(0, destPath.lastIndexOf('/'));await fs.createDirectory(destDir);- if (entry?.editorType === 'prefab') {+ if (entry?.buildTransform) {const content = await fs.readFile(srcPath);if (content) {- const json = convertPrefabWithResolvedRefs(content, artifact);+ const json = entry.buildTransform(content, artifact);await fs.writeFile(destPath, JSON.stringify(JSON.parse(json), null, 2));}continue;diff --git a/editor/src/builder/index.ts b/editor/src/builder/index.tsindex 41b607f61..686348246 100644--- a/editor/src/builder/index.ts+++ b/editor/src/builder/index.ts@@ -5,7 +5,7 @@export { BuildSettingsDialog, showBuildSettingsDialog } from './BuildSettingsDialog';export { BuildService, type BuildResult, type BuildContext, type BuildOptions } from './BuildService';-export { buildArtifact, initializeEsbuild, createBuildVirtualFsPlugin, arrayBufferToBase64, generateAddressableManifest, convertPrefabWithResolvedRefs, type SdkModuleLoader } from './ArtifactBuilder';+export { buildArtifact, initializeEsbuild, createBuildVirtualFsPlugin, arrayBufferToBase64, generateAddressableManifest, type SdkModuleLoader } from './ArtifactBuilder';export { PLAYABLE_HTML_TEMPLATE, generateWeChatGameJs, type WeChatGameJsParams } from './templates';export { BuildCache, type BuildCacheData, type FileHash, type FileChangeResult } from './BuildCache';diff --git a/sdk/src/animation/AnimClipLoader.ts b/sdk/src/animation/AnimClipLoader.tsindex 36e383c56..e4b772c84 100644--- a/sdk/src/animation/AnimClipLoader.ts+++ b/sdk/src/animation/AnimClipLoader.ts@@ -3,18 +3,30 @@* @brief .esanim asset loading and parsing*/-import type { SpriteAnimClip } from './SpriteAnimator';+import type { SpriteAnimClip, SpriteAnimFrame } from './SpriteAnimator';// =============================================================================// .esanim File Format// =============================================================================+export interface AnimClipFrameData {+ texture: string;+ atlasFrame?: {+ x: number;+ y: number;+ width: number;+ height: number;+ pageWidth: number;+ pageHeight: number;+ };+}+export interface AnimClipAssetData {version: string;type: 'animation-clip';fps?: number;loop?: boolean;- frames: { texture: string }[];+ frames: AnimClipFrameData[];}// =============================================================================@@ -42,8 +54,22 @@ export function parseAnimClipData(name: clipPath,fps: data.fps ?? DEFAULT_FPS,loop: data.loop ?? true,- frames: data.frames.map(f => ({- texture: textureHandles.get(f.texture) ?? 0,- })),+ frames: data.frames.map(f => {+ const frame: SpriteAnimFrame = {+ texture: textureHandles.get(f.texture) ?? 0,+ };+ if (f.atlasFrame) {+ const af = f.atlasFrame;+ frame.uvOffset = {+ x: af.x / af.pageWidth,+ y: 1.0 - (af.y + af.height) / af.pageHeight,+ };+ frame.uvScale = {+ x: af.width / af.pageWidth,+ y: af.height / af.pageHeight,+ };+ }+ return frame;+ }),};}diff --git a/sdk/src/animation/SpriteAnimator.ts b/sdk/src/animation/SpriteAnimator.tsindex 03a25329c..0226828b3 100644--- a/sdk/src/animation/SpriteAnimator.ts+++ b/sdk/src/animation/SpriteAnimator.ts@@ -15,6 +15,8 @@ import { Sprite, type SpriteData } from '../component';export interface SpriteAnimFrame {texture: TextureHandle;duration?: number;+ uvOffset?: { x: number; y: number };+ uvScale?: { x: number; y: number };}export interface SpriteAnimClip {@@ -111,6 +113,10 @@ export function spriteAnimatorSystemUpdate(world: World, deltaTime: number): voiconst frame = clip.frames[animator.currentFrame];const sprite = world.get(entity, Sprite) as SpriteData;sprite.texture = frame.texture;+ if (frame.uvOffset) {+ sprite.uvOffset = frame.uvOffset;+ sprite.uvScale = frame.uvScale!;+ }world.insert(entity, Sprite, sprite);}diff --git a/sdk/src/assetTypes.ts b/sdk/src/assetTypes.tsindex 35a35755d..7f9d87196 100644--- a/sdk/src/assetTypes.ts+++ b/sdk/src/assetTypes.ts@@ -8,6 +8,8 @@ export type EditorAssetType =| 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton'| 'bitmap-font' | 'prefab' | 'json' | 'audio' | 'scene' | 'anim-clip' | 'unknown';+export type AssetBuildTransform = (content: string, context: unknown) => string;+export interface AssetTypeEntry {extensions: string[];contentType: AssetContentType;@@ -15,6 +17,7 @@ export interface AssetTypeEntry {addressableType: AddressableAssetType | null;wechatPackInclude: boolean;hasTransitiveDeps: boolean;+ buildTransform?: AssetBuildTransform;}const ASSET_TYPE_REGISTRY: readonly AssetTypeEntry[] = [@@ -141,3 +144,15 @@ export function toBuildPath(path: string): string {const dotIndex = path.lastIndexOf('.');return dotIndex >= 0 ? path.substring(0, dotIndex) + '.json' : path;}++export function registerAssetBuildTransform(editorType: EditorAssetType, transform: AssetBuildTransform): void {+ for (const entry of ASSET_TYPE_REGISTRY) {+ if (entry.editorType === editorType) {+ (entry as AssetTypeEntry).buildTransform = transform;+ }+ }+}++export function getAssetBuildTransform(extensionOrPath: string): AssetBuildTransform | undefined {+ return getAssetTypeEntry(extensionOrPath)?.buildTransform;+}diff --git a/sdk/src/audio/WeChatAudioBackend.ts b/sdk/src/audio/WeChatAudioBackend.tsindex abf04eb69..368478d6e 100644--- a/sdk/src/audio/WeChatAudioBackend.ts+++ b/sdk/src/audio/WeChatAudioBackend.ts@@ -123,7 +123,6 @@ export class WeChatAudioBackend implements PlatformAudioBackend {}const ctx: WxInnerAudioContext = (wx as any).createInnerAudioContext();- ctx.src = url;ctx.loop = config.loop ?? false;ctx.volume = config.volume ?? 1.0;ctx.playbackRate = config.playbackRate ?? 1.0;@@ -141,8 +140,12 @@ export class WeChatAudioBackend implements PlatformAudioBackend {this.contexts_.delete(handleId);}});+ ctx.onError((res) => {+ console.error(`[WeChatAudio] Playback error for "${url}":`, res.errMsg);+ });- ctx.autoplay = true;+ ctx.src = url;+ ctx.play();return handle;}diff --git a/sdk/src/core.ts b/sdk/src/core.tsindex 0be911a3c..18f76947d 100644--- a/sdk/src/core.ts+++ b/sdk/src/core.ts@@ -322,6 +322,7 @@ export {type AddressableAssetType,type EditorAssetType,type AssetTypeEntry,+ type AssetBuildTransform,getAssetTypeEntry,getEditorType,getAddressableType,@@ -334,6 +335,8 @@ export {getAssetMimeType,isCustomExtension,toBuildPath,+ registerAssetBuildTransform,+ getAssetBuildTransform,} from './assetTypes';// =============================================================================