Skip to content

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

feat: add volume-based post-processing system with editor support

esengined5f7128ae858
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.js
index 51e688c36..8fcaf9fdf 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}}async loadBufferFromData(e,t){return this.loadBuffer(e)}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},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",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 T(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 M=null;function E(){return M||(M=wx.getFileSystemManager()),M}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)}(T(e))}async readTextFile(e){return function(e,t="utf-8"){return E().readFileSync(e,t)}(T(e))}async fileExists(e){return A(T(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}},L=1920,D=1080,U=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 V=4294967295,N=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 X=0;function Y(e,t){const s=++X,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:V,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),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:L,y:D},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:N,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={Point:0,Circle:1,Rectangle:2,Cone:3},_e={World:0,Local:1},xe={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},we=se("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:ye.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:xe.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:xe.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:V,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:_e.World,enabled:!0}),ve=q("Name",{value:""}),be=q("SceneOwner",{scene:"",persistent:!1}),Se=q("PostProcessVolume",{effects:[]});const Pe=se("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Te=se("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Me=se("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ee=se("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 Fe(e){return{_type:"res_mut",_resource:e}}class ke{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 ke(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Le=Re({delta:0,elapsed:0,frameCount:0},"Time");function De(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=Ue(t[e]),o=Ue(i);"null"!==s&&"undefined"!==s&&(s!==o&&null!=i&&n.push({field:e,expected:s,actual:o,value:i}))}return n}function Ue(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function We(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}let ze=null;function $e(e){ze=e}function Oe(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),ze&&ze(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 Ve=1;const Ne=new WeakMap;function je(e){let t=Ne.get(e);return void 0===t&&(t=Ve++,Ne.set(e,t)),t}const Xe=[];function Ye(e,t=[],s=[]){Xe.length=0;for(const t of e)Xe.push(je(t));Xe.sort((e,t)=>e-t);let n=Xe.join(",");if(t.length>0){Xe.length=0;for(const e of t)Xe.push(je(e));Xe.sort((e,t)=>e-t),n+="|+"+Xe.join(",")}if(s.length>0){Xe.length=0;for(const e of s)Xe.push(je(e));Xe.sort((e,t)=>e-t),n+="|-"+Xe.join(",")}return n}class Ge{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 Oe(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){Oe(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t){this.tsStorage_.get(s)?.delete(e),this.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){Oe(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Oe(t,`removeParent(entity=${e})`)}}insert(e,t,s){return Q(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}set(e,t,s){if(Q(t)){if(this.cppRegistry_)try{const n=t._default,i=s;let o=i;for(const e of Object.keys(i))e in n||(o===i&&(o={...i}),delete o[e]);this.getBuiltinMethods(t._cppName).add(e,He(o))}catch(s){Oe(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 Oe(s,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");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=t._default,i={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&e in n&&(i[e]=t);const e=De(t._name,n,i);if(e.length>0)throw new Error(We(t._name,e))}const o={...t._default,...i};let r=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(t._cppName);r=!s.has(e),s.add(e,He(o))}catch(s){Oe(s,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),o}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 Oe(s,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(s){return Oe(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Oe(s,`removeBuiltin(${t._name}, entity=${e})`)}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=De(t._name,t._default,e);if(i.length>0)throw new Error(We(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??Ye(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 qe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Ke(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Je(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Qe(e){return qe(e)||Ke(e)||Je(e)?e._component:e}function Ze(e,t=[],s=[]){const n=[],i=[],o=[];return e.forEach((e,t)=>{qe(e)&&n.push(t),Ke(e)?i.push({index:t,component:e._component}):Je(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s,_addedFilters:i,_changedFilters:o,with:(...n)=>Ze(e,[...t,...n],s),without:(...n)=>Ze(e,t,[...s,...n])}}class et{constructor(e,t,s=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=s,this.actualComponents_=t._components.map(Qe),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_=Ye(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 tt{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 st{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 nt{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new st(this,null);return this.spawned_.push(e),e}entity(e){return new st(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 it{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 ot{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new it)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new it,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}class rt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class at{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var lt;function ct(){return{_type:"get_world"}}exports.Schedule=void 0,(lt=exports.Schedule||(exports.Schedule={}))[lt.Startup=0]="Startup",lt[lt.First=1]="First",lt[lt.PreUpdate=2]="PreUpdate",lt[lt.Update=3]="Update",lt[lt.PostUpdate=4]="PostUpdate",lt[lt.Last=5]="Last",lt[lt.FixedPreUpdate=10]="FixedPreUpdate",lt[lt.FixedUpdate=11]="FixedUpdate",lt[lt.FixedPostUpdate=12]="FixedPostUpdate";let ut=0;function dt(e,t,s){const n=++ut;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function ht(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}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 nt&&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 et(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 nt(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 rt(s)}case"event_reader":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new at(s)}case"removed":{const t=e;return new tt(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class ft{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 mt=Re(new ft,"Input");class gt{constructor(e){this.target_=e??null}build(e){const s=new ft;e.insertResource(mt,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,dt([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const yt=new gt,_t=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 xt;function wt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(xt=exports.BlendMode||(exports.BlendMode={}))[xt.Normal=0]="Normal",xt[xt.Additive=1]="Additive",xt[xt.Multiply=2]="Multiply",xt[xt.Screen=3]="Screen",xt[xt.PremultipliedAlpha=4]="PremultipliedAlpha";let vt=null,bt=null,St=1;const Pt=new Map;function Tt(e){vt=e,bt=e.getResourceManager(),Lt()}function Mt(){0!==Rt&&vt&&(vt._free(Rt),Rt=0),Pt.clear(),St=1,At=!1,Ft.clear(),kt=null,bt=null,vt=null}function Et(){if(!bt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return bt}const Ct={createShader:(e,t)=>Et().createShader(e,t),releaseShader(e){e>0&&Et().releaseShader(e)},create(e){const t=St++,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 Pt.set(t,s),t},get:e=>Pt.get(e),setUniform(e,t,s){const n=Pt.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0,vt?.invalidateMaterialCache(e))},getUniform(e,t){const s=Pt.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Pt.get(e);s&&(s.blendMode=t,vt?.invalidateMaterialCache(e))},getBlendMode(e){const t=Pt.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=Pt.get(e);s&&(s.depthTest=t,vt?.invalidateMaterialCache(e))},getShader(e){const t=Pt.get(e);return t?.shader??0},release(e){Pt.delete(e),vt?.invalidateMaterialCache(e)},isValid:e=>Pt.has(e),releaseAll(){Pt.clear(),vt?.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=Pt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=St++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Pt.set(s,n),s},toAssetData(e,t){const s=Pt.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=Pt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let At=!1,Rt=0;const It=16384,Ft=new Map;let kt=null;function Bt(e){const t=(0===Rt&&vt&&(Rt=vt._malloc(It)),Rt);if(0===t||!vt)return{ptr:0,count:0};let s=0,n=0;const i=vt.HEAPU8,o=vt.HEAPU32,r=vt.HEAPF32;for(const[a,l]of e){if(wt(l))continue;let e=Ft.get(a);e||(kt||(kt=new TextEncoder),e=kt.encode(a),Ft.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(s+(4+u+4+16)>It){console.warn(`[ESEngine] Material uniform buffer full (${s}/${It} 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 Lt(){if(!vt||At)return;vt.materialDataProvider=(e,t,s,n,i)=>{const o=Pt.get(e);if(!o)return vt.HEAPU32[t>>2]=0,vt.HEAPU32[s>>2]=0,vt.HEAPU32[n>>2]=0,void(vt.HEAPU32[i>>2]=0);vt.HEAPU32[t>>2]=o.shader,vt.HEAPU32[s>>2]=o.blendMode;const{ptr:r,count:a}=Bt(o.uniforms);vt.HEAPU32[n>>2]=r,vt.HEAPU32[i>>2]=a},At=!0}const Dt={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class Ut{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const 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 Wt{constructor(e,t=""){this.cache_=new Ut,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ct.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ct.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:Ct.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 zt(e){const t=new Set;for(const s of e.frames)s.texture&&t.add(s.texture);return Array.from(t)}function $t(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 Ot=new Map;function Ht(e){Ot.set(e.name,e)}const Vt=q("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function Nt(e,t){const s=e.getEntitiesWithComponents([Vt]);for(const n of s){const s=e.get(n,Vt);if(!s.enabled||!s.playing||!s.clip)continue;const i=Ot.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,Vt,s)}}class jt{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 async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const s=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,s)}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}}}}jt.mixer_=null,jt.bufferCache_=new Map,jt.bgmHandle_=null,jt.bgmVolume_=1,jt.fadeAnimId_=0,jt.disposed_=!1;const Xt=new Map,Yt=new Map;function Gt(e,t,s){Xt.set(e,{width:t,height:s})}function qt(e){return Xt.get(e)}function Kt(){Xt.clear()}function Jt(e,t){Yt.set(e,t)}function Qt(e){return Yt.get(e)}let Zt=null;function es(e){Zt=e}function ts(){Zt=null}const ss={initLayer(e,t,s,n,i){Zt?.tilemap_initLayer(e,t,s,n,i)},destroyLayer(e){Zt?.tilemap_destroyLayer(e)},setTile(e,t,s,n){Zt?.tilemap_setTile(e,t,s,n)},getTile:(e,t,s)=>Zt?Zt.tilemap_getTile(e,t,s):0,fillRect(e,t,s,n,i,o){Zt?.tilemap_fillRect(e,t,s,n,i,o)},setTiles(e,t){if(!Zt)return;const s=t.byteLength,n=Zt._malloc(s);new Uint16Array(Zt.HEAPU8.buffer,n,t.length).set(t),Zt.tilemap_setTiles(e,n,t.length),Zt._free(n)},hasLayer:e=>!!Zt&&Zt.tilemap_hasLayer(e),submitLayer(e,t,s,n,i,o,r,a,l,c,u,d,h){Zt?.tilemap_submitLayer(e,t,s,n,i,o,r,a,l,c,u,d,h)}},ns=q("Tilemap",{source:""}),is=q("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[]});function os(e,t){if(0===e)return 0;let s=0;2147483648&e&&(s|=8192),1073741824&e&&(s|=16384),536870912&e&&(s|=32768);return(536870911&e)-t+1|s}function rs(e){const t=e.width,s=e.height,n=e.tilewidth??0,i=e.tileheight??0;if(!(t&&s&&n&&i))return null;const o=e.tilesets,r=[],a=[];if(o)for(const e of o){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??n,tileHeight:e.tileheight??i,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const n=e.width??t,i=e.height??s,o=!1!==e.visible,r=e.data,l=new Uint16Array(n*i);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=os(r[t],e)}c.push({name:e.name??"",width:n,height:i,visible:o,tiles:l})}return{width:t,height:s,tileWidth:n,tileHeight:i,layers:c,tilesets:r}}function as(e,t){const s=e.lastIndexOf("/"),n=((s>=0?e.substring(0,s+1):"")+t).split("/"),i=[];for(const e of n)".."===e?i.pop():"."!==e&&""!==e&&i.push(e);return i.join("/")}const ls=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"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}]]);function cs(e){const t=ls.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 ls.get(e)?.fields??[]}function ds(e){return ls.get(e)?.spine??null}const hs=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function ps(e){return hs.get(e)}function fs(e,t){const s=hs.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 ms(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)fs(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 ms(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 _s.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=ls.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=[..._s.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=ls.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=ms(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 _s=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),Gt(r.handle,r.width,r.height)}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=zt(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);Ht($t(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 jt.preloadAll(n).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,s,n){const i=[...e].map(async e=>{try{const i=rs(await t.loadJson(e));if(!i)return void console.warn(`Failed to parse tilemap: ${e}`);const o=[];for(const r of i.tilesets){const i=as(e,r.image);let a=0;try{const e=s?`${s}/${i}`:`/${i}`,o=await t.loadTexture(e);a=o.handle,n.set(i,e),Gt(o.handle,o.width,o.height)}catch(e){console.warn(`Failed to load tileset texture: ${i}`,e)}o.push({textureHandle:a,columns:r.columns})}Jt(e,{tileWidth:i.tileWidth,tileHeight:i.tileHeight,layers:i.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(i),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=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 ws(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 vs{constructor(e){this.textureCache_=new Ut,this.shaderCache_=new Ut,this.jsonCache_=new Ut,this.textCache_=new Ut,this.binaryCache_=new Ut,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Ut,this.prefabCache_=new Ut,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.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 Wt(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(),Ct.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 cs(e.type)){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}const s=ds(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 Ct.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 Ct.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(T(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 bs=Re(null,"Assets");class Ss{build(e){const t=e.wasmModule;t?e.insertResource(bs,new vs(t)):console.warn("AssetPlugin: No WASM module available")}}const Ps=new Ss;async function Ts(e,t,s){const{entities:n,rootId:i}=await Es(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 Ms=10;async function Es(e,t,s,n,i,o=0){if(o>Ms)throw new Error(`Prefab nesting depth exceeded ${Ms}. 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 Es(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};Cs(d.components,r),As(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 Cs(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 As(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 Rs{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 Ts(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Is=Re(null,"Prefabs");class Fs{constructor(){this.name="PrefabsPlugin",this.dependencies=[bs]}build(e){const t=e.getResource(bs);e.insertResource(Is,new Rs(e.world,t))}}const ks=new Fs;let Bs=null,Ls=0,Ds=0,Us=0;const Ws=new Float32Array(256);function zs(e){Bs=e,Ls=Bs._malloc(64),Ds=Bs._malloc(64),Us=Bs._malloc(1024)}function $s(){Bs&&(Ls&&(Bs._free(Ls),Ls=0),Ds&&(Bs._free(Ds),Ds=0),Us&&(Bs._free(Us),Us=0)),Bs=null}function Os(){if(!Bs)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Bs}const Hs={r:1,g:1,b:1,a:1},Vs={begin(e){const t=Os();try{t.HEAPF32.set(e,Ls/4),t.draw_begin(Ls)}catch(e){Oe(e,"Draw.begin")}},end(){try{Os().draw_end()}catch(e){Oe(e,"Draw.end")}},line(e,t,s,n=1){try{Os().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.line")}},rect(e,t,s,n=!0){try{Os().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{Os().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,i=32){try{Os().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){Oe(e,"Draw.circle")}},circleOutline(e,t,s,n=1,i=32){try{Os().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){Oe(e,"Draw.circleOutline")}},texture(e,t,s,n=Hs){try{Os().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Oe(e,"Draw.texture")}},textureRotated(e,t,s,n,i=Hs){try{Os().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,i.r,i.g,i.b,i.a)}catch(e){Oe(e,"Draw.textureRotated")}},setLayer(e){Os().draw_setLayer(e)},setDepth(e){Os().draw_setDepth(e)},getDrawCallCount:()=>Bs?Bs.draw_getDrawCallCount():0,getPrimitiveCount:()=>Bs?Bs.draw_getPrimitiveCount():0,setBlendMode(e){Os().draw_setBlendMode(e)},setDepthTest(e){Os().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=Os();n.HEAPF32.set(s,Ds/4),n.draw_mesh(e,t,Ds)}catch(s){Oe(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=Os(),i=Ct.get(t);if(!i)return;if(Vs.setBlendMode(i.blendMode),Vs.setDepthTest(i.depthTest),0===i.uniforms.size)return void Vs.drawMesh(e,i.shader,s);let o;if(n.HEAPF32.set(s,Ds/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,s]of i.uniforms){const n=Xs(t);if(!(n<0)){if(wt(s))Ws[o++]=10,Ws[o++]=n,Ws[o++]=s.slot??e++,Ws[o++]=s.textureId;else if("number"==typeof s)Ws[o++]=1,Ws[o++]=n,Ws[o++]=s;else if(Array.isArray(s)){Ws[o++]=s.length,Ws[o++]=n;for(let e=0;e<s.length;e++)Ws[o++]=s[e]}else"w"in s?(Ws[o++]=4,Ws[o++]=n,Ws[o++]=s.x,Ws[o++]=s.y,Ws[o++]=s.z,Ws[o++]=s.w):"z"in s?(Ws[o++]=3,Ws[o++]=n,Ws[o++]=s.x,Ws[o++]=s.y,Ws[o++]=s.z):(Ws[o++]=2,Ws[o++]=n,Ws[o++]=s.x,Ws[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(Ws.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void n.draw_mesh(e,i.shader,Ds);n.HEAPF32.set(i.cachedBuffer_.subarray(0,o),Us/4),n.draw_meshWithUniforms(e,i.shader,Ds,Us,o)}catch(s){Oe(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Ns={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},js=new Set;function Xs(e){const t=Ns[e];return void 0!==t?t:(js.has(e)||(js.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Ns).join(", ")}`)),-1)}const Ys=new Map;function Gs(e,t,s){Ys.set(e,{fn:t,scene:s??""})}function qs(e){Ys.delete(e)}function Ks(){Ys.clear()}var Js;exports.DataType=void 0,(Js=exports.DataType||(exports.DataType={}))[Js.Float=1]="Float",Js[Js.Float2=2]="Float2",Js[Js.Float3=3]="Float3",Js[Js.Float4=4]="Float4",Js[Js.Int=5]="Int",Js[Js.Int2=6]="Int2",Js[Js.Int3=7]="Int3",Js[Js.Int4=8]="Int4";let Qs=null,Zs=0,en=0,tn=0;function sn(e){Qs=e,Zs=Qs._malloc(262144),en=Qs._malloc(65536),tn=Qs._malloc(256)}function nn(){Qs&&(Zs&&Qs._free(Zs),en&&Qs._free(en),tn&&Qs._free(tn),Zs=0,en=0,tn=0),Qs=null}function on(){if(!Qs)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Qs}const rn={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,Zs/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,tn,i).set(o),t.geometry_init(s,Zs,n,tn,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,en,n).set(e.indices),t.geometry_setIndices16(s,en,n)}else{new Uint32Array(t.HEAPU8.buffer,en,n).set(e.indices),t.geometry_setIndices32(s,en,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,Zs/4),n.geometry_updateVertices(e,Zs,i,s)},release(e){e>0&&on().geometry_release(e)},isValid:e=>!(!Qs||e<=0)&&Qs.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: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 rn.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 rn.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 an=null,ln=1;const cn=new Map,un=new Map;function dn(e){an=e}function hn(){for(const e of cn.values())e.destroy();cn.clear(),un.clear(),an&&mn.isInitialized()&&mn.shutdown(),an=null}class pn{constructor(){this.passes_=[],this.destroyed_=!1,this.id=ln++,cn.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}setEnabled(e,t){const s=this.passes_.find(t=>t.name===e);return s&&(s.enabled=t),this}setUniform(e,t,s){const n=this.passes_.find(t=>t.name===e);return n&&n.floatUniforms.set(t,s),this}setUniformVec4(e,t,s){const n=this.passes_.find(t=>t.name===e);return n&&n.vec4Uniforms.set(t,{...s}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of un)t===this&&un.delete(e);cn.delete(this.id)}}}function fn(){if(!an)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return an}const mn={createStack:()=>new pn,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");un.set(e,t)},unbind(e){un.delete(e)},getStack:e=>un.get(e)??null,init(e,t){try{return fn().postprocess_init(e,t)}catch(s){return Oe(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{fn().postprocess_shutdown()}catch(e){Oe(e,"PostProcess.shutdown")}},resize(e,t){try{fn().postprocess_resize(e,t)}catch(s){Oe(s,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!an)return!1;try{return an.postprocess_isInitialized()}catch(e){return Oe(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{fn().postprocess_setBypass(e)}catch(e){Oe(e,"PostProcess.setBypass")}},setOutputViewport(e,t,s,n){try{fn().postprocess_setOutputViewport(e,t,s,n)}catch(e){Oe(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=un.get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(mn.isInitialized()||mn.init(1,1),mn.setBypass(!1),function(e){const t=fn();try{t.postprocess_clearPasses()}catch(e){return void Oe(e,"PostProcess._applyForCamera:clearPasses")}for(const s of e.passes)if(s.enabled){try{t.postprocess_addPass(s.name,s.shader)}catch(e){Oe(e,`PostProcess._applyForCamera:addPass("${s.name}")`);continue}for(const[e,n]of s.floatUniforms)try{t.postprocess_setUniformFloat(s.name,e,n)}catch(t){Oe(t,`PostProcess._applyForCamera:setUniform("${s.name}", "${e}")`)}for(const[e,n]of s.vec4Uniforms)try{t.postprocess_setUniformVec4(s.name,e,n.x,n.y,n.z,n.w)}catch(t){Oe(t,`PostProcess._applyForCamera:setUniformVec4("${s.name}", "${e}")`)}}}(t)):mn.setBypass(!0)},_resetAfterCamera(){try{fn().postprocess_clearPasses(),fn().postprocess_setBypass(!0)}catch(e){Oe(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of un.keys())e(t)||un.delete(t)},createBlur:()=>Ct.createShader(gn,"#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:()=>Ct.createShader(gn,"#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:()=>Ct.createShader(gn,"#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"),createBloom:()=>Ct.createShader(gn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_threshold;\nuniform float u_intensity;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 texelSize = 1.0 / u_resolution;\n\n vec3 bloom = vec3(0.0);\n float total = 0.0;\n for (float x = -3.0; x <= 3.0; x += 1.0) {\n for (float y = -3.0; y <= 3.0; y += 1.0) {\n vec2 offset = vec2(x, y) * texelSize * u_radius;\n vec4 s = texture(u_texture, v_texCoord + offset);\n float brightness = dot(s.rgb, vec3(0.2126, 0.7152, 0.0722));\n float w = max(brightness - u_threshold, 0.0);\n bloom += s.rgb * w;\n total += w;\n }\n }\n if (total > 0.0) bloom /= total;\n\n fragColor = vec4(color.rgb + bloom * u_intensity, color.a);\n}\n"),createChromaticAberration:()=>Ct.createShader(gn,"#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")},gn="#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",yn=new Map;function _n(e){yn.set(e.type,e)}function xn(e){return yn.get(e)}_n({type:"blur",label:"Blur",factory:()=>mn.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),_n({type:"bloom",label:"Bloom",factory:()=>mn.createBloom(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:2,step:.01,defaultValue:.8},{name:"u_intensity",label:"Intensity",min:0,max:10,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:0,max:20,step:.1,defaultValue:4}]}),_n({type:"vignette",label:"Vignette",factory:()=>mn.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:3,step:.01,defaultValue:.8},{name:"u_softness",label:"Softness",min:0,max:2,step:.01,defaultValue:.3}]}),_n({type:"grayscale",label:"Grayscale",factory:()=>mn.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),_n({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>mn.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const wn=new Map,vn=new Map;function bn(e){const t=wn.get(e);t&&(mn.unbind(e),t.destroy(),wn.delete(e));const s=vn.get(e);if(s){for(const e of s.values())Ct.releaseShader(e);vn.delete(e)}}var Sn;exports.RenderStage=void 0,(Sn=exports.RenderStage||(exports.RenderStage={}))[Sn.Background=0]="Background",Sn[Sn.Opaque=1]="Opaque",Sn[Sn.Transparent=2]="Transparent",Sn[Sn.Overlay=3]="Overlay";let Pn=null,Tn=0;function Mn(e){Pn=e,Tn=Pn._malloc(64)}function En(){Pn&&Tn&&(Pn._free(Tn),Tn=0),Pn=null}const Cn={init(e,t){Pn?.renderer_init(e,t)},resize(e,t){Pn?.renderer_resize(e,t)},begin(e,t){if(Pn&&Tn)try{Pn.HEAPF32.set(e,Tn/4),Pn.renderer_begin(Tn,t??0)}catch(e){Oe(e,"Renderer.begin")}},flush(){try{Pn?.renderer_flush()}catch(e){Oe(e,"Renderer.flush")}},end(){try{Pn?.renderer_end()}catch(e){Oe(e,"Renderer.end")}},submitSprites(e){if(Pn)try{Pn.renderer_submitSprites(e._cpp)}catch(e){Oe(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Pn)try{Pn.renderer_submitBitmapText(e._cpp)}catch(e){Oe(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Pn)try{Pn.renderer_submitSpine?.(e._cpp)}catch(e){Oe(e,"Renderer.submitSpine")}},submitParticles(e){if(Pn)try{Pn.renderer_submitParticles?.(e._cpp)}catch(e){Oe(e,"Renderer.submitParticles")}},setStage(e){Pn?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Pn?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Pn?.renderer_releaseTarget(e)},getTargetTexture:e=>Pn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Pn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Pn?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Pn?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,i){Pn?.renderer_setScissor(e,t,s,n,i)},clearBuffers(e){Pn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Pn?Pn.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Pn?{drawCalls:Pn.renderer_getDrawCalls(),triangles:Pn.renderer_getTriangles(),sprites:Pn.renderer_getSprites(),text:Pn.renderer_getText(),spine:Pn.renderer_getSpine?.()??0,meshes:Pn.renderer_getMeshes(),culled:Pn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let An=null;function Rn(e){An=e}function In(){An=null}const Fn={enable(){An?.gl_enableErrorCheck(!0)},disable(){An?.gl_enableErrorCheck(!1)},check:e=>An?.gl_checkErrors(e)??0,diagnose(){An?.renderer_diagnose()}};class kn{constructor(){this.spineRenderer_=null,this.tilemapRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}setTilemapRenderer(e){this.tilemapRenderer_=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_||(Cn.resize(n,i),this.lastWidth_=n,this.lastHeight_=i),Cn.setViewport(0,0,n,i),Cn.clearBuffers(3),Cn.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,i),this.tilemapRenderer_&&this.tilemapRenderer_(),Cn.submitSprites(t),Cn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Cn.submitSpine(t),Cn.submitParticles(t),Cn.flush(),this.executeDrawCallbacks(s,o),Cn.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==mn.getStack(r);a&&(mn._applyForCamera(r),mn.resize(n.w,n.h),mn.setOutputViewport(n.x,n.y,n.w,n.h)),Cn.setViewport(n.x,n.y,n.w,n.h),Cn.setScissor(n.x,n.y,n.w,n.h,!0),Cn.clearBuffers(i),Cn.setScissor(0,0,0,0,!1),Cn.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),this.tilemapRenderer_&&this.tilemapRenderer_(),Cn.submitSprites(t),Cn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Cn.submitSpine(t),Cn.submitParticles(t),Cn.flush(),this.executeDrawCallbacks(s,o),Cn.end(),a&&mn._resetAfterCamera()}executeDrawCallbacks(e,t){const s=Ys;if(s.size>0){Vs.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)}Vs.end();for(const e of n)qs(e)}}}const Bn="__scene_transition_overlay__";class Ln{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class Dn{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),Gs(e,t,this.instance_.config.name)}bindPostProcess(e,t){mn.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){mn.unbind(e),this.instance_.postProcessBindings.delete(e)}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 Un{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())qs(t);for(const t of e.postProcessBindings.keys())mn.unbind(t)}this.transition_&&(qs(Bn),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}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},Gs(Bn,()=>{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;Vs.setLayer(9999),Vs.setDepth(9999),Vs.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,qs(Bn),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,qs(Bn),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 Ln(t);this.scenes_.set(e,s);const n=new Dn(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(bs)?this.app_.getResource(bs):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 Ln(t);this.scenes_.set(e,s);const n=new Dn(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(bs)?this.app_.getResource(bs):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())qs(e);s.drawCallbacks.clear();for(const e of s.postProcessBindings.keys())mn.unbind(e);s.postProcessBindings.clear(),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(bs)&&(i.assetServer=this.app_.getResource(bs));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=zn(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(bs)?this.app_.getResource(bs):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)Ct.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.postProcessBindings.values())s.setAllPassesEnabled(t)}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 Wn=Re(null,"SceneManager");function zn(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Wn).getSceneStatus(t)&&s._fn(...n)}}}const $n=dt([Fe(Wn),Ie(Le)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),On={name:"SceneManager",build(e){const t=new Un(e);e.insertResource(Wn,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Wn),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,$n)}};class Hn{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 ot,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 Ge,this.resources_=new Be;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Hn}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 $e(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(Wn).register(e),this}setInitialScene(e){return this.getResource(Wn).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(Le)||this.resources_.insert(Le,{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 pt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(Le,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(exports.Schedule.Startup),this.lastTime_=c(),this.mainLoop())}quit(){this.running_=!1,Ks();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=[In,En,hn,nn,Mt,$s];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(Le);t.delta=e,t.elapsed+=e,t.frameCount++}}function Vn(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 Nn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function jn(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 Xn=[];function Yn(e){if(e<Xn.length)return Xn[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 Xn.push(t),t}function Gn(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,d=0;if(i.projectionType===ne.Orthographic){if(d=i.orthoSize,l){d=jn(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=d*r,a=Kn(-u,u,-d,d,-i.farPlane,i.farPlane)}else a=Qn(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const h=ei(o.position.x,o.position.y,o.position.z),p=Yn(c.length);p.entity=e,p.viewProjection.set(si(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 qn=new Float32Array(16);function Kn(e,t,s,n,i,o){const r=qn;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 Jn=new Float32Array(16);function Qn(e,t,s,n){const i=Jn;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 Zn=new Float32Array(16);function ei(e,t,s){const n=Zn;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 si(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 ni={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function ii(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 oi=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 ri=null,ai=null;function li(e,t){e.has(t,ce)||e.insert(t,ce,{texture:V,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0})}function ci(e,t){switch(e){case ni.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case ni.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case ni.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,s,n){if(!e.has(t,oi))return;const i=e.get(t,oi),o=ci(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,oi,i)}function di(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function hi(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function pi(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(hi(r.charCodeAt(0))&&n.length>0&&hi(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!hi(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 fi(e){let t=1;for(;t<e;)t*=2;return t}function mi(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 gi(e,t){if(ri&&ai){const e=ri.getUIRectComputedWidth(ai,t);if(e>0)return e}return e.size.x}function yi(e,t){if(ri&&ai){const e=ri.getUIRectComputedHeight(ai,t);if(e>0)return e}return e.size.y}function _i(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 xi(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function wi(e,t,s,n,i){if(!e.has(t,oi))return;const o=e.get(t,oi),r=ii(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 vi(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 bi=.1,Si=30,Pi={r:.3,g:.5,b:.8,a:1},Ti={Left:0,Center:1,Right:2},Mi={Top:0,Middle:1,Bottom:2},Ei={Visible:0,Clip:1,Ellipsis:2},Ci=q("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Ti.Left,verticalAlign:Mi.Top,wordWrap:!0,overflow:Ei.Visible,lineHeight:1.2});class Ai{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,fi(this.frameMaxW_)),e.height=Math.max(e.height,fi(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=fi(this.frameMaxW_),e.height=fi(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=pi(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===Ei.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,fi(p)),n.height=Math.max(n.height,fi(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===Ei.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 Mi.Top:w=u;break;case Mi.Middle:w=u+(f-2*u-x)/2;break;case Mi.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 Ti.Left:n=u;break;case Ti.Center:n=p/2;break;case Ti.Right:n=p-u;break;default:n=u}s.fillText(t,n,v),v+=c}i&&e.overflow===Ei.Clip&&s.restore();const b=s.getImageData(0,0,p,f),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),T=this.module._malloc(S.length);this.module.HEAPU8.set(S,T);const M=P.createTexture(p,f,T,S.length,1,!0);return this.module._free(T),{textureHandle:M,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const 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 Ti.Left:return"left";case Ti.Center:return"center";case Ti.Right:return"right"}}}const Ri=vi({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?gi(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?yi(e.uiRect,e.entity):0});class Ii{build(e){ee("Text",Ci);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Ai(t),n=e.world,i=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,dt([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Ci));for(const e of i.keys())if(!n.valid(e)||!n.has(e,Ci)){if(n.valid(e)&&n.has(e,ce)){const t=n.get(e,ce);n.insert(e,ce,{texture:V,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([Ci]);for(const t of e){const e=n.get(t,Ci),o=n.has(t,oi)?n.get(t,oi):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!Ri.changed(a,r)){if(n.has(t,ce)&&n.get(t,ce).texture!==V)continue}li(n,t);const l=o?{size:{x:gi(o,t),y:yi(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,Ri.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Fi=new Ii,ki=0,Bi=1,Li=se("UIMask",{enabled:!0,mode:ki});function Di(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 Ui(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,T=d*g-h*m,M=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*M+P*T;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*M)*I,s[5]=(n*R-o*E+r*M)*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*T)*I,s[9]=(i*E-n*A-r*T)*I,s[10]=(m*S-g*v+_*x)*I,s[11]=(h*v-d*S-f*x)*I,s[12]=(l*M-a*C-c*T)*I,s[13]=(n*C-i*M+o*T)*I,s[14]=(g*w-m*b-y*x)*I,s[15]=(d*b-h*w+p*x)*I),s}function Wi(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 zi(e,t){return 2*Math.atan2(e,t)}function $i(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 Oi(e,t,s,n,i,o,r){if(!e.has(t,oi)||!e.has(t,re))return null;const a=e.get(t,oi),l=e.get(t,re),c=gi(a,t)*l.worldScale.x,u=yi(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=zi(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,T=-1/0,M=-1/0;for(const[e,t]of b){const[a,l]=$i(e,t,s,n,i,o,r);S=Math.min(S,a),P=Math.min(P,l),T=Math.max(T,a),M=Math.max(M,l)}return{x:Math.round(S),y:Math.round(P),w:Math.round(T-S),h:Math.round(M-P)}}function Hi(e,t){return(s,n,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Li]);if(0===l.length)return;const c=[],u=[],d=new Set,h=new Set;for(const e of l){const s=t.get(e,Li);s.enabled&&(d.add(e),s.mode===Bi?(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;_i(t,e,e=>{if(i.has(e)){if(t.get(e,Li).mode===ki)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,Li).mode===ki){const e=Oi(t,s,o,r,a,l,c);e&&(n=Di(u,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=Oi(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;_i(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 Vi{build(e){if(ee("UIMask",Li),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Hi(e.wasmModule,e.world))}}const Ni=new Vi,ji=se("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),Xi=se("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Yi={Normal:0,Hovered:1,Pressed:2,Disabled:3},Gi=q("Button",{state:Yi.Normal,transition:null});class qi{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 Ki=Re(new qi,"UIEvents");class Ji{build(e){ee("UIRect",oi);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){ri=e,ai=t}(s,n);e.addSystemToSchedule(exports.Schedule.PreUpdate,dt([Ie(_t)],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,dt([Ie(_t)],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,dt([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const Qi=new Ji;let Zi=!1,eo=!1;function to(){return Zi}function so(){return eo}const no=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&&(Ui(t,e),s=!1),e)}}();function io(e,t,s,n){t.emit(s,n,s),_i(e,s,i=>{if(!e.has(i,ji))return!1;const o=e.get(i,ji);return o.enabled&&t.emit(i,n,s),o.blockRaycast})}class oo{build(e){ee("Interactable",ji),ee("Button",Gi);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),i=new qi;e.insertResource(Ki,i);let o=null,r=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,dt([Ie(mt),Ie(_t)],(e,a)=>{if(i.drain(),to()&&!so())return;const l=t.getEntitiesWithComponents([Xi]);for(const e of l){const s=t.get(e,Xi);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,Xi,s))}if(!a.valid)return;const c=u(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;no.update(a.viewProjection);const p=Wi(d,h,no.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,Xi)){const e=t.get(o,Xi);e.hovered=!1,t.insert(o,Xi,e),i.emit(o,"hover_exit")}if(null!==_){xi(t,_,Xi);const e=t.get(_,Xi);e.hovered=!0,t.insert(_,Xi,e),i.emit(_,"hover_enter")}o=_}if(m&&null!==_){const e=t.get(_,Xi);e.pressed=!0,e.justPressed=!0,t.insert(_,Xi,e),r=_,io(t,i,_,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,Xi)){const e=t.get(r,Xi);e.pressed=!1,e.justReleased=!0,t.insert(r,Xi,e),io(t,i,r,"release"),r===o&&io(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(exports.Schedule.Update,dt([],()=>{const e=t.getEntitiesWithComponents([Gi]);for(const s of e){if(xi(t,s,ji,{enabled:!0}),!t.has(s,Xi))continue;const e=t.get(s,Xi),n=t.get(s,Gi),i=t.get(s,ji),o=!a.has(s),r=n.state;if(i.enabled?e.pressed?n.state=Yi.Pressed:e.hovered?n.state=Yi.Hovered:n.state=Yi.Normal:n.state=Yi.Disabled,o&&a.add(s),(o||r!==n.state)&&n.transition&&t.has(s,ce)){const o=t.get(s,ce);o.color=di(n.transition,i.enabled,e.pressed,e.hovered),t.insert(s,ce,o)}}},{name:"ButtonSystem"}))}}const ro=new oo,ao=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}),lo=q("Focusable",{tabIndex:0,isFocused:!1});class co{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 uo=Re(new co,"FocusManager");class ho{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(ee("TextInput",ao),to()&&!so())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(uo);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,ao)?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,ao);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(Ki).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,ao);n.focused=!1,n.dirty=!0;e.getResource(uo).blur()}};function v(){const t=m();if(null===t)return;const n=s.get(t,ao);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(Ki).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,ao);e.focused=!1,e.dirty=!0}e.getResource(uo).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 T(e,l,c,d){(i.width<c||i.height<d)&&(i.width=fi(Math.max(i.width,c)),i.height=fi(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=pi(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=pi(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,dt([Ie(uo)],e=>{const t=s.getEntitiesWithComponents([ao]);for(const e of t)xi(s,e,lo,{tabIndex:0,isFocused:!1}),xi(s,e,ji,{enabled:!0,blockRaycast:!0});const n=m();if(n!==P){if(null!==P&&s.valid(P)&&s.has(P,ao)){const e=s.get(P,ao);e.focused=!1,e.dirty=!0,f.blur()}null!==n&&function(e){const t=s.get(e,ao);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,dt([],()=>{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,ao).dirty=!0}const r=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,ao)||(r.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([ao,oi]);for(const e of a){const t=s.get(e,ao);if(!t.dirty)continue;const n=s.get(e,oi),i=Math.ceil(n.size.x),o=Math.ceil(n.size.y);i<=0||o<=0||(li(s,e),T(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const po=new ho,fo={Simple:0,Sliced:1,Tiled:2,Filled:3},mo={Horizontal:0,Vertical:1},go={Left:0,Right:1,Bottom:2,Top:3},yo=q("Image",{texture:V,color:{r:1,g:1,b:1,a:1},imageType:fo.Simple,fillMethod:mo.Horizontal,fillOrigin:go.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),_o=vi({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?gi(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?yi(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class xo{build(e){ee("Image",yo);const t=e.world,s=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,dt([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,yo)||s.delete(e);const e=t.getEntitiesWithComponents([yo]);for(const n of e){const e=t.get(n,yo),i=t.has(n,oi)?t.get(n,oi):null,o={image:e,uiRect:i,entity:n},r=s.get(n);if(r&&!_o.changed(r,o))continue;li(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=gi(i,n),a.size.y=yi(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===mo.Horizontal?e.fillOrigin===go.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===go.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,ce,a),s.set(n,_o.take(o))}else a.color.a=0,t.insert(n,ce,a),s.set(n,_o.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const wo=new xo,vo=q("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),bo=q("ToggleGroup",{allowSwitchOff:!1});class So{build(e){ee("Toggle",vo),ee("ToggleGroup",bo);const t=e.world,s=new Set;e.addSystemToSchedule(exports.Schedule.Update,dt([Ie(Ki)],e=>{const n=t.getEntitiesWithComponents([vo]);if(!to()||so()){const i=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,vo);n.isOn&&0!==n.group&&t.valid(n.group)&&(i.has(n.group)?(n.isOn=!1,t.insert(e,vo,n)):i.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,vo);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(xi(t,s,ji,{enabled:!0}),!t.has(s,Xi))continue;const n=t.get(s,Xi),i=t.get(s,vo),r=t.get(s,ji);if(n.justPressed&&r.enabled){const n=i.group,r=0!==n&&t.valid(n)&&t.has(n,bo);if(i.isOn&&r){if(!t.get(n,bo).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(s,vo,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,vo);i.isOn&&(i.isOn=!1,t.insert(n,vo,i),e.emit(n,"change"))}}e.emit(s,"change")}if(i.transition&&t.has(s,ce)){const e=t.get(s,ce);e.color=di(i.transition,r.enabled,n.pressed,n.hovered),t.insert(s,ce,e)}}}for(const e of n){const s=t.get(e,vo);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 Po=new So,To=ni,Mo=q("ProgressBar",{value:0,fillEntity:0,direction:ni.LeftToRight});function Eo(e,t,s,n){if(!e.has(t,oi))return;const i=e.get(t,oi),o=s/2,r=n/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,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 Co{build(e){ee("ProgressBar",Mo);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,dt([],()=>{const e=t.getEntitiesWithComponents([Mo,oi]);for(const s of e){const e=t.get(s,Mo);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,oi),i=Math.max(0,Math.min(1,e.value));ui(t,e.fillEntity,e.direction,i);const o=gi(n,s),r=yi(n,s);Eo(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Ao=new Co,Ro=q("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Io=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 Fo{build(e){ee("Draggable",Ro),ee("DragState",Io);const t=e.world,s=e.getResource(Ki);let n=null,i={x:0,y:0},o=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,dt([Ie(mt),Ie(_t)],(e,r)=>{if(to()&&!so())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Ro,Xi]);let s=null,o=-1/0,r=-1;for(const n of e){if(!t.get(n,Ro).enabled)continue;if(t.get(n,Xi).hovered){let e=0;t.has(n,ce)&&(e=t.get(n,ce).layer);const i=mi(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,Io)||t.insert(s,Io);const e=t.get(s,Io),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,Io)){t.get(n,Io).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,Ro);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=n,n=null;t.get(o,Io).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Io))return void(o=null);const n=t.get(o,Io),i=t.get(o,Ro),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=zi(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 ko=new Fo,Bo=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 Lo(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 Do(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 Uo{build(e){ee("ScrollView",Bo);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(exports.Schedule.PostUpdate,dt([Ie(mt),Ie(_t),Ie(Le)],(e,i,o)=>{const r=to()&&!so(),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([Bo,oi]);for(const o of l){xi(t,o,Li,{enabled:!0,mode:ki});const l=t.get(o,Bo),c=t.get(o,oi);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=gi(c,o),h=yi(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,oi)){const e=t.get(r,oi);a=gi(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,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){xi(t,o,ji,{enabled:!0,blockRaycast:!0});const s=t.has(o,Xi)?t.get(o,Xi):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=Lo(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=Lo(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=Lo(l.scrollY,0,g,h);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Lo(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=Do(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)<bi&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>bi?(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=Do(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)<bi&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>bi?(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 Wo=new Uo,zo=ni,$o=q("Slider",{value:0,minValue:0,maxValue:1,direction:ni.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function Oo(e,t,s,n,i,o){const r=gi(n,i)*s.worldScale.x,a=yi(n,i)*s.worldScale.y,l=zi(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 ni.LeftToRight:return r>0?(p-m)/r:0;case ni.RightToLeft:return r>0?1-(p-m)/r:0;case ni.BottomToTop:return a>0?(f-g)/a:0;case ni.TopToBottom:return a>0?1-(f-g)/a:0}}function Ho(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case ni.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case ni.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case ni.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case ni.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class Vo{build(e){ee("Slider",$o);const t=e.world;let s=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,dt([Ie(mt),Ie(_t),Ie(Ki)],(e,n,i)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([$o,oi]);for(const r of o){const o=t.get(r,$o),a=t.get(r,oi);if(!to()||so()){if(t.has(r,re)){xi(t,r,ji,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&xi(t,o.handleEntity,ji,{enabled:!0,blockRaycast:!1});const l=t.get(r,re),c=t.has(r,Xi)?t.get(r,Xi):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Xi)&&(u=t.get(o.handleEntity,Xi).justPressed),u&&(s=r),s===r&&e.isMouseButtonDown(0)){let e=Oo(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,$o,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=gi(a,r),d=yi(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),wi(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,oi)){const e=t.get(o.handleEntity,oi);Ho(e,o.direction,c),t.insert(o.handleEntity,oi,e),wi(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const No=new Vo;class jo{build(e){ee("Focusable",lo);const t=e.world,s=new co;e.insertResource(uo,s),e.addSystemToSchedule(exports.Schedule.Update,dt([Ie(mt),Ie(Ki)],(e,n)=>{if(to()&&!so())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const i=t.getEntitiesWithComponents([lo]);for(const e of i){if(!t.has(e,Xi))continue;t.get(e,Xi).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,ji)){if(!t.get(s,ji).enabled)continue}const n=t.get(s,lo);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,lo)){t.get(i,lo).isFocused=!1,n.emit(i,"blur",i)}s.focus(e);t.get(e,lo).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const Xo=new jo,Yo=q("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function Go(){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 qo{build(e){ee("SafeArea",Yo);const t=e.world;let n=Go(),i=!0,o=0,r=0;if(s()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=Go(),i=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=Go(),i=!0});e.addSystemToSchedule(exports.Schedule.PreUpdate,dt([Ie(_t)],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([Yo,oi]);for(const e of d){const s=t.get(e,Yo),i=t.get(e,oi),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,oi,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const Ko=new qo,Jo=q("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Qo=null;class Zo{build(e){ee("ListView",Jo);const t=e.world,s=new Map;Qo=s,e.addSystemToSchedule(exports.Schedule.PostUpdate,dt([Ie(mt)],e=>{const n=to()&&!so();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([Jo,oi]);for(const o of i){xi(t,o,ji,{enabled:!0,blockRaycast:!0}),xi(t,o,Li,{enabled:!0,mode:ki});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,Jo),a=t.get(o,oi),l=yi(a,o),c=gi(a,o);if(!n){const s=t.has(o,Xi)?t.get(o,Xi):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,ve,{value:`ListItem_${e}`}),t.insert(s,oi,{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 er=new Zo,tr=q("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class sr{build(e){ee("Dropdown",tr);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*Si;t.insert(i,oi,{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:V,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)*Si;t.insert(o,ve,{value:`Option_${e}`}),t.insert(o,oi,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Si},offsetMax:{x:0,y:0},size:{x:r,y:Si},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:V,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:Si},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,ji,{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,Ci,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Ti.Left,verticalAlign:Mi.Middle,wordWrap:!1,overflow:Ei.Clip,lineHeight:1.2}),t.insert(c,oi,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:Si},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,Ci))return;const n=t.get(s,Ci);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,Ci,{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,ji)&&t.insert(e,ji,{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?{...Pi}:{r:.95,g:.95,b:.95,a:1};t.insert(n,ce,{texture:V,color:i,size:{x:e.ddWidth,y:Si},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,Xi))continue;if(t.get(s,Xi).hovered)return!0}return!1}e.addSystemToSchedule(exports.Schedule.Update,dt([Ie(mt),Ie(Ki)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const p=to()&&!so(),f=t.getEntitiesWithComponents([tr]);for(const m of f){const f=t.get(m,tr);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;xi(t,m,ji,{enabled:!0,blockRaycast:!0});const y=t.has(m,Xi)?t.get(m,Xi):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,Xi))continue;if(t.get(s,Xi).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,Xi))continue;if(t.get(n,Xi).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 nr=new sr,ir=0,or=0,rr=2,ar=q("LayoutGroup",{direction:ir,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:or,reverseOrder:!1});class lr{build(e){ee("LayoutGroup",ar);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,dt([],()=>{const e=t.getEntitiesWithComponents([ar,oi,fe]);for(const s of e){const e=t.get(s,ar),n=t.get(s,oi),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,oi)&&t.has(e,re)&&o.push({entity:e,rect:t.get(e,oi)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=gi(n,s),a=yi(n,s),l=n.pivot.x,c=n.pivot.y,u=e.padding,d=e.direction===ir;let h=0;for(let s=0;s<o.length;s++){const n=o[s],i=gi(n.rect,n.entity),p=yi(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===or?(1-c)*a-u.top-(1-m)*p:e.childAlignment===rr?-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===or?-l*r+u.left+f*i:e.childAlignment===rr?(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 cr=new lr;class ur{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(exports.Schedule.PostUpdate,dt([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const dr=new ur;async function hr(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 pr=Re({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),fr=Re(null,"PhysicsAPI");function mr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function gr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class yr{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(pr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=hr(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,dt([Ie(Le)],a=>{const l=r.getEntitiesWithComponents([Pe,re]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,Pe),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=mr(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),_r(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=mr(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=mr(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=gr(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(pr,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,i)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(fr,xr._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function _r(e,t,s){const n=e.world;if(n.has(s,Te)){const e=n.get(s,Te);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,Me)){const e=n.get(s,Me);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 xr{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(xr.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},vr={repeat:0,clamp:1,mirror:2};function br(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=vr[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 Sr(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function Pr(e,t,s,n){const 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 Tr(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]=br(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=ds(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=Sr(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=br(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 yr("",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=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=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=br(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=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=Ct.createShader(e.vertexSource,e.fragmentSource),n[i]=r),s[o]=Ct.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=zt(n),r=new Map;for(const t of o)try{const n=await s.loadPixels(t);r.set(t,br(e,n))}catch{r.set(t,0)}Ht($t(i,n,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(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("tilemap"!==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=rs(JSON.parse(t));if(!n)continue;const o=[];for(const t of n.tilesets){const n=as(i,t.image);let r=0;try{const t=await s.loadPixels(n);r=br(e,t),Gt(r,t.width,t.height)}catch{}o.push({textureHandle:r,columns:t.columns})}Jt(i,{tileWidth:n.tileWidth,tileHeight:n.tileHeight,layers:n.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${i}`,e)}}}}}(s,n,i),await async function(e,t){const s=[],n=new Set;for(const t of e.entities)for(const e of t.components){const t=us(e.type);for(const i of t){if("audio"!==i.type)continue;const t=e.data[i.field];"string"==typeof t&&t&&!n.has(t)&&(n.add(t),s.push(t))}}0!==s.length&&(t?await Promise.all(s.map(async e=>{try{const s=await t.readBinary(e);await jt.preloadFromData(e,s.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await jt.preloadAll(s).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(n,i),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,p,f);const m=gs(t.world,n);if(c&&t.hasResource(Wn))for(const e of m.values())t.world.insert(e,be,{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=ds(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=U);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=Pr(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(bs);e&&e.setAddressableManifest(l)}}function Mr(e,t,s){return{name:e,async setup(){await Tr({...s,sceneData:t,sceneName:e})}}}async function Er(e){const{app:t,firstScene:s,aspectRatio:n}=e;Vn(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(Wn);for(const t of e.scenes)o.register(Mr(t.name,t.data,i));s&&(o.setInitial(s),await o.load(s)),void 0!==n&&ws(t.world,n)}class Cr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=ds(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=us(e.type);for(const i of o){const o=e.data[i.field];"string"==typeof o&&o&&("font"===i.type?(n.add(o),t.add(o)):"material"===i.type||"anim-clip"===i.type||"tilemap"===i.type?t.add(o):"audio"===i.type&&s.add(o))}}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 Ar="__preview__";const Rr={create(e){const t=e.depth??!0,s="linear"===e.filter,n=(t?1:0)|(s?2:0),i=Cn.createRenderTarget(e.width,e.height,n);return{_handle:i,textureId:Cn.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:s?"linear":"nearest"}},release(e){Cn.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Cn.releaseRenderTarget(e._handle),Rr.create({width:t,height:s,depth:e._depth,filter:e._filter})),begin(e,t){Cn.begin(t,e._handle)},end(){Cn.end()},getDepthTexture:e=>Cn.getTargetDepthTexture(e._handle)};var Ir;exports.LogLevel=void 0,(Ir=exports.LogLevel||(exports.LogLevel={}))[Ir.Debug=0]="Debug",Ir[Ir.Info=1]="Info",Ir[Ir.Warn=2]="Warn",Ir[Ir.Error=3]="Error";class Fr{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 kr{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new Fr)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,s){this.log(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 Br=new kr;const Lr={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},Dr={Running:0,Paused:1,Completed:2,Cancelled:3},Ur={None:0,Restart:1,PingPong:2};const Wr=1.70158,zr=2.70158,$r=2.5949095;const Or=2*Math.PI/3,Hr=2*Math.PI/4.5;const Vr=7.5625,Nr=2.75;const jr=1e-6;function Xr(e,t,s){switch(e){case Lr.Linear:return t;case Lr.EaseInQuad:return function(e){return e*e}(t);case Lr.EaseOutQuad:return function(e){return e*(2-e)}(t);case Lr.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case Lr.EaseInCubic:return function(e){return e*e*e}(t);case Lr.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case Lr.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case Lr.EaseInBack:return function(e){return zr*e*e*e-Wr*e*e}(t);case Lr.EaseOutBack:return function(e){const t=e-1;return 1+zr*t*t*t+Wr*t*t}(t);case Lr.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-$r)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+$r)+2)/2}(t);case Lr.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*Or)}(t);case Lr.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*Or)+1}(t);case Lr.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*Hr)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*Hr)/2+1}(t);case Lr.EaseOutBounce:return function(e){return e<1/Nr?Vr*e*e:e<2/Nr?Vr*(e-=1.5/Nr)*e+.75:e<2.5/Nr?Vr*(e-=2.25/Nr)*e+.9375:Vr*(e-=2.625/Nr)*e+.984375}(t);case Lr.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)<jr)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)<jr)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 Lr.Step:return function(e){return e<1?0:1}(t);default:return t}}const Yr=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??Lr.Linear,bezierPoints:null,state:Dr.Running,loop:i?.loop??Ur.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)===Dr.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==Dr.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=Xr(t.easing,s,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*n),s>=1){if(t.loop!==Ur.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===Ur.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=Dr.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===Dr.Running&&(t.state=Dr.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===Dr.Paused&&(t.state=Dr.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=Dr.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:Dr.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 Gr{constructor(e){this.id=e}get state(){return Yr.getState(this.id)}bezier(e,t,s,n){return Yr.setBezier(this.id,e,t,s,n),this}then(e){return e instanceof Gr?Yr.setSequenceNext(this.id,e.id):Yr.setSequenceNextExternal(this.id,e),this}pause(){Yr.pause(this.id)}resume(){Yr.resume(this.id)}cancel(){Yr.cancel(this.id)}}class qr{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 Gr?(Yr.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 Kr=null,Jr=null;function Qr(e,t){Kr=e,Jr=t,Yr.init(e,t)}function Zr(){Yr.shutdown(),Kr=null,Jr=null}function ea(){if(!Kr)throw new Error("Tween API not initialized");return Kr}function ta(){if(!Jr)throw new Error("Tween API not initialized");return Jr}const sa={to(e,t,s,n,i,o){const r=ea(),a=ta(),l=o?.easing??Lr.Linear,c=o?.delay??0,u=o?.loop??Ur.None,d=o?.loopCount??0,h=r._anim_createTween(a,e,t,s,n,i,l,c,u,d);return new qr(r,a,h)},value(e,t,s,n,i){const o=Yr.create(e,t,s,n,i);return new Gr(o)},cancel(e){ea()._anim_cancelTween(ta(),e.entity)},cancelAll(e){ea()._anim_cancelAllTweens(ta(),e)},update(e){ea()._anim_updateTweens(ta(),e),Yr.update(e)}};class na{constructor(){this.name="AnimationPlugin"}build(e){Qr(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(exports.Schedule.Update,dt([Ie(Le)],e=>{sa.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(exports.Schedule.Update,dt([Ie(Le)],e=>{Nt(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){Zr()}}const ia=new na;var oa;exports.AttenuationModel=void 0,(oa=exports.AttenuationModel||(exports.AttenuationModel={}))[oa.Linear=0]="Linear",oa[oa.Inverse=1]="Inverse",oa[oa.Exponential=2]="Exponential";const ra={model:exports.AttenuationModel.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function aa(e,t=ra){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 la(e,t,s,n,i){const o=e-s;return Math.max(-1,Math.min(1,o/i))}const ca=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}),ua=q("AudioListener",{enabled:!0});class da{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;jt.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,dt([Ie(Le)],t=>{if(!(!to()||so()))return void(c&&(l=!1,c=!1));c=!0;const n=e.world;let i=0,u=0,d=!1;const h=n.getEntitiesWithComponents([ua,le]);for(const e of h){if(n.get(e,ua).enabled){const t=n.get(e,le);i=t.position.x,u=t.position.y,d=!0;break}}const p=n.getEntitiesWithComponents([ca]);a.clear();for(const e of p){const t=n.get(e,ca);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=jt.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=aa(Math.sqrt(p*p+f*f),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=la(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(),jt.dispose()}}const ha=new da;let pa=null,fa=null;function ma(e,t){pa=e,fa=t}function ga(){pa=null,fa=null}const ya={update(e){pa&&fa&&pa.particle_update?.(fa,e)},play(e){pa&&fa&&pa.particle_play?.(fa,e)},stop(e){pa&&fa&&pa.particle_stop?.(fa,e)},reset(e){pa&&fa&&pa.particle_reset?.(fa,e)},getAliveCount:e=>pa?pa.particle_getAliveCount?.(e)??0:0};class _a{constructor(){this.name="ParticlePlugin"}build(e){ma(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(exports.Schedule.Update,dt([Ie(Le)],e=>{ya.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){ga()}}const xa=new _a,wa=1e6;class va{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.sourceEntityKeys_=new Map}build(e){es(e.wasmModule);const t=e.world,s=this.initializedLayers_,n=this.sourceEntityKeys_;e.pipeline?.setTilemapRenderer(()=>{const i=e.getResource(_t),o=i?.valid?i.worldLeft:-1e6,r=i?.valid?i.worldBottom:-1e6,a=i?.valid?i.worldRight:wa,l=i?.valid?i.worldTop:wa,c=t.getEntitiesWithComponents([is,re]);for(const e of c){const n=t.tryGet(e,is),i=t.tryGet(e,re);if(!n||!i)continue;const c=n.texture;if(!c)continue;const u=qt(c);if(!u)continue;if(!s.has(e)){if(ss.initLayer(e,n.width,n.height,n.tileWidth,n.tileHeight),n.tiles.length>0){const t=new Uint16Array(n.tiles.length);for(let e=0;e<n.tiles.length;e++)t[e]=n.tiles[e];ss.setTiles(e,t)}s.add(e)}const d=n.tileWidth/u.width,h=n.tileHeight/u.height;ss.submitLayer(e,c,n.layer,0,n.tilesetColumns,d,h,i.worldPosition.x,i.worldPosition.y,o,r,a,l)}const u=t.getEntitiesWithComponents([ns,re]);for(const e of u){if(t.tryGet(e,is))continue;const i=t.tryGet(e,ns),c=t.tryGet(e,re);if(!i?.source||!c)continue;const u=Qt(i.source);if(!u)continue;if(!n.has(e)){const t=[];for(let n=0;n<u.layers.length;n++){const i=1073741824+256*e+n,o=u.layers[n];ss.initLayer(i,o.width,o.height,u.tileWidth,u.tileHeight),o.tiles.length>0&&ss.setTiles(i,o.tiles),t.push(i),s.add(i)}n.set(e,t)}const d=n.get(e);for(let e=0;e<u.layers.length&&e<d.length;e++){const t=d[e],s=u.tilesets[0];if(!s)continue;const n=qt(s.textureHandle);if(!n)continue;const i=u.tileWidth/n.width,h=u.tileHeight/n.height;ss.submitLayer(t,s.textureHandle,e,0,s.columns,i,h,c.worldPosition.x,c.worldPosition.y,o,r,a,l)}}})}cleanup(){for(const e of this.initializedLayers_)ss.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),Kt(),ts()}}const ba=new va;function Sa(e,t){return e.toFixed(t)}function Pa(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}class Ta{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">${Sa(e.fps,1)}</span> Frame: <span style="color:#d19a66">${Sa(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>${Pa(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${Sa(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 Ma(){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 Ea=Re(Ma(),"Stats");const Ca="StatsCollect";class Aa{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 Ra{constructor(e){this.name="Stats",this.collector_=new Aa,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(Ea,Ma());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new Ta(e,this.options_.position)}const t=this.collector_,s=this.overlay_,n=dt([Ie(Le),{_type:"get_world"}],(n,i)=>{t.pushFrame(n.delta);const o=e.getResource(Ea);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(Ca),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=Cn.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:Ca});e.addSystemToSchedule(exports.Schedule.Last,n)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const Ia=new Ra;class Fa{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 ka(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 Ba=[Fi,Ni,Qi,wo,Ao,ro,ko,Wo,No,Po,po,Xo,Ko,er,nr,cr,dr],La=[...Ba,ia,ha,xa,ba];function Da(e,t){return function(e,t){const s=Hn.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),zs(e),Tt(e),sn(e),dn(e),Mn(e),Rn(e);const i=new kn;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=Gn(e,n,t,i));const r=s.getResource(_t);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(_t,{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;Cn.setClearColor(e.x,e.y,e.z,e.w)}const d=(c()-o)/1e3;let h;if(Cn.resize(t,l),s.hasResource(Wn)){const e=s.getResource(Wn).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const p=Gn(e,n,t,l,s.world,h);if(a(t,l,p),0===p.length)i.render({registry:{_cpp:n},viewProjection:Nn,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,cameraEntity:e.entity})}Cn.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(exports.Schedule.First,l),s.addSystemToSchedule(exports.Schedule.Last,d),s.addPlugin(Ps),s.addPlugin(ks),s.addPlugin(yt),s.addPlugin(On),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:La,...t})}class Ua{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 Wa(e){return(t,s)=>(a(e,t).then(e=>{s(e.instance,e.module)}),{})}async function za(e,t){try{return await e({instantiateWasm:Wa(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=na,exports.App=Hn,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=vs,exports.Assets=bs,exports.AsyncCache=Ut,exports.Audio=jt,exports.AudioBus=d,exports.AudioListener=ua,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=da,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=ca,exports.BitmapText=me,exports.BodyType=Ce,exports.BoxCollider=Te,exports.Button=Gi,exports.ButtonState=Yi,exports.Camera=ue,exports.Canvas=de,exports.CapsuleCollider=Ee,exports.Changed=function(e){return{_filterType:"changed",_component:e}},exports.Children=fe,exports.CircleCollider=Me,exports.ClearFlags=ie,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=nt,exports.DEFAULT_DESIGN_HEIGHT=D,exports.DEFAULT_DESIGN_WIDTH=L,exports.DEFAULT_FALLBACK_DT=U,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=Fo,exports.DragState=Io,exports.Draggable=Ro,exports.Draw=Vs,exports.Dropdown=tr,exports.DropdownPlugin=sr,exports.EasingType=Lr,exports.EmitterShape=ye,exports.EntityCommands=st,exports.EventReader=function(e){return{_type:"event_reader",_event:e}},exports.EventReaderInstance=at,exports.EventRegistry=ot,exports.EventWriter=function(e){return{_type:"event_writer",_event:e}},exports.EventWriterInstance=rt,exports.FillDirection=ni,exports.FillMethod=mo,exports.FillOrigin=go,exports.FocusManager=uo,exports.FocusManagerState=co,exports.FocusPlugin=jo,exports.Focusable=lo,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=Fn,exports.Geometry=rn,exports.GetWorld=ct,exports.INVALID_ENTITY=0,exports.INVALID_FONT=N,exports.INVALID_MATERIAL=0,exports.INVALID_TEXTURE=V,exports.Image=yo,exports.ImagePlugin=xo,exports.ImageType=fo,exports.Input=mt,exports.InputPlugin=gt,exports.InputState=ft,exports.Interactable=ji,exports.LayoutGroupPlugin=lr,exports.ListView=Jo,exports.ListViewPlugin=Zo,exports.LocalTransform=ae,exports.Logger=kr,exports.LoopMode=Ur,exports.Material=Ct,exports.MaterialLoader=Wt,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ve,exports.Parent=pe,exports.Particle=ya,exports.ParticleEasing=xe,exports.ParticleEmitter=we,exports.ParticlePlugin=_a,exports.Physics=xr,exports.PhysicsEvents=pr,exports.PhysicsPlugin=yr,exports.PostProcess=mn,exports.PostProcessStack=pn,exports.PostProcessVolume=Se,exports.PrefabServer=Rs,exports.Prefabs=Is,exports.PrefabsPlugin=Fs,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(Wn);t.register({name:Ar,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Ar),this.loadPromise_=t.load(Ar).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 Cr(this.baseUrl_);await s.prefetch(t);let i=null;const o=this.app_.spineInitPromise;if(o){i=(await o).controller.raw}await Tr({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:s,spineModule:i,sceneName:Ar})}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(Wn).getScene(Ar),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(Wn);await e.switchTo(Ar),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=Mo,exports.ProgressBarDirection=To,exports.ProgressBarPlugin=Co,exports.ProjectionType=ne,exports.Query=function(...e){return Ze(e)},exports.QueryInstance=et,exports.Removed=function(e){return{_type:"removed",_component:e}},exports.RemovedQueryInstance=tt,exports.RenderPipeline=kn,exports.RenderTexture=Rr,exports.Renderer=Cn,exports.Res=Ie,exports.ResMut=Fe,exports.RigidBody=Pe,exports.RuntimeConfig=$,exports.SafeArea=Yo,exports.SafeAreaPlugin=qo,exports.ScaleMode=oe,exports.SceneManager=Wn,exports.SceneManagerState=Un,exports.SceneOwner=be,exports.ScrollView=Bo,exports.ScrollViewPlugin=Uo,exports.ShaderSources=Dt,exports.SimulationSpace=_e,exports.Slider=$o,exports.SliderDirection=zo,exports.SliderPlugin=Vo,exports.SpineAnimation=ge,exports.Sprite=ce,exports.SpriteAnimator=Vt,exports.Stats=Ea,exports.StatsCollector=Aa,exports.StatsOverlay=Ta,exports.StatsPlugin=Ra,exports.SystemRunner=pt,exports.Text=Ci,exports.TextAlign=Ti,exports.TextInput=ao,exports.TextInputPlugin=ho,exports.TextOverflow=Ei,exports.TextPlugin=Ii,exports.TextRenderer=Ai,exports.TextVerticalAlign=Mi,exports.Tilemap=ns,exports.TilemapAPI=ss,exports.TilemapLayer=is,exports.TilemapPlugin=va,exports.Time=Le,exports.Toggle=vo,exports.TogglePlugin=So,exports.Transform=re,exports.Tween=sa,exports.TweenHandle=qr,exports.TweenState=Dr,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=_t,exports.UIEventQueue=qi,exports.UIEvents=Ki,exports.UIInteraction=Xi,exports.UIInteractionPlugin=oo,exports.UILayoutPlugin=Ji,exports.UIMask=Li,exports.UIMaskPlugin=Vi,exports.UIRect=oi,exports.UIRenderOrderPlugin=ur,exports.Velocity=he,exports.WeChatAssetProvider=Ua,exports.WebAssetProvider=Cr,exports.World=Ge,exports.WorldTransform=le,exports.addStartupSystem=function(e){ht().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){ht().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){ht().push({schedule:e,system:t})},exports.animationPlugin=ia,exports.applyBuildRuntimeConfig=H,exports.applyDirectionalFill=ui,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=Ps,exports.audioPlugin=ha,exports.calculateAttenuation=aa,exports.calculatePanning=la,exports.cleanupAllPostProcessVolumes=function(){for(const e of wn.keys())bn(e)},exports.cleanupPostProcessVolume=bn,exports.clearAnimClips=function(){Ot.clear()},exports.clearDrawCallbacks=Ks,exports.clearTextureDimensionsCache=Kt,exports.clearTilemapSourceCache=function(){Yt.clear()},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=ci,exports.computeFillSize=function(e,t,s,n){switch(e){case ni.BottomToTop:case ni.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}},exports.computeHandleAnchors=function(e,t){switch(e){case ni.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case ni.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case ni.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=ii,exports.createMaskProcessor=Hi,exports.createRuntimeSceneConfig=Mr,exports.createWebApp=Da,exports.debug=function(e,t,s){Br.debug(e,t,s)},exports.defaultFrameStats=Ma,exports.defineComponent=q,exports.defineEvent=function(e){return{_id:Symbol(`Event_${e}`),_name:e}},exports.defineResource=Re,exports.defineSystem=dt,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=ko,exports.dropdownPlugin=nr,exports.error=function(e,t,s){Br.error(e,t,s)},exports.extractAnimClipTexturePaths=zt,exports.findEntityByName=function(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},exports.flushPendingSystems=Vn,exports.focusPlugin=Xo,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.getAllEffectDefs=function(){return Array.from(yn.values())},exports.getAnimClip=function(e){return Ot.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=us,exports.getComponentAssetFields=cs,exports.getComponentDefaults=function(e){const t=te(e);return t?j(t._default):null},exports.getComponentEntityFields=ps,exports.getComponentSpineFieldDescriptor=ds,exports.getCustomExtensions=S,exports.getEditorType=function(e){return v(e)?.editorType??"unknown"},exports.getEffectDef=xn,exports.getEffectTypes=function(){return Array.from(yn.keys())},exports.getLogger=function(){return Br},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getTextureDimensions=qt,exports.getTilemapSource=Qt,exports.getUserComponent=K,exports.getWeChatPackOptions=function(){return S().map(e=>({type:"suffix",value:e}))},exports.imagePlugin=wo,exports.info=function(e,t,s){Br.info(e,t,s)},exports.initDrawAPI=zs,exports.initGLDebugAPI=Rn,exports.initGeometryAPI=sn,exports.initMaterialAPI=Tt,exports.initParticleAPI=ma,exports.initPlayableRuntime=async function(e){const{app:t,module:s,assets:n,scenes:i,firstScene:o}=e,r=t.getResource(bs);r&&(r.registerEmbeddedAssets(n),r.setEmbeddedOnly(!0));const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await ka(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 ka(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new Fa(n);await Er({app:t,module:s,provider:c,scenes:i,firstScene:o,spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()},exports.initPostProcessAPI=dn,exports.initRendererAPI=Mn,exports.initRuntime=Er,exports.initTilemapAPI=es,exports.initTweenAPI=Qr,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=T(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:Wa("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=Da(a,{glContextHandle:c,getViewportSize:()=>({width:i.width,height:i.height})});e.runtimeConfig&&H(u,e.runtimeConfig);let d=null;e.spineFactory&&(d=await za(e.spineFactory,"spine.wasm"));let h=null;e.physicsFactory&&(h=await za(e.physicsFactory,"physics.wasm"));const p=new Ua(n),f=[];for(const t of e.sceneNames){const e=await o(`scenes/${t}.json`);f.push({name:t,data:JSON.parse(e)})}await Er({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=yt,exports.instantiatePrefab=Ts,exports.intersectRects=Di,exports.invertMatrix4=Ui,exports.isBuiltinComponent=Q,exports.isCustomExtension=P,exports.isEditor=to,exports.isKnownAssetExtension=b,exports.isPlatformInitialized=function(){return null!==e},exports.isPlayMode=so,exports.isRuntime=function(){return!Zi},exports.isTextureRef=wt,exports.isWeChat=s,exports.isWeb=function(){return"web"===e?.name},exports.layoutGroupPlugin=cr,exports.listViewPlugin=er,exports.loadComponent=xs,exports.loadPhysicsModule=hr,exports.loadRuntimeScene=Tr,exports.loadSceneData=gs,exports.loadSceneWithAssets=ys,exports.loadTiledMap=function(e,t,s){const n=[],i=t.tilesets[0];let o=0;for(const r of t.layers){if(!r.visible)continue;const a=e.spawn();e.insert(a,re,{});const l=i?s.get(i.image)??0:0,c=i?.columns??1;e.insert(a,is,{width:r.width,height:r.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:o,tiles:Array.from(r.tiles)}),n.push(a),o++}return n},exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&b(w(e)))},exports.parseAnimClipData=$t,exports.parseTiledMap=async function(e,t){const s=Zt;if(!s)return null;const n=new TextEncoder,i=n.encode(e),o=s._malloc(i.byteLength);s.HEAPU8.set(i,o);const r=s.tiled_loadMap(o,i.byteLength);if(s._free(o),0===r)return null;try{const e=s.tiled_getExternalTilesetCount(r);for(let i=0;i<e;i++){const e=s.tiled_getExternalTilesetSource(r,i);if(!t)return s.tiled_freeMap(r),null;const o=await t(e),a=n.encode(o),l=s._malloc(a.byteLength);s.HEAPU8.set(a,l);const c=s.tiled_loadExternalTileset(r,i,l,a.byteLength);if(s._free(l),!c)return s.tiled_freeMap(r),null}if(!s.tiled_finalize(r))return s.tiled_freeMap(r),null;const i={width:s.tiled_getMapWidth(r),height:s.tiled_getMapHeight(r),tileWidth:s.tiled_getMapTileWidth(r),tileHeight:s.tiled_getMapTileHeight(r),layers:[],tilesets:[]},o=s.tiled_getLayerCount(r);for(let e=0;e<o;e++){const t=s.tiled_getLayerWidth(r,e),n=s.tiled_getLayerHeight(r,e),o=t*n,a=2*o,l=s._malloc(a);s.tiled_getLayerTiles(r,e,l,o);const c=new Uint16Array(o);c.set(new Uint16Array(s.HEAPU8.buffer,l,o)),s._free(l),i.layers.push({name:s.tiled_getLayerName(r,e),width:t,height:n,visible:s.tiled_getLayerVisible(r,e),tiles:c})}const a=s.tiled_getTilesetCount(r);for(let e=0;e<a;e++)i.tilesets.push({name:s.tiled_getTilesetName(r,e),image:s.tiled_getTilesetImage(r,e),tileWidth:s.tiled_getTilesetTileWidth(r,e),tileHeight:s.tiled_getTilesetTileHeight(r,e),columns:s.tiled_getTilesetColumns(r,e),tileCount:s.tiled_getTilesetTileCount(r,e)});return s.tiled_freeMap(r),i}catch{return s.tiled_freeMap(r),null}},exports.parseTmjJson=rs,exports.particlePlugin=xa,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=zi(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=ks,exports.progressBarPlugin=Ao,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerAnimClip=Ht,exports.registerAssetBuildTransform=function(e,t){for(const s of g)s.editorType===e&&(s.buildTransform=t)},exports.registerComponent=ee,exports.registerComponentAssetFields=function(e,t){ls.set(e,t)},exports.registerComponentEntityFields=function(e,t){hs.set(e,t)},exports.registerDrawCallback=Gs,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(bs);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=Lt,exports.registerTextureDimensions=Gt,exports.registerTilemapSource=Jt,exports.remapEntityFields=fs,exports.resolveRelativePath=as,exports.safeAreaPlugin=Ko,exports.sceneManagerPlugin=On,exports.screenToWorld=Wi,exports.scrollViewPlugin=Wo,exports.setEditorMode=function(e){Zi=e},exports.setListViewRenderer=function(e,t){if(!Qo)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=Qo.get(e);s?s.renderer=t:Qo.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})},exports.setLogLevel=function(e){Br.setMinLevel(e)},exports.setPlayMode=function(e){eo=e},exports.setWasmErrorHandler=$e,exports.shutdownDrawAPI=$s,exports.shutdownGLDebugAPI=In,exports.shutdownGeometryAPI=nn,exports.shutdownMaterialAPI=Mt,exports.shutdownParticleAPI=ga,exports.shutdownPostProcessAPI=hn,exports.shutdownRendererAPI=En,exports.shutdownTilemapAPI=ts,exports.shutdownTweenAPI=Zr,exports.sliderPlugin=No,exports.spriteAnimatorSystemUpdate=Nt,exports.statsPlugin=Ia,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 ni.BottomToTop:case ni.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.syncPostProcessVolume=function(e,t){let s=wn.get(e),n=vn.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(s||(s=mn.createStack(),wn.set(e,s)),n||(n=new Map,vn.set(e,n));s.passCount>0;){const e=s.passes;s.removePass(e[e.length-1].name)}for(const e of i){const t=xn(e.type);if(!t)continue;let i=n.get(e.type);void 0===i&&(i=t.factory(),n.set(e.type,i)),s.addPass(e.type,i);for(const n of t.uniforms){const t=e.uniforms[n.name]??n.defaultValue;s.setUniform(e.type,n.name,t)}}mn.bind(e,s)}else if(s&&(mn.unbind(e),s.destroy(),wn.delete(e)),n){for(const e of n.values())Ct.releaseShader(e);vn.delete(e)}},exports.textInputPlugin=po,exports.textPlugin=Fi,exports.tilemapPlugin=ba,exports.toBuildPath=T,exports.togglePlugin=Po,exports.transitionTo=async function(e,t,s){const n=e.getResource(Wn);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=ro,exports.uiLayoutPlugin=Qi,exports.uiMaskPlugin=Ni,exports.uiPlugins=Ba,exports.uiRenderOrderPlugin=dr,exports.unregisterAnimClip=function(e){Ot.delete(e)},exports.unregisterComponent=function(e){G().delete(e),Z.delete(e)},exports.unregisterDrawCallback=qs,exports.updateCameraAspectRatio=ws,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){Br.warn(e,t,s)},exports.wrapSceneSystem=zn,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}}async loadBufferFromData(e,t){return this.loadBuffer(e)}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},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",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 b(e){return _.get(w(e))}function v(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=b(e);return t?.wechatPackInclude??!1}function M(e){const t=b(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 C(){return T||(T=wx.getFileSystemManager()),T}function E(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=C();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 C().readFileSync(e)}(M(e))}async readTextFile(e){return function(e,t="utf-8"){return C().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}},L=1920,D=1080,U=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 V=4294967295,j=4294967295;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 X=0;function Y(e,t){const s=++X,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 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:V,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),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:L,y:D},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={Point:0,Circle:1,Rectangle:2,Cone:3},_e={World:0,Local:1},xe={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},we=se("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:ye.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:xe.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:xe.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:V,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:_e.World,enabled:!0}),be=q("Name",{value:""}),ve=q("SceneOwner",{scene:"",persistent:!1}),Se=q("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});const Pe=se("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Me=se("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Te=se("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ce=se("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ee={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 Fe(e){return{_type:"res_mut",_resource:e}}class ke{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 ke(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Le=Re({delta:0,elapsed:0,frameCount:0},"Time");function De(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=Ue(t[e]),o=Ue(i);"null"!==s&&"undefined"!==s&&(s!==o&&null!=i&&n.push({field:e,expected:s,actual:o,value:i}))}return n}function Ue(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function We(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}let ze=null;function $e(e){ze=e}function Oe(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),ze&&ze(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 Ve=1;const je=new WeakMap;function Ne(e){let t=je.get(e);return void 0===t&&(t=Ve++,je.set(e,t)),t}const Xe=[];function Ye(e,t=[],s=[]){Xe.length=0;for(const t of e)Xe.push(Ne(t));Xe.sort((e,t)=>e-t);let n=Xe.join(",");if(t.length>0){Xe.length=0;for(const e of t)Xe.push(Ne(e));Xe.sort((e,t)=>e-t),n+="|+"+Xe.join(",")}if(s.length>0){Xe.length=0;for(const e of s)Xe.push(Ne(e));Xe.sort((e,t)=>e-t),n+="|-"+Xe.join(",")}return n}class Ge{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 Oe(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){Oe(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t){this.tsStorage_.get(s)?.delete(e),this.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){Oe(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Oe(t,`removeParent(entity=${e})`)}}insert(e,t,s){return Q(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}set(e,t,s){if(Q(t)){if(this.cppRegistry_)try{const n=t._default,i=s;let o=i;for(const e of Object.keys(i))e in n||(o===i&&(o={...i}),delete o[e]);this.getBuiltinMethods(t._cppName).add(e,He(o))}catch(s){Oe(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 Oe(s,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");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=t._default,i={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&e in n&&(i[e]=t);const e=De(t._name,n,i);if(e.length>0)throw new Error(We(t._name,e))}const o={...t._default,...i};let r=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(t._cppName);r=!s.has(e),s.add(e,He(o))}catch(s){Oe(s,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),o}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 Oe(s,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(s){return Oe(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Oe(s,`removeBuiltin(${t._name}, entity=${e})`)}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=De(t._name,t._default,e);if(i.length>0)throw new Error(We(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??Ye(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 qe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Ke(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Je(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Qe(e){return qe(e)||Ke(e)||Je(e)?e._component:e}function Ze(e,t=[],s=[]){const n=[],i=[],o=[];return e.forEach((e,t)=>{qe(e)&&n.push(t),Ke(e)?i.push({index:t,component:e._component}):Je(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s,_addedFilters:i,_changedFilters:o,with:(...n)=>Ze(e,[...t,...n],s),without:(...n)=>Ze(e,t,[...s,...n])}}function et(...e){return Ze(e)}class tt{constructor(e,t,s=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=s,this.actualComponents_=t._components.map(Qe),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_=Ye(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 st{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 nt{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 it{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new nt(this,null);return this.spawned_.push(e),e}entity(e){return new nt(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 ot{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 rt{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new ot)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new ot,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}class at{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class lt{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var ct;function ut(){return{_type:"get_world"}}exports.Schedule=void 0,(ct=exports.Schedule||(exports.Schedule={}))[ct.Startup=0]="Startup",ct[ct.First=1]="First",ct[ct.PreUpdate=2]="PreUpdate",ct[ct.Update=3]="Update",ct[ct.PostUpdate=4]="PostUpdate",ct[ct.Last=5]="Last",ct[ct.FixedPreUpdate=10]="FixedPreUpdate",ct[ct.FixedUpdate=11]="FixedUpdate",ct[ct.FixedPostUpdate=12]="FixedPostUpdate";let dt=0;function ht(e,t,s){const n=++dt;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function pt(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}class ft{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 it&&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 tt(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 it(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 at(s)}case"event_reader":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new lt(s)}case"removed":{const t=e;return new st(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class mt{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 gt=Re(new mt,"Input");class yt{constructor(e){this.target_=e??null}build(e){const s=new mt;e.insertResource(gt,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,ht([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const _t=new yt,xt=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 wt;function bt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(wt=exports.BlendMode||(exports.BlendMode={}))[wt.Normal=0]="Normal",wt[wt.Additive=1]="Additive",wt[wt.Multiply=2]="Multiply",wt[wt.Screen=3]="Screen",wt[wt.PremultipliedAlpha=4]="PremultipliedAlpha";let vt=null,St=null,Pt=1;const Mt=new Map;function Tt(e){vt=e,St=e.getResourceManager(),Dt()}function Ct(){0!==It&&vt&&(vt._free(It),It=0),Mt.clear(),Pt=1,Rt=!1,kt.clear(),Bt=null,St=null,vt=null}function Et(){if(!St)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return St}const At={createShader:(e,t)=>Et().createShader(e,t),releaseShader(e){e>0&&Et().releaseShader(e)},create(e){const t=Pt++,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 Mt.set(t,s),t},get:e=>Mt.get(e),setUniform(e,t,s){const n=Mt.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0,vt?.invalidateMaterialCache(e))},getUniform(e,t){const s=Mt.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Mt.get(e);s&&(s.blendMode=t,vt?.invalidateMaterialCache(e))},getBlendMode(e){const t=Mt.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=Mt.get(e);s&&(s.depthTest=t,vt?.invalidateMaterialCache(e))},getShader(e){const t=Mt.get(e);return t?.shader??0},release(e){Mt.delete(e),vt?.invalidateMaterialCache(e)},isValid:e=>Mt.has(e),releaseAll(){Mt.clear(),vt?.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=Mt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Pt++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Mt.set(s,n),s},toAssetData(e,t){const s=Mt.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=Mt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Rt=!1,It=0;const Ft=16384,kt=new Map;let Bt=null;function Lt(e){const t=(0===It&&vt&&(It=vt._malloc(Ft)),It);if(0===t||!vt)return{ptr:0,count:0};let s=0,n=0;const i=vt.HEAPU8,o=vt.HEAPU32,r=vt.HEAPF32;for(const[a,l]of e){if(bt(l))continue;let e=kt.get(a);e||(Bt||(Bt=new TextEncoder),e=Bt.encode(a),kt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(s+(4+u+4+16)>Ft){console.warn(`[ESEngine] Material uniform buffer full (${s}/${Ft} 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 Dt(){if(!vt||Rt)return;vt.materialDataProvider=(e,t,s,n,i)=>{const o=Mt.get(e);if(!o)return vt.HEAPU32[t>>2]=0,vt.HEAPU32[s>>2]=0,vt.HEAPU32[n>>2]=0,void(vt.HEAPU32[i>>2]=0);vt.HEAPU32[t>>2]=o.shader,vt.HEAPU32[s>>2]=o.blendMode;const{ptr:r,count:a}=Lt(o.uniforms);vt.HEAPU32[n>>2]=r,vt.HEAPU32[i>>2]=a},Rt=!0}const Ut={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class Wt{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 zt{constructor(e,t=""){this.cache_=new Wt,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(At.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())At.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await 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:At.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 $t(e){const t=new Set;for(const s of e.frames)s.texture&&t.add(s.texture);return Array.from(t)}function Ot(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 Ht=new Map;function Vt(e){Ht.set(e.name,e)}const jt=q("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function Nt(e,t){const s=e.getEntitiesWithComponents([jt]);for(const n of s){const s=e.get(n,jt);if(!s.enabled||!s.playing||!s.clip)continue;const i=Ht.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,jt,s)}}class Xt{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 async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const s=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,s)}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}}}}Xt.mixer_=null,Xt.bufferCache_=new Map,Xt.bgmHandle_=null,Xt.bgmVolume_=1,Xt.fadeAnimId_=0,Xt.disposed_=!1;const Yt=new Map,Gt=new Map;function qt(e,t,s){Yt.set(e,{width:t,height:s})}function Kt(e){return Yt.get(e)}function Jt(){Yt.clear()}function Qt(e,t){Gt.set(e,t)}function Zt(e){return Gt.get(e)}let es=null;function ts(e){es=e}function ss(){es=null}const ns={initLayer(e,t,s,n,i){es?.tilemap_initLayer(e,t,s,n,i)},destroyLayer(e){es?.tilemap_destroyLayer(e)},setTile(e,t,s,n){es?.tilemap_setTile(e,t,s,n)},getTile:(e,t,s)=>es?es.tilemap_getTile(e,t,s):0,fillRect(e,t,s,n,i,o){es?.tilemap_fillRect(e,t,s,n,i,o)},setTiles(e,t){if(!es)return;const s=t.byteLength,n=es._malloc(s);new Uint16Array(es.HEAPU8.buffer,n,t.length).set(t),es.tilemap_setTiles(e,n,t.length),es._free(n)},hasLayer:e=>!!es&&es.tilemap_hasLayer(e),submitLayer(e,t,s,n,i,o,r,a,l,c,u,d,h,p,f,m,g,y,_,x){es?.tilemap_submitLayer(e,t,s,n,i,o,r,a,l,c,u,d,h,p,f,m,g,y,_,x)}},is=q("Tilemap",{source:""}),os=q("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[],tint:{r:1,g:1,b:1,a:1},opacity:1,visible:!0,parallaxFactor:{x:1,y:1}});function rs(e){if(0===e)return{r:1,g:1,b:1,a:1};const t=(e>>>24&255)/255;return{r:(e>>>16&255)/255,g:(e>>>8&255)/255,b:(255&e)/255,a:0===t?1:t}}function as(e){if(!e)return{r:1,g:1,b:1,a:1};const t=e.startsWith("#")?e.slice(1):e;if(8===t.length){const e=parseInt(t.slice(0,2),16)/255;return{r:parseInt(t.slice(2,4),16)/255,g:parseInt(t.slice(4,6),16)/255,b:parseInt(t.slice(6,8),16)/255,a:e}}if(6===t.length){return{r:parseInt(t.slice(0,2),16)/255,g:parseInt(t.slice(2,4),16)/255,b:parseInt(t.slice(4,6),16)/255,a:1}}return{r:1,g:1,b:1,a:1}}function ls(e,t){if(0===e)return 0;let s=0;2147483648&e&&(s|=8192),1073741824&e&&(s|=16384),536870912&e&&(s|=32768);return(536870911&e)-t+1|s}function cs(e){const t=e.width,s=e.height,n=e.tilewidth??0,i=e.tileheight??0;if(!(t&&s&&n&&i))return null;const o=e.tilesets,r=[],a=[];if(o)for(const e of o){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??n,tileHeight:e.tileheight??i,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const n=e.width??t,i=e.height??s,o=!1!==e.visible,r=e.data,l=new Uint16Array(n*i);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=ls(r[t],e)}const u="number"==typeof e.opacity?e.opacity:1,d=as(e.tintcolor),h="number"==typeof e.parallaxx?e.parallaxx:1,p="number"==typeof e.parallaxy?e.parallaxy:1;c.push({name:e.name??"",width:n,height:i,visible:o,tiles:l,opacity:u,tintColor:d,parallaxX:h,parallaxY:p})}const u=[],d=[];if(l)for(const e of l){if("objectgroup"!==e.type)continue;const t=e.objects;if(!t)continue;const s=[];for(const e of t){const t=new Map,n=e.properties;if(n)for(const e of n)t.set(e.name,e.value);let i="rect",o=null;if(e.ellipse)i="ellipse";else if(e.point)i="point";else if(e.polygon){i="polygon";const t=e.polygon;o=[];for(const e of t)o.push(e.x,e.y)}else if(e.polyline){i="polygon";const t=e.polyline;o=[];for(const e of t)o.push(e.x,e.y)}s.push({shape:i,x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0,rotation:e.rotation??0,vertices:o,properties:t})}u.push({name:e.name??"",objects:s})}if(o)for(const e of o){const t=e.firstgid??1,s=e.tiles;if(s)for(const e of s){const s=e.properties;if(s)for(const n of s)"collision"===n.name&&!0===n.value&&d.push(e.id+t)}}return{width:t,height:s,tileWidth:n,tileHeight:i,layers:c,tilesets:r,objectGroups:u,collisionTileIds:d}}function us(e,t){const s=e.lastIndexOf("/"),n=((s>=0?e.substring(0,s+1):"")+t).split("/"),i=[];for(const e of n)".."===e?i.pop():"."!==e&&""!==e&&i.push(e);return i.join("/")}const ds=Math.PI/180;function hs(e,t,s,n,i,o){const r=function(e,t,s,n){const i=new Uint8Array(t*s),o=[],r=(o,r)=>{if(o>=t||r>=s)return!1;const a=r*t+o;if(i[a])return!1;const l=8191&e[a];return 0!==l&&n.has(l)};for(let e=0;e<s;e++)for(let n=0;n<t;n++){if(!r(n,e))continue;let a=1;for(;r(n+a,e);)a++;let l=1,c=!0;for(;c;){const t=e+l;if(t>=s)break;for(let e=0;e<a;e++)if(!r(n+e,t)){c=!1;break}c&&l++}for(let s=0;s<l;s++)for(let o=0;o<a;o++)i[(e+s)*t+(n+o)]=1;o.push({col:n,row:e,width:a,height:l})}return o}(t.tiles,t.width,t.height,n),a=[],l=s.tileWidth,c=s.tileHeight,u=s.height*c;for(const t of r){const s=t.width*l,n=t.height*c,r=i+t.col*l+.5*s,d=o+(u-t.row*c)-.5*n,h=e.spawn();e.insert(h,re,{position:{x:r,y:d,z:0}}),e.insert(h,Pe,{bodyType:Ee.Static}),e.insert(h,Me,{halfExtents:{x:.5*s,y:.5*n}}),a.push(h)}return a}const ps=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"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}]]);function fs(e){const t=ps.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 ms(e){return ps.get(e)?.fields??[]}function gs(e){return ps.get(e)?.spine??null}const ys=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function _s(e){return ys.get(e)}function xs(e,t){const s=ys.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 ws(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,be,{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)xs(i,s),Ps(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 bs(e,t){return ws(e,t)}async function vs(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 Ss.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=ps.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=[...Ss.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=ps.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=ws(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 Ss=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),qt(r.handle,r.width,r.height)}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=$t(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);Vt(Ot(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 Xt.preloadAll(n).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,s,n){const i=[...e].map(async e=>{try{const i=cs(await t.loadJson(e));if(!i)return void console.warn(`Failed to parse tilemap: ${e}`);const o=[];for(const r of i.tilesets){const i=us(e,r.image);let a=0;try{const e=s?`${s}/${i}`:`/${i}`,o=await t.loadTexture(e);a=o.handle,n.set(i,e),qt(o.handle,o.width,o.height)}catch(e){console.warn(`Failed to load tileset texture: ${i}`,e)}o.push({textureHandle:a,columns:r.columns})}Qt(e,{tileWidth:i.tileWidth,tileHeight:i.tileHeight,layers:i.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(i),new Map}}]]);function Ps(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 Ms(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 Ts{constructor(e){this.textureCache_=new Wt,this.shaderCache_=new Wt,this.jsonCache_=new Wt,this.textCache_=new Wt,this.binaryCache_=new Wt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Wt,this.prefabCache_=new Wt,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 zt(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(),At.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const 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"===b(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=b(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 fs(e.type)){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}const s=gs(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 vs(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 At.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 At.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 Cs=Re(null,"Assets");class Es{build(e){const t=e.wasmModule;t?e.insertResource(Cs,new Ts(t)):console.warn("AssetPlugin: No WASM module available")}}const As=new Es;async function Rs(e,t,s){const{entities:n,rootId:i}=await Fs(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 vs(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 Is=10;async function Fs(e,t,s,n,i,o=0){if(o>Is)throw new Error(`Prefab nesting depth exceeded ${Is}. 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 Fs(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};ks(d.components,r),Bs(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 ks(e,t){for(const s of e){const e=_s(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 Bs(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 Ls{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 Rs(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Ds=Re(null,"Prefabs");class Us{constructor(){this.name="PrefabsPlugin",this.dependencies=[Cs]}build(e){const t=e.getResource(Cs);e.insertResource(Ds,new Ls(e.world,t))}}const Ws=new Us;let zs=null,$s=0,Os=0,Hs=0;const Vs=new Float32Array(256);function js(e){zs=e,$s=zs._malloc(64),Os=zs._malloc(64),Hs=zs._malloc(1024)}function Ns(){zs&&($s&&(zs._free($s),$s=0),Os&&(zs._free(Os),Os=0),Hs&&(zs._free(Hs),Hs=0)),zs=null}function Xs(){if(!zs)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return zs}const Ys={r:1,g:1,b:1,a:1},Gs={begin(e){const t=Xs();try{t.HEAPF32.set(e,$s/4),t.draw_begin($s)}catch(e){Oe(e,"Draw.begin")}},end(){try{Xs().draw_end()}catch(e){Oe(e,"Draw.end")}},line(e,t,s,n=1){try{Xs().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.line")}},rect(e,t,s,n=!0){try{Xs().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{Xs().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,i=32){try{Xs().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){Oe(e,"Draw.circle")}},circleOutline(e,t,s,n=1,i=32){try{Xs().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){Oe(e,"Draw.circleOutline")}},texture(e,t,s,n=Ys){try{Xs().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Oe(e,"Draw.texture")}},textureRotated(e,t,s,n,i=Ys){try{Xs().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,i.r,i.g,i.b,i.a)}catch(e){Oe(e,"Draw.textureRotated")}},setLayer(e){Xs().draw_setLayer(e)},setDepth(e){Xs().draw_setDepth(e)},getDrawCallCount:()=>zs?zs.draw_getDrawCallCount():0,getPrimitiveCount:()=>zs?zs.draw_getPrimitiveCount():0,setBlendMode(e){Xs().draw_setBlendMode(e)},setDepthTest(e){Xs().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=Xs();n.HEAPF32.set(s,Os/4),n.draw_mesh(e,t,Os)}catch(s){Oe(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=Xs(),i=At.get(t);if(!i)return;if(Gs.setBlendMode(i.blendMode),Gs.setDepthTest(i.depthTest),0===i.uniforms.size)return void Gs.drawMesh(e,i.shader,s);let o;if(n.HEAPF32.set(s,Os/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,s]of i.uniforms){const n=Js(t);if(!(n<0)){if(bt(s))Vs[o++]=10,Vs[o++]=n,Vs[o++]=s.slot??e++,Vs[o++]=s.textureId;else if("number"==typeof s)Vs[o++]=1,Vs[o++]=n,Vs[o++]=s;else if(Array.isArray(s)){Vs[o++]=s.length,Vs[o++]=n;for(let e=0;e<s.length;e++)Vs[o++]=s[e]}else"w"in s?(Vs[o++]=4,Vs[o++]=n,Vs[o++]=s.x,Vs[o++]=s.y,Vs[o++]=s.z,Vs[o++]=s.w):"z"in s?(Vs[o++]=3,Vs[o++]=n,Vs[o++]=s.x,Vs[o++]=s.y,Vs[o++]=s.z):(Vs[o++]=2,Vs[o++]=n,Vs[o++]=s.x,Vs[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(Vs.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void n.draw_mesh(e,i.shader,Os);n.HEAPF32.set(i.cachedBuffer_.subarray(0,o),Hs/4),n.draw_meshWithUniforms(e,i.shader,Os,Hs,o)}catch(s){Oe(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},qs={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},Ks=new Set;function Js(e){const t=qs[e];return void 0!==t?t:(Ks.has(e)||(Ks.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(qs).join(", ")}`)),-1)}const Qs=new Map;function Zs(e,t,s){Qs.set(e,{fn:t,scene:s??""})}function en(e){Qs.delete(e)}function tn(){Qs.clear()}var sn;exports.DataType=void 0,(sn=exports.DataType||(exports.DataType={}))[sn.Float=1]="Float",sn[sn.Float2=2]="Float2",sn[sn.Float3=3]="Float3",sn[sn.Float4=4]="Float4",sn[sn.Int=5]="Int",sn[sn.Int2=6]="Int2",sn[sn.Int3=7]="Int3",sn[sn.Int4=8]="Int4";let nn=null,on=0,rn=0,an=0;function ln(e){nn=e,on=nn._malloc(262144),rn=nn._malloc(65536),an=nn._malloc(256)}function cn(){nn&&(on&&nn._free(on),rn&&nn._free(rn),an&&nn._free(an),on=0,rn=0,an=0),nn=null}function un(){if(!nn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return nn}const dn={create(e){const t=un(),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,on/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,an,i).set(o),t.geometry_init(s,on,n,an,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,rn,n).set(e.indices),t.geometry_setIndices16(s,rn,n)}else{new Uint32Array(t.HEAPU8.buffer,rn,n).set(e.indices),t.geometry_setIndices32(s,rn,n)}}return s},updateVertices(e,t,s=0){const n=un(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);n.HEAPF32.set(t,on/4),n.geometry_updateVertices(e,on,i,s)},release(e){e>0&&un().geometry_release(e)},isValid:e=>!(!nn||e<=0)&&nn.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return dn.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 dn.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 dn.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 hn=1;const pn=new Map,fn=new Map;function mn(){return pn}function gn(){return fn}class yn{constructor(){this.passes_=[],this.destroyed_=!1,this.id=hn++,pn.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}setEnabled(e,t){const s=this.passes_.find(t=>t.name===e);return s&&(s.enabled=t),this}setUniform(e,t,s){const n=this.passes_.find(t=>t.name===e);return n&&n.floatUniforms.set(t,s),this}setUniformVec4(e,t,s){const n=this.passes_.find(t=>t.name===e);return n&&n.vec4Uniforms.set(t,{...s}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of fn)t===this&&fn.delete(e);pn.delete(this.id)}}}const _n="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";let xn=null;function wn(e){xn=e}function bn(){for(const e of mn().values())e.destroy();mn().clear(),gn().clear(),xn&&Sn.isInitialized()&&Sn.shutdown(),xn=null}function vn(){if(!xn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return xn}const Sn={createStack:()=>new yn,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");gn().set(e,t)},unbind(e){gn().delete(e)},getStack:e=>gn().get(e)??null,init(e,t){try{return vn().postprocess_init(e,t)}catch(s){return Oe(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{vn().postprocess_shutdown()}catch(e){Oe(e,"PostProcess.shutdown")}},resize(e,t){try{vn().postprocess_resize(e,t)}catch(s){Oe(s,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!xn)return!1;try{return xn.postprocess_isInitialized()}catch(e){return Oe(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{vn().postprocess_setBypass(e)}catch(e){Oe(e,"PostProcess.setBypass")}},setOutputViewport(e,t,s,n){try{vn().postprocess_setOutputViewport(e,t,s,n)}catch(e){Oe(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=gn().get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(Sn.isInitialized()||Sn.init(1,1),Sn.setBypass(!1),function(e){const t=vn();try{t.postprocess_clearPasses()}catch(e){return void Oe(e,"PostProcess._applyForCamera:clearPasses")}for(const s of e.passes)if(s.enabled){try{t.postprocess_addPass(s.name,s.shader)}catch(e){Oe(e,`PostProcess._applyForCamera:addPass("${s.name}")`);continue}for(const[e,n]of s.floatUniforms)try{t.postprocess_setUniformFloat(s.name,e,n)}catch(t){Oe(t,`PostProcess._applyForCamera:setUniform("${s.name}", "${e}")`)}for(const[e,n]of s.vec4Uniforms)try{t.postprocess_setUniformVec4(s.name,e,n.x,n.y,n.z,n.w)}catch(t){Oe(t,`PostProcess._applyForCamera:setUniformVec4("${s.name}", "${e}")`)}}}(t)):Sn.setBypass(!0)},_resetAfterCamera(){try{vn().postprocess_clearPasses(),vn().postprocess_setBypass(!0)}catch(e){Oe(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of gn().keys())e(t)||gn().delete(t)},screenStack:null,setScreenStack(e){Sn.screenStack=e},_beginScreenCapture(){try{vn().postprocess_beginScreenCapture()}catch(e){Oe(e,"PostProcess._beginScreenCapture")}},_endScreenCapture(){try{vn().postprocess_endScreenCapture()}catch(e){Oe(e,"PostProcess._endScreenCapture")}},_applyScreenStack(){const e=Sn.screenStack;if(!e||e.isDestroyed||0===e.enabledPassCount)return;const t=vn();try{t.postprocess_clearScreenPasses()}catch(e){return void Oe(e,"PostProcess._applyScreenStack:clearScreenPasses")}for(const s of e.passes)if(s.enabled){try{t.postprocess_addScreenPass(s.name,s.shader)}catch(e){Oe(e,`PostProcess._applyScreenStack:addScreenPass("${s.name}")`);continue}for(const[e,n]of s.floatUniforms)try{t.postprocess_setScreenUniformFloat(s.name,e,n)}catch(t){Oe(t,`PostProcess._applyScreenStack:setScreenUniform("${s.name}", "${e}")`)}for(const[e,n]of s.vec4Uniforms)try{t.postprocess_setScreenUniformVec4(s.name,e,n.x,n.y,n.z,n.w)}catch(t){Oe(t,`PostProcess._applyScreenStack:setScreenUniformVec4("${s.name}", "${e}")`)}}},_executeScreenPasses(){try{vn().postprocess_executeScreenPasses()}catch(e){Oe(e,"PostProcess._executeScreenPasses")}},createBlur:()=>At.createShader(_n,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>At.createShader(_n,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>At.createShader(_n,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createBloom:()=>At.createShader(_n,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_threshold;\nuniform float u_intensity;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 texelSize = 1.0 / u_resolution;\n\n vec3 bloom = vec3(0.0);\n float total = 0.0;\n for (float x = -3.0; x <= 3.0; x += 1.0) {\n for (float y = -3.0; y <= 3.0; y += 1.0) {\n vec2 offset = vec2(x, y) * texelSize * u_radius;\n vec4 s = texture(u_texture, v_texCoord + offset);\n float brightness = dot(s.rgb, vec3(0.2126, 0.7152, 0.0722));\n float w = max(brightness - u_threshold, 0.0);\n bloom += s.rgb * w;\n total += w;\n }\n }\n if (total > 0.0) bloom /= total;\n\n fragColor = vec4(color.rgb + bloom * u_intensity, color.a);\n}\n"),createChromaticAberration:()=>At.createShader(_n,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},Pn=new Map;function Mn(e){Pn.set(e.type,e)}function Tn(e){return Pn.get(e)}Mn({type:"blur",label:"Blur",factory:()=>Sn.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),Mn({type:"bloom",label:"Bloom",factory:()=>Sn.createBloom(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:2,step:.01,defaultValue:.8},{name:"u_intensity",label:"Intensity",min:0,max:10,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:0,max:20,step:.1,defaultValue:4}]}),Mn({type:"vignette",label:"Vignette",factory:()=>Sn.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:3,step:.01,defaultValue:.8},{name:"u_softness",label:"Softness",min:0,max:2,step:.01,defaultValue:.3}]}),Mn({type:"grayscale",label:"Grayscale",factory:()=>Sn.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),Mn({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>Sn.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const Cn=new Map,En=new Map;function An(e){const t=Cn.get(e);t&&(Sn.unbind(e),t.destroy(),Cn.delete(e));const s=En.get(e);if(s){for(const e of s.values())At.releaseShader(e);En.delete(e)}}function Rn(){for(const e of Cn.keys())An(e)}const In=Re({enabled:!0},"PostProcessVolumeConfig"),Fn=new Map,kn=new Map;function Bn(e){const t=kn.get(e);if(void 0!==t)return t;const s=Tn(e);if(!s)return null;const n=s.factory();return kn.set(e,n),n}function Ln(e,t){if(0===t.size){const t=Fn.get(e);return void(t&&(Sn.unbind(e),t.destroy(),Fn.delete(e)))}let s=Fn.get(e);for(s||(s=Sn.createStack(),Fn.set(e,s));s.passCount>0;){const e=s.passes;s.removePass(e[e.length-1].name)}for(const[e,n]of t){if(!n.enabled)continue;const t=Bn(e);if(null!==t){s.addPass(e,t);for(const[t,i]of n.uniforms)s.setUniform(e,t,i)}}s.enabledPassCount>0?Sn.bind(e,s):Sn.unbind(e)}const Dn=ht([et(Se,re)],e=>{const t=[];for(const[s,n,i]of e)t.push({data:n,tx:{x:i.position.x,y:i.position.y}});if(0===t.length)return;const s=[];for(const{data:e,tx:n}of t)e.isGlobal&&s.push({data:e,factor:1});if(s.length>0){const e=function(e){const t=new Map,s=[...e].sort((e,t)=>e.data.priority-t.data.priority);for(const{data:e,factor:n}of s)if(!(n<=0))for(const s of e.effects){if(!s.enabled)continue;const e=t.get(s.type);if(e)for(const[t,i]of Object.entries(s.uniforms)){const s=e.uniforms.get(t)??0;e.uniforms.set(t,s+(i-s)*n)}else{const e=new Map;for(const[t,i]of Object.entries(s.uniforms))e.set(t,i*n);t.set(s.type,{enabled:!0,uniforms:e})}}return t}(s);for(const[t]of Fn)Ln(t,e)}},{name:"PostProcessVolumeSystem"});class Un{constructor(){this.name="PostProcessPlugin"}build(e){e.insertResource(In,{enabled:!0}),e.addSystemToSchedule(exports.Schedule.PostUpdate,Dn)}cleanup(){Rn(),function(){for(const[e,t]of Fn)Sn.unbind(e),t.destroy();Fn.clear();for(const e of kn.values())At.releaseShader(e);kn.clear()}(),Sn.setScreenStack(null)}}const Wn=new Un;var zn;exports.RenderStage=void 0,(zn=exports.RenderStage||(exports.RenderStage={}))[zn.Background=0]="Background",zn[zn.Opaque=1]="Opaque",zn[zn.Transparent=2]="Transparent",zn[zn.Overlay=3]="Overlay";let $n=null,On=0;function Hn(e){$n=e,On=$n._malloc(64)}function Vn(){$n&&On&&($n._free(On),On=0),$n=null}const jn={init(e,t){$n?.renderer_init(e,t)},resize(e,t){$n?.renderer_resize(e,t)},begin(e,t){if($n&&On)try{$n.HEAPF32.set(e,On/4),$n.renderer_begin(On,t??0)}catch(e){Oe(e,"Renderer.begin")}},flush(){try{$n?.renderer_flush()}catch(e){Oe(e,"Renderer.flush")}},end(){try{$n?.renderer_end()}catch(e){Oe(e,"Renderer.end")}},submitSprites(e){if($n)try{$n.renderer_submitSprites(e._cpp)}catch(e){Oe(e,"Renderer.submitSprites")}},submitBitmapText(e){if($n)try{$n.renderer_submitBitmapText(e._cpp)}catch(e){Oe(e,"Renderer.submitBitmapText")}},submitSpine(e){if($n)try{$n.renderer_submitSpine?.(e._cpp)}catch(e){Oe(e,"Renderer.submitSpine")}},submitParticles(e){if($n)try{$n.renderer_submitParticles?.(e._cpp)}catch(e){Oe(e,"Renderer.submitParticles")}},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 Nn=null;function Xn(e){Nn=e}function Yn(){Nn=null}const Gn={enable(){Nn?.gl_enableErrorCheck(!0)},disable(){Nn?.gl_enableErrorCheck(!1)},check:e=>Nn?.gl_checkErrors(e)??0,diagnose(){Nn?.renderer_diagnose()}};class qn{constructor(){this.spineRenderer_=null,this.tilemapRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}setTilemapRenderer(e){this.tilemapRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}beginScreenCapture(){Sn.screenStack&&Sn.screenStack.enabledPassCount>0&&(Sn.isInitialized()||Sn.init(1,1),Sn._applyScreenStack(),Sn._beginScreenCapture())}endScreenCapture(){Sn.screenStack&&Sn.screenStack.enabledPassCount>0&&(Sn._endScreenCapture(),Sn._executeScreenPasses())}render(e){const{registry:t,viewProjection:s,width:n,height:i,elapsed:o}=e;n===this.lastWidth_&&i===this.lastHeight_||(jn.resize(n,i),this.lastWidth_=n,this.lastHeight_=i),jn.setViewport(0,0,n,i),jn.clearBuffers(3),jn.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,i),this.tilemapRenderer_&&this.tilemapRenderer_(),jn.submitSprites(t),jn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):jn.submitSpine(t),jn.submitParticles(t),jn.flush(),this.executeDrawCallbacks(s,o),jn.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==Sn.getStack(r);a&&(Sn._applyForCamera(r),Sn.resize(n.w,n.h),Sn.setOutputViewport(n.x,n.y,n.w,n.h)),jn.setViewport(n.x,n.y,n.w,n.h),jn.setScissor(n.x,n.y,n.w,n.h,!0),jn.clearBuffers(i),jn.setScissor(0,0,0,0,!1),jn.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),this.tilemapRenderer_&&this.tilemapRenderer_(),jn.submitSprites(t),jn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):jn.submitSpine(t),jn.submitParticles(t),jn.flush(),this.executeDrawCallbacks(s,o),jn.end(),a&&Sn._resetAfterCamera()}executeDrawCallbacks(e,t){const s=Qs;if(s.size>0){Gs.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)}Gs.end();for(const e of n)en(e)}}}const Kn="__scene_transition_overlay__";class Jn{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class Qn{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,ve,{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),Zs(e,t,this.instance_.config.name)}bindPostProcess(e,t){Sn.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){Sn.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,ve)){const s=this.app_.world.get(e,ve);s.persistent=t,this.app_.world.insert(e,ve,s)}}}class Zn{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}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())en(t);for(const t of e.postProcessBindings.keys())Sn.unbind(t)}this.transition_&&(en(Kn),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}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},Zs(Kn,()=>{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;Gs.setLayer(9999),Gs.setDepth(9999),Gs.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,en(Kn),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,en(Kn),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 Jn(t);this.scenes_.set(e,s);const n=new Qn(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Cs)?this.app_.getResource(Cs):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 Jn(t);this.scenes_.set(e,s);const n=new Qn(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Cs)?this.app_.getResource(Cs):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,ve)){if(this.app_.world.get(e,ve).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())en(e);s.drawCallbacks.clear();for(const e of s.postProcessBindings.keys())Sn.unbind(e);s.postProcessBindings.clear(),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(Cs)&&(i.assetServer=this.app_.getResource(Cs));const o=await vs(this.app_.world,n,i);e.loadedAssets=s;for(const s of o.values())e.entities.add(s),this.app_.world.insert(s,ve,{scene:t,persistent:!1})}if(s.systems)for(const{schedule:e,system:n}of s.systems){const s=ti(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(Cs)?this.app_.getResource(Cs):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)At.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.postProcessBindings.values())s.setAllPassesEnabled(t)}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 ei=Re(null,"SceneManager");function ti(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(ei).getSceneStatus(t)&&s._fn(...n)}}}const si=ht([Fe(ei),Ie(Le)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),ni={name:"SceneManager",build(e){const t=new Zn(e);e.insertResource(ei,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(ei),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,si)}};class ii{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 rt,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 Ge,this.resources_=new Be;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new ii}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 $e(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(ei).register(e),this}setInitialScene(e){return this.getResource(ei).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new ft(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(Le)||this.resources_.insert(Le,{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 ft(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(Le,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(exports.Schedule.Startup),this.lastTime_=c(),this.mainLoop())}quit(){this.running_=!1,tn();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=[Yn,Vn,bn,cn,Ct,Ns];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(Le);t.delta=e,t.elapsed+=e,t.frameCount++}}function oi(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 ri=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ai(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 li=[];function ci(e){if(e<li.length)return li[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 li.push(t),t}function ui(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,ve);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=ai(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=d*r,a=hi(-u,u,-d,d,-i.farPlane,i.farPlane)}else a=fi(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const h=gi(o.position.x,o.position.y,o.position.z),p=ci(c.length);p.entity=e,p.viewProjection.set(_i(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 di=new Float32Array(16);function hi(e,t,s,n,i,o){const r=di;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 pi=new Float32Array(16);function fi(e,t,s,n){const i=pi;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 gi(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 yi=new Float32Array(16);function _i(e,t){const s=yi;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 xi={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function wi(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 bi=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 vi=null,Si=null;function Pi(e,t){e.has(t,ce)||e.insert(t,ce,{texture:V,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0})}function Mi(e,t){switch(e){case xi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case xi.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case xi.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 Ti(e,t,s,n){if(!e.has(t,bi))return;const i=e.get(t,bi),o=Mi(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,bi,i)}function Ci(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 Ai(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 Ii(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 Fi(e,t){if(vi&&Si){const e=vi.getUIRectComputedWidth(Si,t);if(e>0)return e}return e.size.x}function ki(e,t){if(vi&&Si){const e=vi.getUIRectComputedHeight(Si,t);if(e>0)return e}return e.size.y}function Bi(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 Li(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function Di(e,t,s,n,i){if(!e.has(t,bi))return;const o=e.get(t,bi),r=wi(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 Ui(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 Wi=.1,zi=30,$i={r:.3,g:.5,b:.8,a:1},Oi={Left:0,Center:1,Right:2},Hi={Top:0,Middle:1,Bottom:2},Vi={Visible:0,Clip:1,Ellipsis:2},ji=q("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Oi.Left,verticalAlign:Hi.Top,wordWrap:!0,overflow:Vi.Visible,lineHeight:1.2});class Ni{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,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=Ai(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===Vi.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,Ri(p)),n.height=Math.max(n.height,Ri(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===Vi.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 Hi.Top:w=u;break;case Hi.Middle:w=u+(f-2*u-x)/2;break;case Hi.Bottom:w=f-x-u;break;default:w=u}w<0&&(w=0)}else w=u;let b=w;for(const t of l){let n;switch(e.align){case Oi.Left:n=u;break;case Oi.Center:n=p/2;break;case Oi.Right:n=p-u;break;default:n=u}s.fillText(t,n,b),b+=c}i&&e.overflow===Vi.Clip&&s.restore();const v=s.getImageData(0,0,p,f),S=new Uint8Array(v.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 Oi.Left:return"left";case Oi.Center:return"center";case Oi.Right:return"right"}}}const Xi=Ui({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?Fi(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?ki(e.uiRect,e.entity):0});class Yi{build(e){ee("Text",ji);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Ni(t),n=e.world,i=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,ht([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,ji));for(const e of i.keys())if(!n.valid(e)||!n.has(e,ji)){if(n.valid(e)&&n.has(e,ce)){const t=n.get(e,ce);n.insert(e,ce,{texture:V,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([ji]);for(const t of e){const e=n.get(t,ji),o=n.has(t,bi)?n.get(t,bi):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!Xi.changed(a,r)){if(n.has(t,ce)&&n.get(t,ce).texture!==V)continue}Pi(n,t);const l=o?{size:{x:Fi(o,t),y:ki(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,Xi.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Gi=new Yi,qi=0,Ki=1,Ji=se("UIMask",{enabled:!0,mode:qi});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],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,b=n*u-r*a,v=i*c-o*l,S=i*u-r*l,P=o*u-r*c,M=d*g-h*m,T=d*y-p*m,C=d*_-f*m,E=h*y-p*g,A=h*_-f*g,R=p*_-f*y;let I=x*R-w*A+b*E+v*C-S*T+P*M;return 0===I||(I=1/I,s[0]=(l*R-c*A+u*E)*I,s[1]=(o*A-i*R-r*E)*I,s[2]=(g*P-y*S+_*v)*I,s[3]=(p*S-h*P-f*v)*I,s[4]=(c*C-a*R-u*T)*I,s[5]=(n*R-o*C+r*T)*I,s[6]=(y*b-m*P-_*w)*I,s[7]=(d*P-p*b+f*w)*I,s[8]=(a*A-l*C+u*M)*I,s[9]=(i*C-n*A-r*M)*I,s[10]=(m*S-g*b+_*x)*I,s[11]=(h*b-d*S-f*x)*I,s[12]=(l*T-a*E-c*M)*I,s[13]=(n*E-i*T+o*M)*I,s[14]=(g*w-m*v-y*x)*I,s[15]=(d*v-h*w+p*x)*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],d=s[3]*a+s[7]*l+s[15];return{x:c/d,y:u/d}}function to(e,t){return 2*Math.atan2(e,t)}function so(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 no(e,t,s,n,i,o,r){if(!e.has(t,bi)||!e.has(t,re))return null;const a=e.get(t,bi),l=e.get(t,re),c=Fi(a,t)*l.worldScale.x,u=ki(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=to(l.worldRotation.z,l.worldRotation.w),w=Math.cos(x),b=Math.sin(x),v=[[d+m*w-y*b,h+m*b+y*w],[d+g*w-y*b,h+g*b+y*w],[d+g*w-_*b,h+g*b+_*w],[d+m*w-_*b,h+m*b+_*w]];let S=1/0,P=1/0,M=-1/0,T=-1/0;for(const[e,t]of v){const[a,l]=so(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 io(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=[],d=new Set,h=new Set;for(const e of l){const s=t.get(e,Ji);s.enabled&&(d.add(e),s.mode===Ki?(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;Bi(t,e,e=>{if(i.has(e)){if(t.get(e,Ji).mode===qi)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,Ji).mode===qi){const e=no(t,s,o,r,a,l,c);e&&(n=Qi(u,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=no(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;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,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class oo{build(e){if(ee("UIMask",Ji),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(io(e.wasmModule,e.world))}}const ro=new oo,ao=se("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),lo=se("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),co={Normal:0,Hovered:1,Pressed:2,Disabled:3},uo=q("Button",{state:co.Normal,transition:null});class ho{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 po=Re(new ho,"UIEvents");class fo{build(e){ee("UIRect",bi);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){vi=e,Si=t}(s,n);e.addSystemToSchedule(exports.Schedule.PreUpdate,ht([Ie(xt)],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,ht([Ie(xt)],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,ht([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const mo=new fo;let go=!1,yo=!1;function _o(){return go}function xo(){return yo}const wo=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 bo(e,t,s,n){t.emit(s,n,s),Bi(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 vo{build(e){ee("Interactable",ao),ee("Button",uo);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),i=new ho;e.insertResource(po,i);let o=null,r=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,ht([Ie(gt),Ie(xt)],(e,a)=>{if(i.drain(),_o()&&!xo())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=u(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;wo.update(a.viewProjection);const p=eo(d,h,wo.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,lo)){const e=t.get(o,lo);e.hovered=!1,t.insert(o,lo,e),i.emit(o,"hover_exit")}if(null!==_){Li(t,_,lo);const e=t.get(_,lo);e.hovered=!0,t.insert(_,lo,e),i.emit(_,"hover_enter")}o=_}if(m&&null!==_){const e=t.get(_,lo);e.pressed=!0,e.justPressed=!0,t.insert(_,lo,e),r=_,bo(t,i,_,"press")}if(g&&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),bo(t,i,r,"release"),r===o&&bo(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(exports.Schedule.Update,ht([],()=>{const e=t.getEntitiesWithComponents([uo]);for(const s of e){if(Li(t,s,ao,{enabled:!0}),!t.has(s,lo))continue;const e=t.get(s,lo),n=t.get(s,uo),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,ce)){const o=t.get(s,ce);o.color=Ci(n.transition,i.enabled,e.pressed,e.hovered),t.insert(s,ce,o)}}},{name:"ButtonSystem"}))}}const So=new vo,Po=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}),Mo=q("Focusable",{tabIndex:0,isFocused:!1});class To{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 Co=Re(new To,"FocusManager");class Eo{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(ee("TextInput",Po),_o()&&!xo())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(Co);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,Po)?n:null}const g=()=>{c||null===m()||b()},y=()=>{c=!0},_=()=>{c=!1,b()},x=t=>{const n=m();if(null===n)return;if("Escape"===t.key)return void v();const i=s.get(n,Po);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(po).emit(n,"submit"),void v()}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,Po);n.focused=!1,n.dirty=!0;e.getResource(Co).blur()}};function b(){const t=m();if(null===t)return;const n=s.get(t,Po);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(po).emit(t,"change")}n.cursorPos=f.selectionStart??i.length,n.dirty=!0,S()}function v(){const t=m();if(null!==t){const e=s.get(t,Po);e.focused=!1,e.dirty=!0}e.getResource(Co).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=Ri(Math.max(i.width,c)),i.height=Ri(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=Ai(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=Ai(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 b=n.get(e);void 0!==b&&w.releaseTexture(b);const v=w.createTexture(c,d,r,x.length,1,!0);n.set(e,v);const S=s.get(e,ce);S.texture=v,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,ht([Ie(Co)],e=>{const t=s.getEntitiesWithComponents([Po]);for(const e of t)Li(s,e,Mo,{tabIndex:0,isFocused:!1}),Li(s,e,ao,{enabled:!0,blockRaycast:!0});const n=m();if(n!==P){if(null!==P&&s.valid(P)&&s.has(P,Po)){const e=s.get(P,Po);e.focused=!1,e.dirty=!0,f.blur()}null!==n&&function(e){const t=s.get(e,Po);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,ht([],()=>{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,Po).dirty=!0}const r=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Po)||(r.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Po,bi]);for(const e of a){const t=s.get(e,Po);if(!t.dirty)continue;const n=s.get(e,bi),i=Math.ceil(n.size.x),o=Math.ceil(n.size.y);i<=0||o<=0||(Pi(s,e),M(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Ao=new Eo,Ro={Simple:0,Sliced:1,Tiled:2,Filled:3},Io={Horizontal:0,Vertical:1},Fo={Left:0,Right:1,Bottom:2,Top:3},ko=q("Image",{texture:V,color:{r:1,g:1,b:1,a:1},imageType:Ro.Simple,fillMethod:Io.Horizontal,fillOrigin:Fo.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Bo=Ui({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?Fi(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?ki(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class Lo{build(e){ee("Image",ko);const t=e.world,s=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,ht([],()=>{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,bi)?t.get(n,bi):null,o={image:e,uiRect:i,entity:n},r=s.get(n);if(r&&!Bo.changed(r,o))continue;Pi(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=Fi(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===Ro.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===Io.Horizontal?e.fillOrigin===Fo.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===Fo.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===Ro.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,Bo.take(o))}else a.color.a=0,t.insert(n,ce,a),s.set(n,Bo.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const Do=new Lo,Uo=q("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Wo=q("ToggleGroup",{allowSwitchOff:!1});class zo{build(e){ee("Toggle",Uo),ee("ToggleGroup",Wo);const t=e.world,s=new Set;e.addSystemToSchedule(exports.Schedule.Update,ht([Ie(po)],e=>{const n=t.getEntitiesWithComponents([Uo]);if(!_o()||xo()){const i=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,Uo);n.isOn&&0!==n.group&&t.valid(n.group)&&(i.has(n.group)?(n.isOn=!1,t.insert(e,Uo,n)):i.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,Uo);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(Li(t,s,ao,{enabled:!0}),!t.has(s,lo))continue;const n=t.get(s,lo),i=t.get(s,Uo),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,Uo,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,Uo);i.isOn&&(i.isOn=!1,t.insert(n,Uo,i),e.emit(n,"change"))}}e.emit(s,"change")}if(i.transition&&t.has(s,ce)){const e=t.get(s,ce);e.color=Ci(i.transition,r.enabled,n.pressed,n.hovered),t.insert(s,ce,e)}}}for(const e of n){const s=t.get(e,Uo);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 $o=new zo,Oo=xi,Ho=q("ProgressBar",{value:0,fillEntity:0,direction:xi.LeftToRight});function Vo(e,t,s,n){if(!e.has(t,bi))return;const i=e.get(t,bi),o=s/2,r=n/2,a={left:-o,bottom:-r,right:o,top:r},l=wi(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 jo{build(e){ee("ProgressBar",Ho);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,ht([],()=>{const e=t.getEntitiesWithComponents([Ho,bi]);for(const s of e){const e=t.get(s,Ho);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,bi),i=Math.max(0,Math.min(1,e.value));Ti(t,e.fillEntity,e.direction,i);const o=Fi(n,s),r=ki(n,s);Vo(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const No=new jo,Xo=q("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Yo=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 Go{build(e){ee("Draggable",Xo),ee("DragState",Yo);const t=e.world,s=e.getResource(po);let n=null,i={x:0,y:0},o=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,ht([Ie(gt),Ie(xt)],(e,r)=>{if(_o()&&!xo())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Xo,lo]);let s=null,o=-1/0,r=-1;for(const n of e){if(!t.get(n,Xo).enabled)continue;if(t.get(n,lo).hovered){let e=0;t.has(n,ce)&&(e=t.get(n,ce).layer);const i=Ii(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,Yo)||t.insert(s,Yo);const e=t.get(s,Yo),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,Yo)){t.get(n,Yo).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,Xo);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=n,n=null;t.get(o,Yo).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Yo))return void(o=null);const n=t.get(o,Yo),i=t.get(o,Xo),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=to(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 qo=new Go,Ko=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 Jo(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 Qo(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 Zo{build(e){ee("ScrollView",Ko);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(exports.Schedule.PostUpdate,ht([Ie(gt),Ie(xt),Ie(Le)],(e,i,o)=>{const r=_o()&&!xo(),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([Ko,bi]);for(const o of l){Li(t,o,Ji,{enabled:!0,mode:qi});const l=t.get(o,Ko),c=t.get(o,bi);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=Fi(c,o),h=ki(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,bi)){const e=t.get(r,bi);a=Fi(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,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){Li(t,o,ao,{enabled:!0,blockRaycast:!0});const s=t.has(o,lo)?t.get(o,lo):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=Jo(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=Jo(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=Jo(l.scrollY,0,g,h);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Jo(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=Qo(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)<Wi&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Wi?(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=Qo(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)<Wi&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Wi?(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 er=new Zo,tr=xi,sr=q("Slider",{value:0,minValue:0,maxValue:1,direction:xi.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function nr(e,t,s,n,i,o){const r=Fi(n,i)*s.worldScale.x,a=ki(n,i)*s.worldScale.y,l=to(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 xi.LeftToRight:return r>0?(p-m)/r:0;case xi.RightToLeft:return r>0?1-(p-m)/r:0;case xi.BottomToTop:return a>0?(f-g)/a:0;case xi.TopToBottom:return a>0?1-(f-g)/a:0}}function ir(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case xi.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case xi.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case xi.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case xi.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class or{build(e){ee("Slider",sr);const t=e.world;let s=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,ht([Ie(gt),Ie(xt),Ie(po)],(e,n,i)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([sr,bi]);for(const r of o){const o=t.get(r,sr),a=t.get(r,bi);if(!_o()||xo()){if(t.has(r,re)){Li(t,r,ao,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Li(t,o.handleEntity,ao,{enabled:!0,blockRaycast:!1});const l=t.get(r,re),c=t.has(r,lo)?t.get(r,lo):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,lo)&&(u=t.get(o.handleEntity,lo).justPressed),u&&(s=r),s===r&&e.isMouseButtonDown(0)){let e=nr(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,sr,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=Fi(a,r),d=ki(a,r),h={left:-u/2,bottom:-d/2,right:u/2,top:d/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(Ti(t,o.fillEntity,o.direction,c),Di(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,bi)){const e=t.get(o.handleEntity,bi);ir(e,o.direction,c),t.insert(o.handleEntity,bi,e),Di(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const rr=new or;class ar{build(e){ee("Focusable",Mo);const t=e.world,s=new To;e.insertResource(Co,s),e.addSystemToSchedule(exports.Schedule.Update,ht([Ie(gt),Ie(po)],(e,n)=>{if(_o()&&!xo())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const i=t.getEntitiesWithComponents([Mo]);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,Mo);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,Mo)){t.get(i,Mo).isFocused=!1,n.emit(i,"blur",i)}s.focus(e);t.get(e,Mo).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const lr=new ar,cr=q("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function ur(){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 dr{build(e){ee("SafeArea",cr);const t=e.world;let n=ur(),i=!0,o=0,r=0;if(s()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=ur(),i=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=ur(),i=!0});e.addSystemToSchedule(exports.Schedule.PreUpdate,ht([Ie(xt)],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([cr,bi]);for(const e of d){const s=t.get(e,cr),i=t.get(e,bi),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,bi,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const hr=new dr,pr=q("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let fr=null;class mr{build(e){ee("ListView",pr);const t=e.world,s=new Map;fr=s,e.addSystemToSchedule(exports.Schedule.PostUpdate,ht([Ie(gt)],e=>{const n=_o()&&!xo();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([pr,bi]);for(const o of i){Li(t,o,ao,{enabled:!0,blockRaycast:!0}),Li(t,o,Ji,{enabled:!0,mode:qi});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,pr),a=t.get(o,bi),l=ki(a,o),c=Fi(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 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,be,{value:`ListItem_${e}`}),t.insert(s,bi,{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 gr=new mr,yr=q("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class _r{build(e){ee("Dropdown",yr);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*zi;t.insert(i,bi,{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:V,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)*zi;t.insert(o,be,{value:`Option_${e}`}),t.insert(o,bi,{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,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:V,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,ao,{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,ji,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Oi.Left,verticalAlign:Hi.Middle,wordWrap:!1,overflow:Vi.Clip,lineHeight:1.2}),t.insert(c,bi,{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),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,ji))return;const n=t.get(s,ji);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,ji,{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,ao)&&t.insert(e,ao,{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?{...$i}:{r:.95,g:.95,b:.95,a:1};t.insert(n,ce,{texture:V,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 h(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(exports.Schedule.Update,ht([Ie(gt),Ie(po)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const p=_o()&&!xo(),f=t.getEntitiesWithComponents([yr]);for(const m of f){const f=t.get(m,yr);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;Li(t,m,ao,{enabled:!0,blockRaycast:!0});const y=t.has(m,lo)?t.get(m,lo):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,lo))continue;if(t.get(s,lo).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,lo))continue;if(t.get(n,lo).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 xr=new _r,wr=0,br=0,vr=2,Sr=q("LayoutGroup",{direction:wr,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:br,reverseOrder:!1});class Pr{build(e){ee("LayoutGroup",Sr);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,ht([],()=>{const e=t.getEntitiesWithComponents([Sr,bi,fe]);for(const s of e){const e=t.get(s,Sr),n=t.get(s,bi),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,bi)&&t.has(e,re)&&o.push({entity:e,rect:t.get(e,bi)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=Fi(n,s),a=ki(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=Fi(n.rect,n.entity),p=ki(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===br?(1-c)*a-u.top-(1-m)*p:e.childAlignment===vr?-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===br?-l*r+u.left+f*i:e.childAlignment===vr?(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 Mr=new Pr;class Tr{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(exports.Schedule.PostUpdate,ht([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const Cr=new Tr;async function Er(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const Ar=Re({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),Rr={r:.2,g:.4,b:1,a:.7},Ir={r:.2,g:1,b:.2,a:.7},Fr={r:.2,g:1,b:1,a:.7},kr={r:1,g:1,b:.2,a:.5},Br={r:1,g:.2,b:.2,a:.8},Lr={r:1,g:.2,b:.2,a:1},Dr=1.5,Ur=16;function Wr(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){switch(e){case Ee.Static:return Rr;case Ee.Kinematic:return Fr;default:return Ir}}function $r(e,t,s,n,i,o){const r=Math.cos(i),a=Math.sin(i),l=[{x:-s,y:-n},{x:s,y:-n},{x:s,y:n},{x:-s,y:n}].map(s=>({x:e+s.x*r-s.y*a,y:t+s.x*a+s.y*r}));for(let e=0;e<4;e++)Gs.line(l[e],l[(e+1)%4],o,Dr)}function Or(e,t,s,n,i,o){const r=Math.cos(i),a=Math.sin(i),l=(s,n)=>({x:e+s*r-n*a,y:t+s*a+n*r}),c=l(-s,n),u=l(s,n),d=l(-s,-n),h=l(s,-n);Gs.line(c,d,o,Dr),Gs.line(u,h,o,Dr);for(let e=0;e<Ur;e++){const t=e/Ur*Math.PI,i=(e+1)/Ur*Math.PI,r=l(-s*Math.cos(t),n+s*Math.sin(t)),a=l(-s*Math.cos(i),n+s*Math.sin(i));Gs.line(r,a,o,Dr)}for(let e=0;e<Ur;e++){const t=Math.PI+e/Ur*Math.PI,i=Math.PI+(e+1)/Ur*Math.PI,r=l(-s*Math.cos(t),-n+s*Math.sin(t)),a=l(-s*Math.cos(i),-n+s*Math.sin(i));Gs.line(r,a,o,Dr)}}function Hr(e,t,s,n){const i=e+.5*s,o=t+.5*n;Gs.line({x:e,y:t},{x:i,y:o},Br,Dr);const r=Math.sqrt(s*s+n*n);if(r<1)return;const a=Math.PI/6,l=s/r,c=n/r,u=i-6*(l*Math.cos(a)-c*Math.sin(a)),d=o-6*(l*Math.sin(a)+c*Math.cos(a)),h=i-6*(l*Math.cos(a)+c*Math.sin(a)),p=o-6*(-l*Math.sin(a)+c*Math.cos(a));Gs.line({x:i,y:o},{x:u,y:d},Br,Dr),Gs.line({x:i,y:o},{x:h,y:p},Br,Dr)}function Vr(e,t,s){const n=e.getResource(Ar);if(!n||!n.enabled)return;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=e.world.getEntitiesWithComponents([Pe,re]);let r=null;n.showVelocity&&e.hasResource(t)&&(r=e.getResource(t));for(const t of o){const s=e.world.get(t,Pe);if(!s.enabled)continue;const o=e.world.get(t,re),a=o.worldPosition.x,l=o.worldPosition.y,c=Wr(o.worldRotation);if(n.showColliders){if(e.world.has(t,Me)){const n=e.world.get(t,Me),o=n.isSensor?kr:zr(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,d=Math.cos(c),h=Math.sin(c);$r(a+r*d-u*h,l+r*h+u*d,n.halfExtents.x*i,n.halfExtents.y*i,c,o)}if(e.world.has(t,Te)){const n=e.world.get(t,Te),o=n.isSensor?kr:zr(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,d=Math.cos(c),h=Math.sin(c),p=a+r*d-u*h,f=l+r*h+u*d;Gs.circleOutline({x:p,y:f},n.radius*i,o,Dr,32)}if(e.world.has(t,Ce)){const n=e.world.get(t,Ce),o=n.isSensor?kr:zr(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,d=Math.cos(c),h=Math.sin(c);Or(a+r*d-u*h,l+r*h+u*d,n.radius*i,n.halfHeight*i,c,o)}}if(n.showVelocity&&r&&s.bodyType===Ee.Dynamic){const e=r.getLinearVelocity(t);Hr(a,l,e.x*i,e.y*i)}}if(n.showContacts&&e.hasResource(s)){const t=e.getResource(s);for(const e of t.collisionEnters)Gs.circle({x:e.contactX,y:e.contactY},3,Lr,!0,32)}}const jr=Re({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Nr=Re(null,"PhysicsAPI");function Xr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Yr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Gr{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(jr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Er(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,ht([Ie(Le)],a=>{const l=r.getEntitiesWithComponents([Pe,re]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,Pe),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=Xr(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),qr(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===Ee.Kinematic){const e=Xr(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=Xr(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=Yr(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(jr,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,i)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Nr,Kr._fromModule(n)),function(e,t,s){e.insertResource(Ar,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),Zs("physics-debug-draw",()=>{Vr(e,t,s)})}(e,Nr,jr),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function qr(e,t,s){const n=e.world;if(n.has(s,Me)){const e=n.get(s,Me);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,Ce)){const e=n.get(s,Ce);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 Kr{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(Kr.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)}static setDebugDraw(e,t){const s=e.getResource(Ar);s&&(s.enabled=t,e.insertResource(Ar,s))}static setDebugDrawConfig(e,t){const s=e.getResource(Ar);s&&e.insertResource(Ar,{...s,...t})}}const Jr={nearest:0,linear:1},Qr={repeat:0,clamp:1,mirror:2};function Zr(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=Jr[n.filterMode??"linear"]??1,a=Qr[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 ea(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 ta(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,b=u*h,v=u*p;return new Float32Array([(1-(y+x))*i,(m+v)*i,(g-b)*i,0,(m-v)*o,(1-(f+x))*o,(_+w)*o,0,(g+b)*r,(_-w)*r,(1-(f+y))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function sa(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=ms(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]=Zr(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=gs(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"===b(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=ea(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=Zr(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 Gr("",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=ms(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=b(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=Zr(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=ms(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=At.createShader(e.vertexSource,e.fragmentSource),n[i]=r),s[o]=At.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=ms(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=$t(n),r=new Map;for(const t of o)try{const n=await s.loadPixels(t);r.set(t,Zr(e,n))}catch{r.set(t,0)}Vt(Ot(i,n,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(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=ms(t.type);for(const o of i){if("tilemap"!==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=cs(JSON.parse(t));if(!n)continue;const o=[];for(const t of n.tilesets){const n=us(i,t.image);let r=0;try{const t=await s.loadPixels(n);r=Zr(e,t),qt(r,t.width,t.height)}catch{}o.push({textureHandle:r,columns:t.columns})}Qt(i,{tileWidth:n.tileWidth,tileHeight:n.tileHeight,layers:n.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${i}`,e)}}}}}(s,n,i),await async function(e,t){const s=[],n=new Set;for(const t of e.entities)for(const e of t.components){const t=ms(e.type);for(const i of t){if("audio"!==i.type)continue;const t=e.data[i.field];"string"==typeof t&&t&&!n.has(t)&&(n.add(t),s.push(t))}}0!==s.length&&(t?await Promise.all(s.map(async e=>{try{const s=await t.readBinary(e);await Xt.preloadFromData(e,s.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await Xt.preloadAll(s).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(n,i),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=ms(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=bs(t.world,n);if(c&&t.hasResource(ei))for(const e of m.values())t.world.insert(e,ve,{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=gs(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=U);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=ta(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(Cs);e&&e.setAddressableManifest(l)}}function na(e,t,s){return{name:e,async setup(){await sa({...s,sceneData:t,sceneName:e})}}}async function ia(e){const{app:t,firstScene:s,aspectRatio:n}=e;oi(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(ei);for(const t of e.scenes)o.register(na(t.name,t.data,i));s&&(o.setInitial(s),await o.load(s)),void 0!==n&&Ms(t.world,n)}class oa{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=gs(e.type);if(i){const n=e.data[i.skeletonField],o=e.data[i.atlasField];n&&("binary"===b(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=ms(e.type);for(const i of o){const o=e.data[i.field];"string"==typeof o&&o&&("font"===i.type?(n.add(o),t.add(o)):"material"===i.type||"anim-clip"===i.type||"tilemap"===i.type?t.add(o):"audio"===i.type&&s.add(o))}}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=b(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 ra="__preview__";const aa={create(e){const t=e.depth??!0,s="linear"===e.filter,n=(t?1:0)|(s?2:0),i=jn.createRenderTarget(e.width,e.height,n);return{_handle:i,textureId:jn.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:s?"linear":"nearest"}},release(e){jn.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(jn.releaseRenderTarget(e._handle),aa.create({width:t,height:s,depth:e._depth,filter:e._filter})),begin(e,t){jn.begin(t,e._handle)},end(){jn.end()},getDepthTexture:e=>jn.getTargetDepthTexture(e._handle)};var la;exports.LogLevel=void 0,(la=exports.LogLevel||(exports.LogLevel={}))[la.Debug=0]="Debug",la[la.Info=1]="Info",la[la.Warn=2]="Warn",la[la.Error=3]="Error";class ca{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 ua{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new ca)}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 da=new ua;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},pa={Running:0,Paused:1,Completed:2,Cancelled:3},fa={None:0,Restart:1,PingPong:2};const ma=1.70158,ga=2.70158,ya=2.5949095;const _a=2*Math.PI/3,xa=2*Math.PI/4.5;const wa=7.5625,ba=2.75;const va=1e-6;function Sa(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 ga*e*e*e-ma*e*e}(t);case ha.EaseOutBack:return function(e){const t=e-1;return 1+ga*t*t*t+ma*t*t}(t);case ha.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-ya)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+ya)+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)*_a)}(t);case ha.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*_a)+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)*xa)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*xa)/2+1}(t);case ha.EaseOutBounce:return function(e){return e<1/ba?wa*e*e:e<2/ba?wa*(e-=1.5/ba)*e+.75:e<2.5/ba?wa*(e-=2.25/ba)*e+.9375:wa*(e-=2.625/ba)*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 Pa=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:pa.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)===pa.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==pa.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=Sa(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=pa.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===pa.Running&&(t.state=pa.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===pa.Paused&&(t.state=pa.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=pa.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:pa.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 Pa.getState(this.id)}bezier(e,t,s,n){return Pa.setBezier(this.id,e,t,s,n),this}then(e){return e instanceof Ma?Pa.setSequenceNext(this.id,e.id):Pa.setSequenceNextExternal(this.id,e),this}pause(){Pa.pause(this.id)}resume(){Pa.resume(this.id)}cancel(){Pa.cancel(this.id)}}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?(Pa.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 Ca=null,Ea=null;function Aa(e,t){Ca=e,Ea=t,Pa.init(e,t)}function Ra(){Pa.shutdown(),Ca=null,Ea=null}function Ia(){if(!Ca)throw new Error("Tween API not initialized");return Ca}function Fa(){if(!Ea)throw new Error("Tween API not initialized");return Ea}const ka={to(e,t,s,n,i,o){const r=Ia(),a=Fa(),l=o?.easing??ha.Linear,c=o?.delay??0,u=o?.loop??fa.None,d=o?.loopCount??0,h=r._anim_createTween(a,e,t,s,n,i,l,c,u,d);return new Ta(r,a,h)},value(e,t,s,n,i){const o=Pa.create(e,t,s,n,i);return new Ma(o)},cancel(e){Ia()._anim_cancelTween(Fa(),e.entity)},cancelAll(e){Ia()._anim_cancelAllTweens(Fa(),e)},update(e){Ia()._anim_updateTweens(Fa(),e),Pa.update(e)}};class Ba{constructor(){this.name="AnimationPlugin"}build(e){Aa(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(exports.Schedule.Update,ht([Ie(Le)],e=>{ka.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(exports.Schedule.Update,ht([Ie(Le)],e=>{Nt(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){Ra()}}const La=new Ba;var Da;exports.AttenuationModel=void 0,(Da=exports.AttenuationModel||(exports.AttenuationModel={}))[Da.Linear=0]="Linear",Da[Da.Inverse=1]="Inverse",Da[Da.Exponential=2]="Exponential";const Ua={model:exports.AttenuationModel.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function Wa(e,t=Ua){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 za(e,t,s,n,i){const o=e-s;return Math.max(-1,Math.min(1,o/i))}const $a=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}),Oa=q("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;Xt.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,ht([Ie(Le)],t=>{if(!(!_o()||xo()))return void(c&&(l=!1,c=!1));c=!0;const n=e.world;let i=0,u=0,d=!1;const h=n.getEntitiesWithComponents([Oa,le]);for(const e of h){if(n.get(e,Oa).enabled){const t=n.get(e,le);i=t.position.x,u=t.position.y,d=!0;break}}const p=n.getEntitiesWithComponents([$a]);a.clear();for(const e of p){const t=n.get(e,$a);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=Xt.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=Wa(Math.sqrt(p*p+f*f),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=za(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(),Xt.dispose()}}const Va=new Ha;let ja=null,Na=null;function Xa(e,t){ja=e,Na=t}function Ya(){ja=null,Na=null}const Ga={update(e){ja&&Na&&ja.particle_update?.(Na,e)},play(e){ja&&Na&&ja.particle_play?.(Na,e)},stop(e){ja&&Na&&ja.particle_stop?.(Na,e)},reset(e){ja&&Na&&ja.particle_reset?.(Na,e)},getAliveCount:e=>ja?ja.particle_getAliveCount?.(e)??0:0};class qa{constructor(){this.name="ParticlePlugin"}build(e){Xa(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(exports.Schedule.Update,ht([Ie(Le)],e=>{Ga.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){Ya()}}const Ka=new qa,Ja=1e6;class Qa{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.sourceEntityKeys_=new Map}build(e){ts(e.wasmModule);const t=e.world,s=this.initializedLayers_,n=this.sourceEntityKeys_;e.pipeline?.setTilemapRenderer(()=>{const i=e.getResource(xt),o=i?.valid?i.worldLeft:-1e6,r=i?.valid?i.worldBottom:-1e6,a=i?.valid?i.worldRight:Ja,l=i?.valid?i.worldTop:Ja,c=t.getEntitiesWithComponents([os,re]);for(const e of c){const n=t.tryGet(e,os),i=t.tryGet(e,re);if(!n||!i)continue;if(!n.visible)continue;const c=n.texture;if(!c)continue;const u=Kt(c);if(!u)continue;if(!s.has(e)){if(ns.initLayer(e,n.width,n.height,n.tileWidth,n.tileHeight),n.tiles.length>0){const t=new Uint16Array(n.tiles.length);for(let e=0;e<n.tiles.length;e++)t[e]=n.tiles[e];ns.setTiles(e,t)}s.add(e)}const d=n.tileWidth/u.width,h=n.tileHeight/u.height,p=n.tint,f=n.parallaxFactor;ns.submitLayer(e,c,n.layer,0,n.tilesetColumns,d,h,i.worldPosition.x,i.worldPosition.y,o,r,a,l,p.r,p.g,p.b,p.a,n.opacity,f.x,f.y)}const u=t.getEntitiesWithComponents([is,re]);for(const e of u){if(t.tryGet(e,os))continue;const i=t.tryGet(e,is),c=t.tryGet(e,re);if(!i?.source||!c)continue;const u=Zt(i.source);if(!u)continue;if(!n.has(e)){const t=[];for(let n=0;n<u.layers.length;n++){const i=1073741824+256*e+n,o=u.layers[n];ns.initLayer(i,o.width,o.height,u.tileWidth,u.tileHeight),o.tiles.length>0&&ns.setTiles(i,o.tiles),t.push(i),s.add(i)}n.set(e,t)}const d=n.get(e);for(let e=0;e<u.layers.length&&e<d.length;e++){const t=d[e],s=u.tilesets[0];if(!s)continue;const n=Kt(s.textureHandle);if(!n)continue;const i=u.tileWidth/n.width,h=u.tileHeight/n.height;ns.submitLayer(t,s.textureHandle,e,0,s.columns,i,h,c.worldPosition.x,c.worldPosition.y,o,r,a,l,1,1,1,1,1,1,1)}}})}cleanup(){for(const e of this.initializedLayers_)ns.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),Jt(),ss()}}const Za=new Qa;function el(e,t){return e.toFixed(t)}function tl(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}class sl{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">${el(e.fps,1)}</span> Frame: <span style="color:#d19a66">${el(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>${tl(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${el(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 nl(){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 il=Re(nl(),"Stats");const ol="StatsCollect";class rl{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 al{constructor(e){this.name="Stats",this.collector_=new rl,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(il,nl());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new sl(e,this.options_.position)}const t=this.collector_,s=this.overlay_,n=ht([Ie(Le),{_type:"get_world"}],(n,i)=>{t.pushFrame(n.delta);const o=e.getResource(il);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(ol),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=jn.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:ol});e.addSystemToSchedule(exports.Schedule.Last,n)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const ll=new al;class cl{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 ul(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 dl=[Gi,ro,mo,Do,No,So,qo,er,rr,$o,Ao,lr,hr,gr,xr,Mr,Cr],hl=[...dl,La,Va,Ka,Za,Wn];function pl(e,t){return function(e,t){const s=ii.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),js(e),Tt(e),ln(e),wn(e),Hn(e),Xn(e);const i=new qn;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=ui(e,n,t,i));const r=s.getResource(xt);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(xt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=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;jn.setClearColor(e.x,e.y,e.z,e.w)}const d=(c()-o)/1e3;let h;if(jn.resize(t,l),s.hasResource(ei)){const e=s.getResource(ei).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const p=ui(e,n,t,l,s.world,h);if(a(t,l,p),0===p.length)i.render({registry:{_cpp:n},viewProjection:ri,width:t,height:l,elapsed:d});else{i.beginScreenCapture();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,cameraEntity:e.entity})}i.endScreenCapture(),jn.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(exports.Schedule.First,l),s.addSystemToSchedule(exports.Schedule.Last,d),s.addPlugin(As),s.addPlugin(Ws),s.addPlugin(_t),s.addPlugin(ni),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:hl,...t})}class fl{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 ml(e){return(t,s)=>(a(e,t).then(e=>{s(e.instance,e.module)}),{})}async function gl(e,t){try{return await e({instantiateWasm:ml(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=Ba,exports.App=ii,exports.AssetPlugin=Es,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=Ts,exports.Assets=Cs,exports.AsyncCache=Wt,exports.Audio=Xt,exports.AudioBus=d,exports.AudioListener=Oa,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=Ha,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=$a,exports.BitmapText=me,exports.BodyType=Ee,exports.BoxCollider=Me,exports.Button=uo,exports.ButtonState=co,exports.Camera=ue,exports.Canvas=de,exports.CapsuleCollider=Ce,exports.Changed=function(e){return{_filterType:"changed",_component:e}},exports.Children=fe,exports.CircleCollider=Te,exports.ClearFlags=ie,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=it,exports.DEFAULT_DESIGN_HEIGHT=D,exports.DEFAULT_DESIGN_WIDTH=L,exports.DEFAULT_FALLBACK_DT=U,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=Go,exports.DragState=Yo,exports.Draggable=Xo,exports.Draw=Gs,exports.Dropdown=yr,exports.DropdownPlugin=_r,exports.EasingType=ha,exports.EmitterShape=ye,exports.EntityCommands=nt,exports.EventReader=function(e){return{_type:"event_reader",_event:e}},exports.EventReaderInstance=lt,exports.EventRegistry=rt,exports.EventWriter=function(e){return{_type:"event_writer",_event:e}},exports.EventWriterInstance=at,exports.FillDirection=xi,exports.FillMethod=Io,exports.FillOrigin=Fo,exports.FocusManager=Co,exports.FocusManagerState=To,exports.FocusPlugin=ar,exports.Focusable=Mo,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=Gn,exports.Geometry=dn,exports.GetWorld=ut,exports.INVALID_ENTITY=0,exports.INVALID_FONT=j,exports.INVALID_MATERIAL=0,exports.INVALID_TEXTURE=V,exports.Image=ko,exports.ImagePlugin=Lo,exports.ImageType=Ro,exports.Input=gt,exports.InputPlugin=yt,exports.InputState=mt,exports.Interactable=ao,exports.LayoutGroupPlugin=Pr,exports.ListView=pr,exports.ListViewPlugin=mr,exports.LocalTransform=ae,exports.Logger=ua,exports.LoopMode=fa,exports.Material=At,exports.MaterialLoader=zt,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=be,exports.Parent=pe,exports.Particle=Ga,exports.ParticleEasing=xe,exports.ParticleEmitter=we,exports.ParticlePlugin=qa,exports.Physics=Kr,exports.PhysicsEvents=jr,exports.PhysicsPlugin=Gr,exports.PostProcess=Sn,exports.PostProcessPlugin=Un,exports.PostProcessStack=yn,exports.PostProcessVolume=Se,exports.PrefabServer=Ls,exports.Prefabs=Ds,exports.PrefabsPlugin=Us,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(ei);t.register({name:ra,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(ra),this.loadPromise_=t.load(ra).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 oa(this.baseUrl_);await s.prefetch(t);let i=null;const o=this.app_.spineInitPromise;if(o){i=(await o).controller.raw}await sa({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:s,spineModule:i,sceneName:ra})}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(ei).getScene(ra),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(ei);await e.switchTo(ra),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=Ho,exports.ProgressBarDirection=Oo,exports.ProgressBarPlugin=jo,exports.ProjectionType=ne,exports.Query=et,exports.QueryInstance=tt,exports.Removed=function(e){return{_type:"removed",_component:e}},exports.RemovedQueryInstance=st,exports.RenderPipeline=qn,exports.RenderTexture=aa,exports.Renderer=jn,exports.Res=Ie,exports.ResMut=Fe,exports.RigidBody=Pe,exports.RuntimeConfig=$,exports.SafeArea=cr,exports.SafeAreaPlugin=dr,exports.ScaleMode=oe,exports.SceneManager=ei,exports.SceneManagerState=Zn,exports.SceneOwner=ve,exports.ScrollView=Ko,exports.ScrollViewPlugin=Zo,exports.ShaderSources=Ut,exports.SimulationSpace=_e,exports.Slider=sr,exports.SliderDirection=tr,exports.SliderPlugin=or,exports.SpineAnimation=ge,exports.Sprite=ce,exports.SpriteAnimator=jt,exports.Stats=il,exports.StatsCollector=rl,exports.StatsOverlay=sl,exports.StatsPlugin=al,exports.SystemRunner=ft,exports.Text=ji,exports.TextAlign=Oi,exports.TextInput=Po,exports.TextInputPlugin=Eo,exports.TextOverflow=Vi,exports.TextPlugin=Yi,exports.TextRenderer=Ni,exports.TextVerticalAlign=Hi,exports.Tilemap=is,exports.TilemapAPI=ns,exports.TilemapLayer=os,exports.TilemapPlugin=Qa,exports.Time=Le,exports.Toggle=Uo,exports.TogglePlugin=zo,exports.Transform=re,exports.Tween=ka,exports.TweenHandle=Ta,exports.TweenState=pa,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=xt,exports.UIEventQueue=ho,exports.UIEvents=po,exports.UIInteraction=lo,exports.UIInteractionPlugin=vo,exports.UILayoutPlugin=fo,exports.UIMask=Ji,exports.UIMaskPlugin=oo,exports.UIRect=bi,exports.UIRenderOrderPlugin=Tr,exports.Velocity=he,exports.WeChatAssetProvider=fl,exports.WebAssetProvider=oa,exports.World=Ge,exports.WorldTransform=le,exports.addStartupSystem=function(e){pt().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){pt().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){pt().push({schedule:e,system:t})},exports.animationPlugin=La,exports.applyBuildRuntimeConfig=H,exports.applyDirectionalFill=Ti,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=As,exports.audioPlugin=Va,exports.calculateAttenuation=Wa,exports.calculatePanning=za,exports.cleanupAllPostProcessVolumes=Rn,exports.cleanupPostProcessVolume=An,exports.clearAnimClips=function(){Ht.clear()},exports.clearDrawCallbacks=tn,exports.clearTextureDimensionsCache=Jt,exports.clearTilemapSourceCache=function(){Gt.clear()},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=Mi,exports.computeFillSize=function(e,t,s,n){switch(e){case xi.BottomToTop:case xi.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}},exports.computeHandleAnchors=function(e,t){switch(e){case xi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case xi.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case xi.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=wi,exports.createMaskProcessor=io,exports.createRuntimeSceneConfig=na,exports.createWebApp=pl,exports.debug=function(e,t,s){da.debug(e,t,s)},exports.defaultFrameStats=nl,exports.defineComponent=q,exports.defineEvent=function(e){return{_id:Symbol(`Event_${e}`),_name:e}},exports.defineResource=Re,exports.defineSystem=ht,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=qo,exports.dropdownPlugin=xr,exports.error=function(e,t,s){da.error(e,t,s)},exports.extractAnimClipTexturePaths=$t,exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([be]);for(const n of s){const s=e.get(n,be);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=oi,exports.focusPlugin=lr,exports.getAddressableType=function(e){return b(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.getAllEffectDefs=function(){return Array.from(Pn.values())},exports.getAnimClip=function(e){return Ht.get(e)},exports.getAssetBuildTransform=function(e){return b(e)?.buildTransform},exports.getAssetMimeType=function(e){return y[e.toLowerCase()]},exports.getAssetTypeEntry=b,exports.getComponent=te,exports.getComponentAssetFieldDescriptors=ms,exports.getComponentAssetFields=fs,exports.getComponentDefaults=function(e){const t=te(e);return t?N(t._default):null},exports.getComponentEntityFields=_s,exports.getComponentSpineFieldDescriptor=gs,exports.getCustomExtensions=S,exports.getEditorType=function(e){return b(e)?.editorType??"unknown"},exports.getEffectDef=Tn,exports.getEffectTypes=function(){return Array.from(Pn.keys())},exports.getLogger=function(){return da},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getTextureDimensions=Kt,exports.getTilemapSource=Zt,exports.getUserComponent=K,exports.getWeChatPackOptions=function(){return S().map(e=>({type:"suffix",value:e}))},exports.imagePlugin=Do,exports.info=function(e,t,s){da.info(e,t,s)},exports.initDrawAPI=js,exports.initGLDebugAPI=Xn,exports.initGeometryAPI=ln,exports.initMaterialAPI=Tt,exports.initParticleAPI=Xa,exports.initPlayableRuntime=async function(e){const{app:t,module:s,assets:n,scenes:i,firstScene:o}=e,r=t.getResource(Cs);r&&(r.registerEmbeddedAssets(n),r.setEmbeddedOnly(!0));const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await ul(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 ul(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new cl(n);await ia({app:t,module:s,provider:c,scenes:i,firstScene:o,spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()},exports.initPostProcessAPI=wn,exports.initRendererAPI=Hn,exports.initRuntime=ia,exports.initTilemapAPI=ts,exports.initTweenAPI=Aa,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:ml("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=pl(a,{glContextHandle:c,getViewportSize:()=>({width:i.width,height:i.height})});e.runtimeConfig&&H(u,e.runtimeConfig);let d=null;e.spineFactory&&(d=await gl(e.spineFactory,"spine.wasm"));let h=null;e.physicsFactory&&(h=await gl(e.physicsFactory,"physics.wasm"));const p=new fl(n),f=[];for(const t of e.sceneNames){const e=await o(`scenes/${t}.json`);f.push({name:t,data:JSON.parse(e)})}await ia({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=_t,exports.instantiatePrefab=Rs,exports.intersectRects=Qi,exports.invertMatrix4=Zi,exports.isBuiltinComponent=Q,exports.isCustomExtension=P,exports.isEditor=_o,exports.isKnownAssetExtension=v,exports.isPlatformInitialized=function(){return null!==e},exports.isPlayMode=xo,exports.isRuntime=function(){return!go},exports.isTextureRef=bt,exports.isWeChat=s,exports.isWeb=function(){return"web"===e?.name},exports.layoutGroupPlugin=Mr,exports.listViewPlugin=gr,exports.loadComponent=Ps,exports.loadPhysicsModule=Er,exports.loadRuntimeScene=sa,exports.loadSceneData=bs,exports.loadSceneWithAssets=vs,exports.loadTiledMap=function(e,t,s,n={}){const i=[],o=t.tilesets[0];let r=0;for(const n of t.layers){if(!n.visible)continue;const a=e.spawn();e.insert(a,re,{});const l=o?s.get(o.image)??0:0,c=o?.columns??1;e.insert(a,os,{width:n.width,height:n.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:r,tiles:Array.from(n.tiles),tint:{...n.tintColor},opacity:n.opacity,visible:n.visible,parallaxFactor:{x:n.parallaxX,y:n.parallaxY}}),i.push(a),r++}if(!1!==n.generateObjectCollision&&t.objectGroups.length>0){const s=function(e,t,s,n){const i=[],o=t.height*t.tileHeight;for(const r of t.objectGroups)for(const t of r.objects){if("point"===t.shape)continue;const r=e.spawn(),a=t.x,l=t.y,c=s+a+.5*t.width,u=n+(o-l)-.5*t.height,d=-t.rotation*ds;if(e.insert(r,re,{position:{x:c,y:u,z:0}}),e.insert(r,Pe,{bodyType:Ee.Static}),"ellipse"===t.shape){const s=.5*Math.max(t.width,t.height);e.insert(r,Te,{radius:s})}else if("polygon"===t.shape&&t.vertices){let s=1/0,n=1/0,i=-1/0,o=-1/0;for(let e=0;e<t.vertices.length;e+=2){const r=t.vertices[e],a=t.vertices[e+1];r<s&&(s=r),r>i&&(i=r),a<n&&(n=a),a>o&&(o=a)}const a=i-s,l=o-n,c=.5*(s+i),u=.5*(n+o);e.insert(r,Me,{halfExtents:{x:.5*a,y:.5*l},offset:{x:c,y:-u}})}else e.insert(r,Me,{halfExtents:{x:.5*t.width,y:.5*t.height}});if(0!==d){const t=.5*d;e.insert(r,re,{position:{x:c,y:u,z:0},rotation:{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}})}i.push(r)}return i}(e,t,0,0);i.push(...s)}const a=new Set(n.collisionTileIds??t.collisionTileIds);if(a.size>0)for(const s of t.layers){if(!s.visible)continue;const n=hs(e,s,t,a,0,0);i.push(...n)}return i},exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&v(w(e)))},exports.parseAnimClipData=Ot,exports.parseTiledMap=async function(e,t){const s=es;if(!s)return null;const n=new TextEncoder,i=n.encode(e),o=s._malloc(i.byteLength);s.HEAPU8.set(i,o);const r=s.tiled_loadMap(o,i.byteLength);if(s._free(o),0===r)return null;try{const e=s.tiled_getExternalTilesetCount(r);for(let i=0;i<e;i++){const e=s.tiled_getExternalTilesetSource(r,i);if(!t)return s.tiled_freeMap(r),null;const o=await t(e),a=n.encode(o),l=s._malloc(a.byteLength);s.HEAPU8.set(a,l);const c=s.tiled_loadExternalTileset(r,i,l,a.byteLength);if(s._free(l),!c)return s.tiled_freeMap(r),null}if(!s.tiled_finalize(r))return s.tiled_freeMap(r),null;const i={width:s.tiled_getMapWidth(r),height:s.tiled_getMapHeight(r),tileWidth:s.tiled_getMapTileWidth(r),tileHeight:s.tiled_getMapTileHeight(r),layers:[],tilesets:[],objectGroups:[],collisionTileIds:[]},o=s.tiled_getLayerCount(r);for(let e=0;e<o;e++){const t=s.tiled_getLayerWidth(r,e),n=s.tiled_getLayerHeight(r,e),o=t*n,a=2*o,l=s._malloc(a);s.tiled_getLayerTiles(r,e,l,o);const c=new Uint16Array(o);c.set(new Uint16Array(s.HEAPU8.buffer,l,o)),s._free(l),i.layers.push({name:s.tiled_getLayerName(r,e),width:t,height:n,visible:s.tiled_getLayerVisible(r,e),tiles:c,opacity:s.tiled_getLayerOpacity(r,e),tintColor:s.tiled_getLayerTintColor?rs(s.tiled_getLayerTintColor(r,e)):{r:1,g:1,b:1,a:1},parallaxX:s.tiled_getLayerParallaxX(r,e),parallaxY:s.tiled_getLayerParallaxY(r,e)})}const a=s.tiled_getTilesetCount(r);for(let e=0;e<a;e++)i.tilesets.push({name:s.tiled_getTilesetName(r,e),image:s.tiled_getTilesetImage(r,e),tileWidth:s.tiled_getTilesetTileWidth(r,e),tileHeight:s.tiled_getTilesetTileHeight(r,e),columns:s.tiled_getTilesetColumns(r,e),tileCount:s.tiled_getTilesetTileCount(r,e)});return s.tiled_freeMap(r),i}catch{return s.tiled_freeMap(r),null}},exports.parseTmjJson=cs,exports.particlePlugin=Ka,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=to(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.postProcessPlugin=Wn,exports.prefabsPlugin=Ws,exports.progressBarPlugin=No,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerAnimClip=Vt,exports.registerAssetBuildTransform=function(e,t){for(const s of g)s.editorType===e&&(s.buildTransform=t)},exports.registerComponent=ee,exports.registerComponentAssetFields=function(e,t){ps.set(e,t)},exports.registerComponentEntityFields=function(e,t){ys.set(e,t)},exports.registerDrawCallback=Zs,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(Cs);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=Dt,exports.registerTextureDimensions=qt,exports.registerTilemapSource=Qt,exports.remapEntityFields=xs,exports.resolveRelativePath=us,exports.safeAreaPlugin=hr,exports.sceneManagerPlugin=ni,exports.screenToWorld=eo,exports.scrollViewPlugin=er,exports.setEditorMode=function(e){go=e},exports.setListViewRenderer=function(e,t){if(!fr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=fr.get(e);s?s.renderer=t:fr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})},exports.setLogLevel=function(e){da.setMinLevel(e)},exports.setPlayMode=function(e){yo=e},exports.setWasmErrorHandler=$e,exports.shutdownDrawAPI=Ns,exports.shutdownGLDebugAPI=Yn,exports.shutdownGeometryAPI=cn,exports.shutdownMaterialAPI=Ct,exports.shutdownParticleAPI=Ya,exports.shutdownPostProcessAPI=bn,exports.shutdownRendererAPI=Vn,exports.shutdownTilemapAPI=ss,exports.shutdownTweenAPI=Ra,exports.sliderPlugin=rr,exports.spriteAnimatorSystemUpdate=Nt,exports.statsPlugin=ll,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 xi.BottomToTop:case xi.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.syncPostProcessVolume=function(e,t){let s=Cn.get(e),n=En.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(s||(s=Sn.createStack(),Cn.set(e,s)),n||(n=new Map,En.set(e,n));s.passCount>0;){const e=s.passes;s.removePass(e[e.length-1].name)}for(const e of i){const t=Tn(e.type);if(!t)continue;let i=n.get(e.type);void 0===i&&(i=t.factory(),n.set(e.type,i)),s.addPass(e.type,i);for(const n of t.uniforms){const t=e.uniforms[n.name]??n.defaultValue;s.setUniform(e.type,n.name,t)}}Sn.bind(e,s)}else if(s&&(Sn.unbind(e),s.destroy(),Cn.delete(e)),n){for(const e of n.values())At.releaseShader(e);En.delete(e)}},exports.textInputPlugin=Ao,exports.textPlugin=Gi,exports.tilemapPlugin=Za,exports.toBuildPath=M,exports.togglePlugin=$o,exports.transitionTo=async function(e,t,s){const n=e.getResource(ei);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=So,exports.uiLayoutPlugin=mo,exports.uiMaskPlugin=ro,exports.uiPlugins=dl,exports.uiRenderOrderPlugin=Cr,exports.unregisterAnimClip=function(e){Ht.delete(e)},exports.unregisterComponent=function(e){G().delete(e),Z.delete(e)},exports.unregisterDrawCallback=en,exports.updateCameraAspectRatio=Ms,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){da.warn(e,t,s)},exports.wrapSceneSystem=ti,exports.wxFileExists=function(e){return new Promise(t=>{C().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)=>{C().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(E(e,t.errMsg)))}})})},exports.wxReadTextFile=function(e,t="utf-8"){return new Promise((s,n)=>{C().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(E(e,t.errMsg)))}})})},exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{C().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};
//# sourceMappingURL=index.wechat.cjs.js.map
diff --git a/desktop/public/sdk/cjs/index.wechat.js b/desktop/public/sdk/cjs/index.wechat.js
index 427374222..77cd2f400 100644
--- a/desktop/public/sdk/cjs/index.wechat.js
+++ b/desktop/public/sdk/cjs/index.wechat.js
@@ -1,2 +1,2 @@
-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function 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 d(e,n){return t().createCanvas(e,n)}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),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 y{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 _{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}}async loadBufferFromData(e,t){return this.loadBuffer(e)}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 y(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},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",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 W(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 $(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(W(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 V(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 X(e){return new Promise(t=>{L().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function N(e){const t=L();try{return t.accessSync(e),!0}catch{return!1}}function Y(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 N(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 _}},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,de="default",he={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=he.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=he.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=he.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=he.canvasMatchWidthOrHeight)}const pe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function me(e,t){if(void 0!==t.maxDeltaTime&&(he.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(he.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(he.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(he.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(he.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");he.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&&(he.canvasScaleMode=pe[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(he.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight)}const ge=0,ye=4294967295,_e=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=We.get(e)??Ce().get(e);if(n)return n;const s=Ee(e,t);return Ce().set(e,s),We.set(e,s),Be(e,t,!1),s}function Re(e){const t=We.get(e)??Ce().get(e);if(t)return t;const n=Ee(e,{});return Ce().set(e,n),We.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())We.delete(t);e.clear()}function Fe(e){Ce().delete(e),We.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 We=new Map;function Ue(e,t){We.set(e,t)}function $e(e){return We.get(e)??Ie(e)}function De(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return We.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}}),Ve=je,Xe=je,Ne=De("Sprite",{texture:ye,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=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:_e,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={Point:0,Circle:1,Rectangle:2,Cone:3},tt={World:0,Local:1},nt={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},st=De("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:et.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:nt.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:nt.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:ye,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:tt.World,enabled:!0}),it=Ae("Name",{value:""}),ot=Ae("SceneOwner",{scene:"",persistent:!1}),rt=Ae("PostProcessVolume",{effects:[]});function at(e){const t=$e(e);return t?Pe(t._default):null}const lt=De("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ct=De("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ut=De("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),dt=De("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ht={Static:0,Kinematic:1,Dynamic:2};let ft=0;function pt(e,t){const n=++ft;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function mt(e){return{_type:"res",_resource:e}}function gt(e){return{_type:"res_mut",_resource:e}}class yt{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 _t{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 yt(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const wt=pt({delta:0,elapsed:0,frameCount:0},"Time");function xt(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=vt(t[e]),o=vt(i);"null"!==n&&"undefined"!==n&&(n!==o&&null!=i&&s.push({field:e,expected:n,actual:o,value:i}))}return s}function vt(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function bt(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 St=null;function Mt(e){St=e}function Pt(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),St&&St(e,t)}function Tt(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 Et=1;const Ct=new WeakMap;function At(e){let t=Ct.get(e);return void 0===t&&(t=Et++,Ct.set(e,t)),t}const Rt=[];function It(e,t=[],n=[]){Rt.length=0;for(const t of e)Rt.push(At(t));Rt.sort((e,t)=>e-t);let s=Rt.join(",");if(t.length>0){Rt.length=0;for(const e of t)Rt.push(At(e));Rt.sort((e,t)=>e-t),s+="|+"+Rt.join(",")}if(n.length>0){Rt.length=0;for(const e of n)Rt.push(At(e));Rt.sort((e,t)=>e-t),s+="|-"+Rt.join(",")}return s}class kt{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 Pt(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){Pt(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){Pt(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Pt(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{const s=t._default,i=n;let o=i;for(const e of Object.keys(i))e in s||(o===i&&(o={...i}),delete o[e]);this.getBuiltinMethods(t._cppName).add(e,Tt(o))}catch(n){Pt(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 Pt(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=t._default,i={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&e in s&&(i[e]=t);const e=xt(t._name,s,i);if(e.length>0)throw new Error(bt(t._name,e))}const o={...t._default,...i};let r=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);r=!n.has(e),n.add(e,Tt(o))}catch(n){Pt(n,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),o}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 Pt(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 Pt(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){Pt(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=xt(t._name,t._default,e);if(i.length>0)throw new Error(bt(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 We)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??It(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 Ft(e){return{_type:"mut",_component:e}}function Bt(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function zt(e){return{_filterType:"added",_component:e}}function Wt(e){return{_filterType:"changed",_component:e}}function Ut(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function $t(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Dt(e){return Bt(e)||Ut(e)||$t(e)?e._component:e}function Ot(e,t=[],n=[]){const s=[],i=[],o=[];return e.forEach((e,t)=>{Bt(e)&&s.push(t),Ut(e)?i.push({index:t,component:e._component}):$t(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:o,with:(...s)=>Ot(e,[...t,...s],n),without:(...s)=>Ot(e,t,[...n,...s])}}function Lt(...e){return Ot(e)}class Ht{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(Dt),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_=It(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 jt(e){return{_type:"removed",_component:e}}class Vt{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 Xt(){return{_type:"commands"}}class Nt{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 Yt{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Nt(this,null);return this.spawned_.push(e),e}entity(e){return new Nt(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 qt(e){return{_id:Symbol(`Event_${e}`),_name:e}}class Gt{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 Kt{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Gt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Gt,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function Jt(e){return{_type:"event_writer",_event:e}}function Qt(e){return{_type:"event_reader",_event:e}}class Zt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class en{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var tn;function nn(){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"}(tn||(tn={}));let sn=0;function on(e,t,n){const s=++sn;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function rn(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function an(e){rn().push({schedule:tn.Update,system:e})}function ln(e){rn().push({schedule:tn.Startup,system:e})}function cn(e,t){rn().push({schedule:e,system:t})}class un{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 Yt&&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 Ht(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 Yt(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 Zt(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new en(n)}case"removed":{const t=e;return new Vt(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class dn{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 hn=pt(new dn,"Input");class fn{constructor(e){this.target_=e??null}build(e){const n=new dn;e.insertResource(hn,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(tn.Last,on([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const pn=new fn,mn=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},"UICameraInfo");var gn;function yn(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"}(gn||(gn={}));let _n=null,wn=null,xn=1;const vn=new Map;function bn(e){_n=e,wn=e.getResourceManager(),kn()}function Sn(){0!==En&&_n&&(_n._free(En),En=0),vn.clear(),xn=1,Tn=!1,An.clear(),Rn=null,wn=null,_n=null}function Mn(){if(!wn)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return wn}const Pn={createShader:(e,t)=>Mn().createShader(e,t),releaseShader(e){e>0&&Mn().releaseShader(e)},create(e){const t=xn++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??gn.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 vn.set(t,n),t},get:e=>vn.get(e),setUniform(e,t,n){const s=vn.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,_n?.invalidateMaterialCache(e))},getUniform(e,t){const n=vn.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=vn.get(e);n&&(n.blendMode=t,_n?.invalidateMaterialCache(e))},getBlendMode(e){const t=vn.get(e);return t?.blendMode??gn.Normal},setDepthTest(e,t){const n=vn.get(e);n&&(n.depthTest=t,_n?.invalidateMaterialCache(e))},getShader(e){const t=vn.get(e);return t?.shader??0},release(e){vn.delete(e),_n?.invalidateMaterialCache(e)},isValid:e=>vn.has(e),releaseAll(){vn.clear(),_n?.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??gn.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=vn.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=xn++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return vn.set(n,s),n},toAssetData(e,t){const n=vn.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=vn.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Tn=!1,En=0;const Cn=16384,An=new Map;let Rn=null;function In(e){const t=(0===En&&_n&&(En=_n._malloc(Cn)),En);if(0===t||!_n)return{ptr:0,count:0};let n=0,s=0;const i=_n.HEAPU8,o=_n.HEAPU32,r=_n.HEAPF32;for(const[a,l]of e){if(yn(l))continue;let e=An.get(a);e||(Rn||(Rn=new TextEncoder),e=Rn.encode(a),An.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(n+(4+u+4+16)>Cn){console.warn(`[ESEngine] Material uniform buffer full (${n}/${Cn} bytes), skipping remaining uniforms`);break}o[t+n>>2]=c,n+=4,i.set(e,t+n),n+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)r[t+n>>2]=h[e],n+=4;s++}return{ptr:t,count:s}}function kn(){if(!_n||Tn)return;_n.materialDataProvider=(e,t,n,s,i)=>{const o=vn.get(e);if(!o)return _n.HEAPU32[t>>2]=0,_n.HEAPU32[n>>2]=0,_n.HEAPU32[s>>2]=0,void(_n.HEAPU32[i>>2]=0);_n.HEAPU32[t>>2]=o.shader,_n.HEAPU32[n>>2]=o.blendMode;const{ptr:r,count:a}=In(o.uniforms);_n.HEAPU32[s>>2]=r,_n.HEAPU32[i>>2]=a},Tn=!0}const Fn={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 Bn{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 zn{constructor(e,t=""){this.cache_=new Bn,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&&(Pn.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Pn.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:Pn.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 Wn(e){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function Un(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 $n=new Map;function Dn(e){$n.set(e.name,e)}function On(e){$n.delete(e)}function Ln(e){return $n.get(e)}function Hn(){$n.clear()}const jn=Ae("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function Vn(e,t){const n=e.getEntitiesWithComponents([jn]);for(const s of n){const n=e.get(s,jn);if(!n.enabled||!n.playing||!n.clip)continue;const i=$n.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,Ne)){const t=i.frames[n.currentFrame],o=e.get(s,Ne);o.texture=t.texture,t.uvOffset&&(o.uvOffset=t.uvOffset,o.uvScale=t.uvScale),e.insert(s,Ne,o)}a&&e.insert(s,jn,n)}}class Xn{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 async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const n=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,n)}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}}}}Xn.mixer_=null,Xn.bufferCache_=new Map,Xn.bgmHandle_=null,Xn.bgmVolume_=1,Xn.fadeAnimId_=0,Xn.disposed_=!1;const Nn=new Map,Yn=new Map;function qn(e,t,n){Nn.set(e,{width:t,height:n})}function Gn(e){return Nn.get(e)}function Kn(){Nn.clear()}function Jn(e,t){Yn.set(e,t)}function Qn(e){return Yn.get(e)}function Zn(){Yn.clear()}let es=null;function ts(e){es=e}function ns(){es=null}const ss={initLayer(e,t,n,s,i){es?.tilemap_initLayer(e,t,n,s,i)},destroyLayer(e){es?.tilemap_destroyLayer(e)},setTile(e,t,n,s){es?.tilemap_setTile(e,t,n,s)},getTile:(e,t,n)=>es?es.tilemap_getTile(e,t,n):0,fillRect(e,t,n,s,i,o){es?.tilemap_fillRect(e,t,n,s,i,o)},setTiles(e,t){if(!es)return;const n=t.byteLength,s=es._malloc(n);new Uint16Array(es.HEAPU8.buffer,s,t.length).set(t),es.tilemap_setTiles(e,s,t.length),es._free(s)},hasLayer:e=>!!es&&es.tilemap_hasLayer(e),submitLayer(e,t,n,s,i,o,r,a,l,c,u,d,h){es?.tilemap_submitLayer(e,t,n,s,i,o,r,a,l,c,u,d,h)}},is=Ae("Tilemap",{source:""}),os=Ae("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[]});function rs(e,t){if(0===e)return 0;let n=0;2147483648&e&&(n|=8192),1073741824&e&&(n|=16384),536870912&e&&(n|=32768);return(536870911&e)-t+1|n}function as(e){const t=e.width,n=e.height,s=e.tilewidth??0,i=e.tileheight??0;if(!(t&&n&&s&&i))return null;const o=e.tilesets,r=[],a=[];if(o)for(const e of o){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??s,tileHeight:e.tileheight??i,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const s=e.width??t,i=e.height??n,o=!1!==e.visible,r=e.data,l=new Uint16Array(s*i);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=rs(r[t],e)}c.push({name:e.name??"",width:s,height:i,visible:o,tiles:l})}return{width:t,height:n,tileWidth:s,tileHeight:i,layers:c,tilesets:r}}function ls(e,t){const n=e.lastIndexOf("/"),s=((n>=0?e.substring(0,n+1):"")+t).split("/"),i=[];for(const e of s)".."===e?i.pop():"."!==e&&""!==e&&i.push(e);return i.join("/")}async function cs(e,t){const n=es;if(!n)return null;const s=new TextEncoder,i=s.encode(e),o=n._malloc(i.byteLength);n.HEAPU8.set(i,o);const r=n.tiled_loadMap(o,i.byteLength);if(n._free(o),0===r)return null;try{const e=n.tiled_getExternalTilesetCount(r);for(let i=0;i<e;i++){const e=n.tiled_getExternalTilesetSource(r,i);if(!t)return n.tiled_freeMap(r),null;const o=await t(e),a=s.encode(o),l=n._malloc(a.byteLength);n.HEAPU8.set(a,l);const c=n.tiled_loadExternalTileset(r,i,l,a.byteLength);if(n._free(l),!c)return n.tiled_freeMap(r),null}if(!n.tiled_finalize(r))return n.tiled_freeMap(r),null;const i={width:n.tiled_getMapWidth(r),height:n.tiled_getMapHeight(r),tileWidth:n.tiled_getMapTileWidth(r),tileHeight:n.tiled_getMapTileHeight(r),layers:[],tilesets:[]},o=n.tiled_getLayerCount(r);for(let e=0;e<o;e++){const t=n.tiled_getLayerWidth(r,e),s=n.tiled_getLayerHeight(r,e),o=t*s,a=2*o,l=n._malloc(a);n.tiled_getLayerTiles(r,e,l,o);const c=new Uint16Array(o);c.set(new Uint16Array(n.HEAPU8.buffer,l,o)),n._free(l),i.layers.push({name:n.tiled_getLayerName(r,e),width:t,height:s,visible:n.tiled_getLayerVisible(r,e),tiles:c})}const a=n.tiled_getTilesetCount(r);for(let e=0;e<a;e++)i.tilesets.push({name:n.tiled_getTilesetName(r,e),image:n.tiled_getTilesetImage(r,e),tileWidth:n.tiled_getTilesetTileWidth(r,e),tileHeight:n.tiled_getTilesetTileHeight(r,e),columns:n.tiled_getTilesetColumns(r,e),tileCount:n.tiled_getTilesetTileCount(r,e)});return n.tiled_freeMap(r),i}catch{return n.tiled_freeMap(r),null}}function us(e,t,n){const s=[],i=t.tilesets[0];let o=0;for(const r of t.layers){if(!r.visible)continue;const a=e.spawn();e.insert(a,je,{});const l=i?n.get(i.image)??0:0,c=i?.columns??1;e.insert(a,os,{width:r.width,height:r.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:o,tiles:Array.from(r.tiles)}),s.push(a),o++}return s}const ds=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"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}]]);function hs(e,t){ds.set(e,t)}function fs(e){const t=ds.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 ps(e){return ds.get(e)?.fields??[]}function ms(e){return ds.get(e)?.spine??null}const gs=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function ys(e,t){gs.set(e,t)}function _s(e){return gs.get(e)}function ws(e,t){const n=gs.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 xs(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,it,{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)ws(i,n),Ms(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 vs(e,t){return xs(e,t)}async function bs(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 Ss.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=ds.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=[...Ss.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=ds.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=xs(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 Ss=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),qn(r.handle,r.width,r.height)}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=Wn(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);Dn(Un(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 Xn.preloadAll(s).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=as(await t.loadJson(e));if(!i)return void console.warn(`Failed to parse tilemap: ${e}`);const o=[];for(const r of i.tilesets){const i=ls(e,r.image);let a=0;try{const e=n?`${n}/${i}`:`/${i}`,o=await t.loadTexture(e);a=o.handle,s.set(i,e),qn(o.handle,o.width,o.height)}catch(e){console.warn(`Failed to load tileset texture: ${i}`,e)}o.push({textureHandle:a,columns:r.columns})}Jn(e,{tileWidth:i.tileWidth,tileHeight:i.tileHeight,layers:i.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(i),new Map}}]]);function Ms(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=$e(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 Ps(e,t){const n=e.getEntitiesWithComponents([Ye]);for(const s of n){const n=e.get(s,Ye);n&&(n.aspectRatio=t,e.insert(s,Ye,n))}}function Ts(e,t){const n=e.getEntitiesWithComponents([it]);for(const s of n){const n=e.get(s,it);if(n&&n.value===t)return s}return null}class Es{constructor(e){this.textureCache_=new Bn,this.shaderCache_=new Bn,this.jsonCache_=new Bn,this.textCache_=new Bn,this.binaryCache_=new Bn,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Bn,this.prefabCache_=new Bn,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(he.textCanvasSize,he.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 zn(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(),Pn.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,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),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 fs(e.type)){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}const n=ms(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 bs(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 Pn.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 Pn.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 Cs=pt(null,"Assets");class As{build(e){const t=e.wasmModule;t?e.insertResource(Cs,new Es(t)):console.warn("AssetPlugin: No WASM module available")}}const Rs=new As;class Is{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 ks(e,t){const n=e.getResource(Cs);n&&n.registerEmbeddedAssets(t)}async function Fs(e,t,n){const{entities:s,rootId:i}=await zs(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 bs(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 Bs=10;async function zs(e,t,n,s,i,o=0){if(o>Bs)throw new Error(`Prefab nesting depth exceeded ${Bs}. 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 zs(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,d={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};Ws(d.components,r),Us(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 Ws(e,t){for(const n of e){const e=_s(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 Us(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 $s{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 Fs(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Ds=pt(null,"Prefabs");class Os{constructor(){this.name="PrefabsPlugin",this.dependencies=[Cs]}build(e){const t=e.getResource(Cs);e.insertResource(Ds,new $s(e.world,t))}}const Ls=new Os;let Hs=null,js=0,Vs=0,Xs=0;const Ns=new Float32Array(256);function Ys(e){Hs=e,js=Hs._malloc(64),Vs=Hs._malloc(64),Xs=Hs._malloc(1024)}function qs(){Hs&&(js&&(Hs._free(js),js=0),Vs&&(Hs._free(Vs),Vs=0),Xs&&(Hs._free(Xs),Xs=0)),Hs=null}function Gs(){if(!Hs)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Hs}const Ks={r:1,g:1,b:1,a:1},Js={begin(e){const t=Gs();try{t.HEAPF32.set(e,js/4),t.draw_begin(js)}catch(e){Pt(e,"Draw.begin")}},end(){try{Gs().draw_end()}catch(e){Pt(e,"Draw.end")}},line(e,t,n,s=1){try{Gs().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Pt(e,"Draw.line")}},rect(e,t,n,s=!0){try{Gs().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Pt(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{Gs().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Pt(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{Gs().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Pt(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{Gs().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Pt(e,"Draw.circleOutline")}},texture(e,t,n,s=Ks){try{Gs().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){Pt(e,"Draw.texture")}},textureRotated(e,t,n,s,i=Ks){try{Gs().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){Pt(e,"Draw.textureRotated")}},setLayer(e){Gs().draw_setLayer(e)},setDepth(e){Gs().draw_setDepth(e)},getDrawCallCount:()=>Hs?Hs.draw_getDrawCallCount():0,getPrimitiveCount:()=>Hs?Hs.draw_getPrimitiveCount():0,setBlendMode(e){Gs().draw_setBlendMode(e)},setDepthTest(e){Gs().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=Gs();s.HEAPF32.set(n,Vs/4),s.draw_mesh(e,t,Vs)}catch(n){Pt(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=Gs(),i=Pn.get(t);if(!i)return;if(Js.setBlendMode(i.blendMode),Js.setDepthTest(i.depthTest),0===i.uniforms.size)return void Js.drawMesh(e,i.shader,n);let o;if(s.HEAPF32.set(n,Vs/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,n]of i.uniforms){const s=ei(t);if(!(s<0)){if(yn(n))Ns[o++]=10,Ns[o++]=s,Ns[o++]=n.slot??e++,Ns[o++]=n.textureId;else if("number"==typeof n)Ns[o++]=1,Ns[o++]=s,Ns[o++]=n;else if(Array.isArray(n)){Ns[o++]=n.length,Ns[o++]=s;for(let e=0;e<n.length;e++)Ns[o++]=n[e]}else"w"in n?(Ns[o++]=4,Ns[o++]=s,Ns[o++]=n.x,Ns[o++]=n.y,Ns[o++]=n.z,Ns[o++]=n.w):"z"in n?(Ns[o++]=3,Ns[o++]=s,Ns[o++]=n.x,Ns[o++]=n.y,Ns[o++]=n.z):(Ns[o++]=2,Ns[o++]=s,Ns[o++]=n.x,Ns[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(Ns.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void s.draw_mesh(e,i.shader,Vs);s.HEAPF32.set(i.cachedBuffer_.subarray(0,o),Xs/4),s.draw_meshWithUniforms(e,i.shader,Vs,Xs,o)}catch(n){Pt(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Qs={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},Zs=new Set;function ei(e){const t=Qs[e];return void 0!==t?t:(Zs.has(e)||(Zs.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Qs).join(", ")}`)),-1)}const ti=new Map;function ni(e,t,n){ti.set(e,{fn:t,scene:n??""})}function si(e){ti.delete(e)}function ii(){ti.clear()}var oi;!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"}(oi||(oi={}));let ri=null,ai=0,li=0,ci=0;function ui(e){ri=e,ai=ri._malloc(262144),li=ri._malloc(65536),ci=ri._malloc(256)}function di(){ri&&(ai&&ri._free(ai),li&&ri._free(li),ci&&ri._free(ci),ai=0,li=0,ci=0),ri=null}function hi(){if(!ri)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ri}const fi={create(e){const t=hi(),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,ai/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,ci,i).set(o),t.geometry_init(n,ai,s,ci,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,li,s).set(e.indices),t.geometry_setIndices16(n,li,s)}else{new Uint32Array(t.HEAPU8.buffer,li,s).set(e.indices),t.geometry_setIndices32(n,li,s)}}return n},updateVertices(e,t,n=0){const s=hi(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,ai/4),s.geometry_updateVertices(e,ai,i,n)},release(e){e>0&&hi().geometry_release(e)},isValid:e=>!(!ri||e<=0)&&ri.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return fi.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:oi.Float2},{name:"a_texCoord",type:oi.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 fi.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:oi.Float2},{name:"a_texCoord",type:oi.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 fi.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:oi.Float2},{name:"a_texCoord",type:oi.Float2}],indices:new Uint16Array(r)})}};let pi=null,mi=1;const gi=new Map,yi=new Map;function _i(e){pi=e}function wi(){for(const e of gi.values())e.destroy();gi.clear(),yi.clear(),pi&&bi.isInitialized()&&bi.shutdown(),pi=null}class xi{constructor(){this.passes_=[],this.destroyed_=!1,this.id=mi++,gi.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}setEnabled(e,t){const n=this.passes_.find(t=>t.name===e);return n&&(n.enabled=t),this}setUniform(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.floatUniforms.set(t,n),this}setUniformVec4(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.vec4Uniforms.set(t,{...n}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of yi)t===this&&yi.delete(e);gi.delete(this.id)}}}function vi(){if(!pi)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return pi}const bi={createStack:()=>new xi,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");yi.set(e,t)},unbind(e){yi.delete(e)},getStack:e=>yi.get(e)??null,init(e,t){try{return vi().postprocess_init(e,t)}catch(n){return Pt(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{vi().postprocess_shutdown()}catch(e){Pt(e,"PostProcess.shutdown")}},resize(e,t){try{vi().postprocess_resize(e,t)}catch(n){Pt(n,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!pi)return!1;try{return pi.postprocess_isInitialized()}catch(e){return Pt(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{vi().postprocess_setBypass(e)}catch(e){Pt(e,"PostProcess.setBypass")}},setOutputViewport(e,t,n,s){try{vi().postprocess_setOutputViewport(e,t,n,s)}catch(e){Pt(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=yi.get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(bi.isInitialized()||bi.init(1,1),bi.setBypass(!1),function(e){const t=vi();try{t.postprocess_clearPasses()}catch(e){return void Pt(e,"PostProcess._applyForCamera:clearPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addPass(n.name,n.shader)}catch(e){Pt(e,`PostProcess._applyForCamera:addPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setUniformFloat(n.name,e,s)}catch(t){Pt(t,`PostProcess._applyForCamera:setUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){Pt(t,`PostProcess._applyForCamera:setUniformVec4("${n.name}", "${e}")`)}}}(t)):bi.setBypass(!0)},_resetAfterCamera(){try{vi().postprocess_clearPasses(),vi().postprocess_setBypass(!0)}catch(e){Pt(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of yi.keys())e(t)||yi.delete(t)},createBlur:()=>Pn.createShader(Si,"#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:()=>Pn.createShader(Si,"#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:()=>Pn.createShader(Si,"#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"),createBloom:()=>Pn.createShader(Si,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_threshold;\nuniform float u_intensity;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 texelSize = 1.0 / u_resolution;\n\n vec3 bloom = vec3(0.0);\n float total = 0.0;\n for (float x = -3.0; x <= 3.0; x += 1.0) {\n for (float y = -3.0; y <= 3.0; y += 1.0) {\n vec2 offset = vec2(x, y) * texelSize * u_radius;\n vec4 s = texture(u_texture, v_texCoord + offset);\n float brightness = dot(s.rgb, vec3(0.2126, 0.7152, 0.0722));\n float w = max(brightness - u_threshold, 0.0);\n bloom += s.rgb * w;\n total += w;\n }\n }\n if (total > 0.0) bloom /= total;\n\n fragColor = vec4(color.rgb + bloom * u_intensity, color.a);\n}\n"),createChromaticAberration:()=>Pn.createShader(Si,"#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")},Si="#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",Mi=new Map;function Pi(e){Mi.set(e.type,e)}function Ti(e){return Mi.get(e)}function Ei(){return Array.from(Mi.keys())}function Ci(){return Array.from(Mi.values())}Pi({type:"blur",label:"Blur",factory:()=>bi.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),Pi({type:"bloom",label:"Bloom",factory:()=>bi.createBloom(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:2,step:.01,defaultValue:.8},{name:"u_intensity",label:"Intensity",min:0,max:10,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:0,max:20,step:.1,defaultValue:4}]}),Pi({type:"vignette",label:"Vignette",factory:()=>bi.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:3,step:.01,defaultValue:.8},{name:"u_softness",label:"Softness",min:0,max:2,step:.01,defaultValue:.3}]}),Pi({type:"grayscale",label:"Grayscale",factory:()=>bi.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),Pi({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>bi.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const Ai=new Map,Ri=new Map;function Ii(e,t){let n=Ai.get(e),s=Ri.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(n||(n=bi.createStack(),Ai.set(e,n)),s||(s=new Map,Ri.set(e,s));n.passCount>0;){const e=n.passes;n.removePass(e[e.length-1].name)}for(const e of i){const t=Ti(e.type);if(!t)continue;let i=s.get(e.type);void 0===i&&(i=t.factory(),s.set(e.type,i)),n.addPass(e.type,i);for(const s of t.uniforms){const t=e.uniforms[s.name]??s.defaultValue;n.setUniform(e.type,s.name,t)}}bi.bind(e,n)}else if(n&&(bi.unbind(e),n.destroy(),Ai.delete(e)),s){for(const e of s.values())Pn.releaseShader(e);Ri.delete(e)}}function ki(e){const t=Ai.get(e);t&&(bi.unbind(e),t.destroy(),Ai.delete(e));const n=Ri.get(e);if(n){for(const e of n.values())Pn.releaseShader(e);Ri.delete(e)}}function Fi(){for(const e of Ai.keys())ki(e)}var Bi;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Bi||(Bi={}));let zi=null,Wi=0;function Ui(e){zi=e,Wi=zi._malloc(64)}function $i(){zi&&Wi&&(zi._free(Wi),Wi=0),zi=null}const Di={init(e,t){zi?.renderer_init(e,t)},resize(e,t){zi?.renderer_resize(e,t)},begin(e,t){if(zi&&Wi)try{zi.HEAPF32.set(e,Wi/4),zi.renderer_begin(Wi,t??0)}catch(e){Pt(e,"Renderer.begin")}},flush(){try{zi?.renderer_flush()}catch(e){Pt(e,"Renderer.flush")}},end(){try{zi?.renderer_end()}catch(e){Pt(e,"Renderer.end")}},submitSprites(e){if(zi)try{zi.renderer_submitSprites(e._cpp)}catch(e){Pt(e,"Renderer.submitSprites")}},submitBitmapText(e){if(zi)try{zi.renderer_submitBitmapText(e._cpp)}catch(e){Pt(e,"Renderer.submitBitmapText")}},submitSpine(e){if(zi)try{zi.renderer_submitSpine?.(e._cpp)}catch(e){Pt(e,"Renderer.submitSpine")}},submitParticles(e){if(zi)try{zi.renderer_submitParticles?.(e._cpp)}catch(e){Pt(e,"Renderer.submitParticles")}},setStage(e){zi?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>zi?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){zi?.renderer_releaseTarget(e)},getTargetTexture:e=>zi?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>zi?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){zi?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){zi?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){zi?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){zi?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>zi?zi.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>zi?{drawCalls:zi.renderer_getDrawCalls(),triangles:zi.renderer_getTriangles(),sprites:zi.renderer_getSprites(),text:zi.renderer_getText(),spine:zi.renderer_getSpine?.()??0,meshes:zi.renderer_getMeshes(),culled:zi.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Oi=null;function Li(e){Oi=e}function Hi(){Oi=null}const ji={enable(){Oi?.gl_enableErrorCheck(!0)},disable(){Oi?.gl_enableErrorCheck(!1)},check:e=>Oi?.gl_checkErrors(e)??0,diagnose(){Oi?.renderer_diagnose()}};class Vi{constructor(){this.spineRenderer_=null,this.tilemapRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}setTilemapRenderer(e){this.tilemapRenderer_=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_||(Di.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),Di.setViewport(0,0,s,i),Di.clearBuffers(3),Di.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),this.tilemapRenderer_&&this.tilemapRenderer_(),Di.submitSprites(t),Di.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Di.submitSpine(t),Di.submitParticles(t),Di.flush(),this.executeDrawCallbacks(n,o),Di.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==bi.getStack(r);a&&(bi._applyForCamera(r),bi.resize(s.w,s.h),bi.setOutputViewport(s.x,s.y,s.w,s.h)),Di.setViewport(s.x,s.y,s.w,s.h),Di.setScissor(s.x,s.y,s.w,s.h,!0),Di.clearBuffers(i),Di.setScissor(0,0,0,0,!1),Di.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),this.tilemapRenderer_&&this.tilemapRenderer_(),Di.submitSprites(t),Di.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Di.submitSpine(t),Di.submitParticles(t),Di.flush(),this.executeDrawCallbacks(n,o),Di.end(),a&&bi._resetAfterCamera()}executeDrawCallbacks(e,t){const n=ti;if(n.size>0){Js.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)}Js.end();for(const e of s)si(e)}}}const Xi="__scene_transition_overlay__";class Ni{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class Yi{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,ot,{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),ni(e,t,this.instance_.config.name)}bindPostProcess(e,t){bi.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){bi.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,ot)){const n=this.app_.world.get(e,ot);n.persistent=t,this.app_.world.insert(e,ot,n)}}}class qi{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}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())si(t);for(const t of e.postProcessBindings.keys())bi.unbind(t)}this.transition_&&(si(Xi),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}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??he.sceneTransitionDuration,i=t.color??{...he.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},ni(Xi,()=>{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;Js.setLayer(9999),Js.setDepth(9999),Js.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,si(Xi),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,si(Xi),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 Ni(t);this.scenes_.set(e,n);const s=new Yi(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Cs)?this.app_.getResource(Cs):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 Ni(t);this.scenes_.set(e,n);const s=new Yi(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Cs)?this.app_.getResource(Cs):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,ot)){if(this.app_.world.get(e,ot).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())si(e);n.drawCallbacks.clear();for(const e of n.postProcessBindings.keys())bi.unbind(e);n.postProcessBindings.clear(),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(Cs)&&(i.assetServer=this.app_.getResource(Cs));const o=await bs(this.app_.world,s,i);e.loadedAssets=n;for(const n of o.values())e.entities.add(n),this.app_.world.insert(n,ot,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=Ki(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(Cs)?this.app_.getResource(Cs):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)Pn.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,Ne)){const t=n.get(e,Ne);s.sprite=t.color.a,t.color.a=0,n.insert(e,Ne,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,Ne)){const t=n.get(e,Ne);t.color.a=s.sprite,n.insert(e,Ne,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.postProcessBindings.values())n.setAllPassesEnabled(t)}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 Gi=pt(null,"SceneManager");function Ki(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Gi).getSceneStatus(t)&&n._fn(...s)}}}const Ji=on([gt(Gi),mt(wt)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Qi={name:"SceneManager",build(e){const t=new qi(e);e.insertResource(Gi,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Gi),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(tn.Startup,n),e.addSystemToSchedule(tn.Last,Ji)}};class Zi{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 Kt,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 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(tn.Last);else{this.runSchedule(tn.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(tn.FixedPreUpdate),this.runSchedule(tn.FixedUpdate),this.runSchedule(tn.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(tn.PreUpdate),this.runSchedule(tn.Update),this.runSchedule(tn.PostUpdate),this.runSchedule(tn.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new kt,this.resources_=new _t;for(const e of Object.values(tn))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Zi}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(tn.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(tn.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 Mt(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(Gi).register(e),this}setInitialScene(e){return this.getResource(Gi).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new un(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(wt)||this.resources_.insert(wt,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(tn.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(tn.Last);else{this.runSchedule(tn.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(tn.FixedPreUpdate),this.runSchedule(tn.FixedUpdate),this.runSchedule(tn.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(tn.PreUpdate),this.runSchedule(tn.Update),this.runSchedule(tn.PostUpdate),this.runSchedule(tn.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new un(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(wt,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(tn.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1,ii();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=[Hi,$i,wi,di,Sn,qs];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(tn[e],performance.now()-s)}updateTime(e){const t=this.resources_.get(wt);t.delta=e,t.elapsed+=e,t.frameCount++}}function eo(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 to=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function no(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 so=[];function io(e){if(e<so.length)return so[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 so.push(t),t}function oo(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,ot);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,d=0;if(i.projectionType===Oe.Orthographic){if(d=i.orthoSize,l){d=no(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=d*r,a=ao(-u,u,-d,d,-i.farPlane,i.farPlane)}else a=co(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const h=ho(o.position.x,o.position.y,o.position.z),f=io(c.length);f.entity=e,f.viewProjection.set(po(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 ro=new Float32Array(16);function ao(e,t,n,s,i,o){const r=ro;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 lo=new Float32Array(16);function co(e,t,n,s){const i=lo;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 uo=new Float32Array(16);function ho(e,t,n){const s=uo;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 fo=new Float32Array(16);function po(e,t){const n=fo;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 mo={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function go(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,d=o.bottom+e.y*l,h=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=d+n.y-i.y*r.y,g=p+i.y):(p=d+n.y,g=h+s.y);const y=Math.max(0,m-f),_=Math.max(0,g-p);return{originX:f+r.x*y,originY:p+r.y*_,width:y,height:_,rect:{left:f,bottom:p,right:m,top:g}}}const yo=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 _o=null,wo=null;function xo(e,t){e.has(t,Ne)||e.insert(t,Ne,{texture:ye,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 vo(e,t){switch(e){case mo.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case mo.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case mo.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 bo(e,t){switch(e){case mo.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case mo.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case mo.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 So(e,t,n,s){switch(e){case mo.BottomToTop:case mo.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function Mo(e,t,n,s){if(!e.has(t,yo))return;const i=e.get(t,yo),o=vo(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,yo,i)}function Po(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function To(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Eo(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(To(r.charCodeAt(0))&&s.length>0&&To(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!To(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 Co(e){let t=1;for(;t<e;)t*=2;return t}function Ao(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 Ro(e,t){if(_o&&wo){const e=_o.getUIRectComputedWidth(wo,t);if(e>0)return e}return e.size.x}function Io(e,t){if(_o&&wo){const e=_o.getUIRectComputedHeight(wo,t);if(e>0)return e}return e.size.y}function ko(e,t,n,s,i,o){if(!e.has(t,Ne))return;const r=e.get(t,Ne);let a,l;switch(n){case mo.BottomToTop:case mo.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,Ne,r))}function Fo(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 Bo(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function zo(e,t,n,s,i){if(!e.has(t,yo))return;const o=e.get(t,yo),r=go(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,Ne)){const n=e.get(t,Ne);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,Ne,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 Wo(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 Uo=.1,$o=30,Do={r:.3,g:.5,b:.8,a:1},Oo={Left:0,Center:1,Right:2},Lo={Top:0,Middle:1,Bottom:2},Ho={Visible:0,Clip:1,Ellipsis:2},jo=Ae("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Oo.Left,verticalAlign:Lo.Top,wordWrap:!0,overflow:Ho.Visible,lineHeight:1.2});class Vo{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=d(he.textCanvasSize,he.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,Co(this.frameMaxW_)),e.height=Math.max(e.height,Co(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Co(this.frameMaxW_),e.height=Co(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=Eo(n,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===Ho.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),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,Co(f)),s.height=Math.max(s.height,Co(p)));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;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===Ho.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 Lo.Top:x=u;break;case Lo.Middle:x=u+(p-2*u-w)/2;break;case Lo.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 Oo.Left:s=u;break;case Oo.Center:s=f/2;break;case Oo.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=c}i&&e.overflow===Ho.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 Oo.Left:return"left";case Oo.Center:return"center";case Oo.Right:return"right"}}}const Xo=Wo({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?Ro(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Io(e.uiRect,e.entity):0});class No{build(e){Ue("Text",jo);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Vo(t),s=e.world,i=new Map;e.addSystemToSchedule(tn.PreUpdate,on([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,jo));for(const e of i.keys())if(!s.valid(e)||!s.has(e,jo)){if(s.valid(e)&&s.has(e,Ne)){const t=s.get(e,Ne);s.insert(e,Ne,{texture:ye,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([jo]);for(const t of e){const e=s.get(t,jo),o=s.has(t,yo)?s.get(t,yo):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!Xo.changed(a,r)){if(s.has(t,Ne)&&s.get(t,Ne).texture!==ye)continue}xo(s,t);const l=o?{size:{x:Ro(o,t),y:Io(o,t)}}:null,c=n.renderForEntity(t,e,l),u=s.get(t,Ne);s.insert(t,Ne,{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,Xo.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Yo=new No,qo=0,Go=1,Ko=De("UIMask",{enabled:!0,mode:qo});function Jo(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 Qo(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],d=e[8],h=e[9],f=e[10],p=e[11],m=e[12],g=e[13],y=e[14],_=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=d*g-h*m,T=d*y-f*m,E=d*_-p*m,C=h*y-f*g,A=h*_-p*g,R=f*_-p*y;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-y*S+_*b)*I,n[3]=(f*S-h*M-p*b)*I,n[4]=(c*E-a*R-u*T)*I,n[5]=(s*R-o*E+r*T)*I,n[6]=(y*v-m*M-_*x)*I,n[7]=(d*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+_*w)*I,n[11]=(h*v-d*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-y*w)*I,n[15]=(d*b-h*x+f*w)*I),n}function Zo(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],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:u/d}}function er(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 tr(e,t){return 2*Math.atan2(e,t)}function nr(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 sr(e,t,n,s,i,o,r,a,l,c){const u=tr(l,c),d=Math.sin(-u),h=Math.cos(-u),f=e-n,p=t-s,m=f*h-p*d+n,g=f*d+p*h+s;return m>=n-i*r&&m<=n+i*(1-r)&&g>=s-o*a&&g<=s+o*(1-a)}function ir(e,t,n,s,i,o,r){if(!e.has(t,yo)||!e.has(t,je))return null;const a=e.get(t,yo),l=e.get(t,je),c=Ro(a,t)*l.worldScale.x,u=Io(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),y=-u*p,_=u*(1-p),w=tr(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[d+m*x-y*v,h+m*v+y*x],[d+g*x-y*v,h+g*v+y*x],[d+g*x-_*v,h+g*v+_*x],[d+m*x-_*v,h+m*v+_*x]];let S=1/0,M=1/0,P=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=nr(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 or(e,t){return(n,s,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Ko]);if(0===l.length)return;const c=[],u=[],d=new Set,h=new Set;for(const e of l){const n=t.get(e,Ko);n.enabled&&(d.add(e),n.mode===Go?(u.push(e),h.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;Fo(t,e,e=>{if(i.has(e)){if(t.get(e,Ko).mode===qo)return n=!1,!0}return!1}),n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(i.has(n)){if(t.get(n,Ko).mode===qo){const e=ir(t,n,o,r,a,l,c);e&&(s=Jo(u,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=ir(t,e,o,r,a,l,c);n&&d(e,n)}}(e,t,n,c,d,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;Fo(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,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class rr{build(e){if(Ue("UIMask",Ko),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(or(e.wasmModule,e.world))}}const ar=new rr,lr=De("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),cr=De("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),ur={Normal:0,Hovered:1,Pressed:2,Disabled:3},dr=Ae("Button",{state:ur.Normal,transition:null});class hr{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 fr=pt(new hr,"UIEvents");class pr{build(e){Ue("UIRect",yo);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){_o=e,wo=t}(n,s);e.addSystemToSchedule(tn.PreUpdate,on([mt(mn)],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(tn.PostUpdate,on([mt(mn)],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(tn.PostUpdate,on([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const mr=new pr;let gr=!1,yr=!1;function _r(e){gr=e}function wr(){return gr}function xr(){return!gr}function vr(e){yr=e}function br(){return yr}const Sr=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&&(Qo(t,e),n=!1),e)}}();function Mr(e,t,n,s){t.emit(n,s,n),Fo(e,n,i=>{if(!e.has(i,lr))return!1;const o=e.get(i,lr);return o.enabled&&t.emit(i,s,n),o.blockRaycast})}class Pr{build(e){Ue("Interactable",lr),Ue("Button",dr);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new hr;e.insertResource(fr,i);let o=null,r=null;e.addSystemToSchedule(tn.PreUpdate,on([mt(hn),mt(mn)],(e,a)=>{if(i.drain(),wr()&&!br())return;const l=t.getEntitiesWithComponents([cr]);for(const e of l){const n=t.get(e,cr);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,cr,n))}if(!a.valid)return;const c=f(),u=e.mouseX*c,d=a.screenH-e.mouseY*c;Sr.update(a.viewProjection);const h=Zo(u,d,Sr.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);n.uiHitTest_update(s,h.x,h.y,p,m,g);const y=n.uiHitTest_getHitEntity(),_=4294967295===y?null:y;if(null===o||t.valid(o)||(o=null),o!==_){if(null!==o&&t.valid(o)&&t.has(o,cr)){const e=t.get(o,cr);e.hovered=!1,t.insert(o,cr,e),i.emit(o,"hover_exit")}if(null!==_){Bo(t,_,cr);const e=t.get(_,cr);e.hovered=!0,t.insert(_,cr,e),i.emit(_,"hover_enter")}o=_}if(m&&null!==_){const e=t.get(_,cr);e.pressed=!0,e.justPressed=!0,t.insert(_,cr,e),r=_,Mr(t,i,_,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,cr)){const e=t.get(r,cr);e.pressed=!1,e.justReleased=!0,t.insert(r,cr,e),Mr(t,i,r,"release"),r===o&&Mr(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(tn.Update,on([],()=>{const e=t.getEntitiesWithComponents([dr]);for(const n of e){if(Bo(t,n,lr,{enabled:!0}),!t.has(n,cr))continue;const e=t.get(n,cr),s=t.get(n,dr),i=t.get(n,lr),o=!a.has(n),r=s.state;if(i.enabled?e.pressed?s.state=ur.Pressed:e.hovered?s.state=ur.Hovered:s.state=ur.Normal:s.state=ur.Disabled,o&&a.add(n),(o||r!==s.state)&&s.transition&&t.has(n,Ne)){const o=t.get(n,Ne);o.color=Po(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,Ne,o)}}},{name:"ButtonSystem"}))}}const Tr=new Pr,Er=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}),Cr=Ae("Focusable",{tabIndex:0,isFocused:!1});class Ar{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 Rr=pt(new Ar,"FocusManager");class Ir{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(Ue("TextInput",Er),wr()&&!br())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,i=d(he.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(Rr);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,Er)?s:null}const g=()=>{l||null===m()||v()},y=()=>{l=!0},_=()=>{l=!1,v()},w=t=>{const s=m();if(null===s)return;if("Escape"===t.key)return void b();const i=n.get(s,Er);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(fr).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,Er);s.focused=!1,s.dirty=!0;e.getResource(Rr).blur()}};function v(){const t=m();if(null===t)return;const s=n.get(t,Er);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(fr).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,Er);e.focused=!1,e.dirty=!0}e.getResource(Rr).blur(),p.blur()}function S(){c=!0,u=0}p.addEventListener("input",g),p.addEventListener("compositionstart",y),p.addEventListener("compositionend",_),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",g),p.removeEventListener("compositionstart",y),p.removeEventListener("compositionend",_),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,d){(i.width<u||i.height<d)&&(i.width=Co(Math.max(i.width,u)),i.height=Co(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),y=l.padding;if(l.multiline){const e=Eo(o,p,u-2*y);let t=y;for(const n of e)o.fillText(n,y,t),t+=g}else{const e=(d-l.fontSize)/2;o.fillText(p,y,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=Eo(o,l.value,u-2*y);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=y+o.measureText(c).width,n=y+r*g,s=g}else t=y+o.measureText(e).width,n=(d-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 _=o.getImageData(0,0,u,d),w=new Uint8Array(_.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,d,r,w.length,1,!0);s.set(e,b);const S=n.get(e,Ne);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},n.insert(e,Ne,S)}e.addSystemToSchedule(tn.Update,on([mt(Rr)],e=>{const t=n.getEntitiesWithComponents([Er]);for(const e of t)Bo(n,e,Cr,{tabIndex:0,isFocused:!1}),Bo(n,e,lr,{enabled:!0,blockRaycast:!0});const s=m();if(s!==M){if(null!==M&&n.valid(M)&&n.has(M,Er)){const e=n.get(M,Er);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,Er);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(tn.PreUpdate,on([],()=>{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;n.get(o,Er).dirty=!0}const r=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Er)||(r.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([Er,yo]);for(const e of a){const t=n.get(e,Er);if(!t.dirty)continue;const s=n.get(e,yo),i=Math.ceil(s.size.x),o=Math.ceil(s.size.y);i<=0||o<=0||(xo(n,e),P(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const kr=new Ir,Fr={Simple:0,Sliced:1,Tiled:2,Filled:3},Br={Horizontal:0,Vertical:1},zr={Left:0,Right:1,Bottom:2,Top:3},Wr=Ae("Image",{texture:ye,color:{r:1,g:1,b:1,a:1},imageType:Fr.Simple,fillMethod:Br.Horizontal,fillOrigin:zr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Ur=Wo({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?Ro(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Io(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class $r{build(e){Ue("Image",Wr);const t=e.world,n=new Map;e.addSystemToSchedule(tn.PreUpdate,on([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,Wr)||n.delete(e);const e=t.getEntitiesWithComponents([Wr]);for(const s of e){const e=t.get(s,Wr),i=t.has(s,yo)?t.get(s,yo):null,o={image:e,uiRect:i,entity:s},r=n.get(s);if(r&&!Ur.changed(r,o))continue;xo(t,s);const a=t.get(s,Ne);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=Ro(i,s),a.size.y=Io(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Fr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===Br.Horizontal?e.fillOrigin===zr.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===zr.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===Fr.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,Ne,a),n.set(s,Ur.take(o))}else a.color.a=0,t.insert(s,Ne,a),n.set(s,Ur.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const Dr=new $r,Or=Ae("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Lr=Ae("ToggleGroup",{allowSwitchOff:!1});class Hr{build(e){Ue("Toggle",Or),Ue("ToggleGroup",Lr);const t=e.world,n=new Set;e.addSystemToSchedule(tn.Update,on([mt(fr)],e=>{const s=t.getEntitiesWithComponents([Or]);if(!wr()||br()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,Or);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,Or,s)):i.set(s.group,e))}const o=new Map;for(const e of s){const n=t.get(e,Or);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(Bo(t,n,lr,{enabled:!0}),!t.has(n,cr))continue;const s=t.get(n,cr),i=t.get(n,Or),r=t.get(n,lr);if(s.justPressed&&r.enabled){const s=i.group,r=0!==s&&t.valid(s)&&t.has(s,Lr);if(i.isOn&&r){if(!t.get(s,Lr).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,Or,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,Or);i.isOn&&(i.isOn=!1,t.insert(s,Or,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,Ne)){const e=t.get(n,Ne);e.color=Po(i.transition,r.enabled,s.pressed,s.hovered),t.insert(n,Ne,e)}}}for(const e of s){const n=t.get(e,Or);if(n.graphicEntity&&t.valid(n.graphicEntity)&&t.has(n.graphicEntity,Ne)){const e=t.get(n.graphicEntity,Ne);e.enabled=n.isOn,t.insert(n.graphicEntity,Ne,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const jr=new Hr,Vr=mo,Xr=Ae("ProgressBar",{value:0,fillEntity:0,direction:mo.LeftToRight});function Nr(e,t,n,s){if(!e.has(t,yo))return;const i=e.get(t,yo),o=n/2,r=s/2,a={left:-o,bottom:-r,right:o,top:r},l=go(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,Ne)){const n=e.get(t,Ne);n.size.x===l.width&&n.size.y===l.height||(n.size.x=l.width,n.size.y=l.height,e.insert(t,Ne,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 Yr{build(e){Ue("ProgressBar",Xr);const t=e.world;e.addSystemToSchedule(tn.PreUpdate,on([],()=>{const e=t.getEntitiesWithComponents([Xr,yo]);for(const n of e){const e=t.get(n,Xr);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,yo),i=Math.max(0,Math.min(1,e.value));Mo(t,e.fillEntity,e.direction,i);const o=Ro(s,n),r=Io(s,n);Nr(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const qr=new Yr,Gr=Ae("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Kr=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 Jr{build(e){Ue("Draggable",Gr),Ue("DragState",Kr);const t=e.world,n=e.getResource(fr);let s=null,i={x:0,y:0},o=null;e.addSystemToSchedule(tn.PreUpdate,on([mt(hn),mt(mn)],(e,r)=>{if(wr()&&!br())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Gr,cr]);let n=null,o=-1/0,r=-1;for(const s of e){if(!t.get(s,Gr).enabled)continue;if(t.get(s,cr).hovered){let e=0;t.has(s,Ne)&&(e=t.get(s,Ne).layer);const i=Ao(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,Kr)||t.insert(n,Kr);const e=t.get(n,Kr),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,Kr)){t.get(s,Kr).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,Gr);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=s,s=null;t.get(o,Kr).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Kr))return void(o=null);const s=t.get(o,Kr),i=t.get(o,Gr),r=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+r,u=s.startWorldPos.y+l;const d=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=d.x,u=d.y;const h=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-h,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=tr(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 Qr=new Jr,Zr=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 ea(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 ta(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 na{build(e){Ue("ScrollView",Zr);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(tn.PostUpdate,on([mt(hn),mt(mn),mt(wt)],(e,i,o)=>{const r=wr()&&!br(),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([Zr,yo]);for(const o of l){Bo(t,o,Ko,{enabled:!0,mode:qo});const l=t.get(o,Zr),c=t.get(o,yo);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 d=Ro(c,o),h=Io(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,yo)){const e=t.get(r,yo);a=Ro(e,r)||e.size.x,l=Io(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,Ne)){const e=t.get(r,Ne);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<n&&(n=d),h>s&&(s=h),f<i&&(i=f),p>o&&(o=p)}0===f&&(f=s-n),0===p&&(p=o-i)}const m=Math.max(0,f-d),g=Math.max(0,p-h);if(!r&&i.valid){Bo(t,o,lr,{enabled:!0,blockRaycast:!0});const n=t.has(o,cr)?t.get(o,cr):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=ea(l.scrollX,0,m,d);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=ea(l.scrollY,0,g,h);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*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(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=ea(l.scrollY,0,g,h);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=ea(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=ta(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)<Uo&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Uo?(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=ta(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)<Uo&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Uo?(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,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 sa=new na,ia=mo,oa=Ae("Slider",{value:0,minValue:0,maxValue:1,direction:mo.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function ra(e,t,n,s,i,o){const r=Ro(s,i)*n.worldScale.x,a=Io(s,i)*n.worldScale.y,l=tr(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),d=e-n.worldPosition.x,h=t-n.worldPosition.y,f=d*u-h*c,p=d*c+h*u,m=-s.pivot.x*r,g=-s.pivot.y*a;switch(o){case mo.LeftToRight:return r>0?(f-m)/r:0;case mo.RightToLeft:return r>0?1-(f-m)/r:0;case mo.BottomToTop:return a>0?(p-g)/a:0;case mo.TopToBottom:return a>0?1-(p-g)/a:0}}function aa(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case mo.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case mo.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case mo.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case mo.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class la{build(e){Ue("Slider",oa);const t=e.world;let n=null;e.addSystemToSchedule(tn.PreUpdate,on([mt(hn),mt(mn),mt(fr)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const o=t.getEntitiesWithComponents([oa,yo]);for(const r of o){const o=t.get(r,oa),a=t.get(r,yo);if(!wr()||br()){if(t.has(r,je)){Bo(t,r,lr,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Bo(t,o.handleEntity,lr,{enabled:!0,blockRaycast:!1});const l=t.get(r,je),c=t.has(r,cr)?t.get(r,cr):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,cr)&&(u=t.get(o.handleEntity,cr).justPressed),u&&(n=r),n===r&&e.isMouseButtonDown(0)){let e=ra(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,oa,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=Ro(a,r),d=Io(a,r),h={left:-u/2,bottom:-d/2,right:u/2,top:d/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(Mo(t,o.fillEntity,o.direction,c),zo(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,yo)){const e=t.get(o.handleEntity,yo);aa(e,o.direction,c),t.insert(o.handleEntity,yo,e),zo(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const ca=new la;class ua{build(e){Ue("Focusable",Cr);const t=e.world,n=new Ar;e.insertResource(Rr,n),e.addSystemToSchedule(tn.Update,on([mt(hn),mt(fr)],(e,s)=>{if(wr()&&!br())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([Cr]);for(const e of i){if(!t.has(e,cr))continue;t.get(e,cr).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,lr)){if(!t.get(n,lr).enabled)continue}const s=t.get(n,Cr);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,Cr)){t.get(i,Cr).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,Cr).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const da=new ua,ha=Ae("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function fa(){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 pa{build(e){Ue("SafeArea",ha);const t=e.world;let n=fa(),s=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=fa(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=fa(),s=!0});e.addSystemToSchedule(tn.PreUpdate,on([mt(mn)],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([ha,yo]);for(const e of u){const s=t.get(e,ha),i=t.get(e,yo),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,yo,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const ma=new pa,ga=Ae("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let ya=null;function _a(e,t){if(!ya)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=ya.get(e);n?n.renderer=t:ya.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}class wa{build(e){Ue("ListView",ga);const t=e.world,n=new Map;ya=n,e.addSystemToSchedule(tn.PostUpdate,on([mt(hn)],e=>{const s=wr()&&!br();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([ga,yo]);for(const o of i){Bo(t,o,lr,{enabled:!0,blockRaycast:!0}),Bo(t,o,Ko,{enabled:!0,mode:qo});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,ga),a=t.get(o,yo),l=Io(a,o),c=Ro(a,o);if(!s){const n=t.has(o,cr)?t.get(o,cr):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 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,n]of i.itemEntities)(e<d||e>=h)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=d;e<h;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,it,{value:`ListItem_${e}`}),t.insert(n,yo,{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=d,i.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const xa=new wa,va=Ae("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class ba{build(e){Ue("Dropdown",va);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,Ne)){const n=t.get(e,Ne);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&t.insert(e,Ne,{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,Ne),r=o.size.x,a=o.size.y;s.ddWidth=r;const l=n.options.length*$o;t.insert(i,yo,{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,Ne,{texture:ye,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)*$o;t.insert(o,it,{value:`Option_${e}`}),t.insert(o,yo,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*$o},offsetMax:{x:0,y:0},size:{x:r,y:$o},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,Ne,{texture:ye,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:$o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,lr,{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,jo,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Oo.Left,verticalAlign:Lo.Middle,wordWrap:!1,overflow:Ho.Clip,lineHeight:1.2}),t.insert(c,yo,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:$o},pivot:{x:.5,y:.5}}),t.setParent(c,o),s.textEntities.push(c)}d(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,jo))return;const s=t.get(n,jo);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,jo,{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,lr)&&t.insert(e,lr,{enabled:n,blockRaycast:!0,raycastTarget:!0}),t.has(e,Ne))){const s=t.get(e,Ne);t.insert(e,Ne,{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 d(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s)||!t.has(s,Ne))continue;const i=n===e.highlightIndex?{...Do}:{r:.95,g:.95,b:.95,a:1};t.insert(s,Ne,{texture:ye,color:i,size:{x:e.ddWidth,y:$o},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 n of e.optionEntities){if(!t.valid(n)||!t.has(n,cr))continue;if(t.get(n,cr).hovered)return!0}return!1}e.addSystemToSchedule(tn.Update,on([mt(hn),mt(fr)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=wr()&&!br(),p=t.getEntitiesWithComponents([va]);for(const m of p){const p=t.get(m,va);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;Bo(t,m,lr,{enabled:!0,blockRaycast:!0});const y=t.has(m,cr)?t.get(m,cr):null;if(y?.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,cr))continue;if(t.get(n,cr).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,cr))continue;if(t.get(s,cr).hovered){n=e;break}}n>=0&&n!==g.highlightIndex&&(g.highlightIndex=n,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)&&(y?.hovered||h(g)||r(m,p,g))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}}const Sa=new ba,Ma=0,Pa=0,Ta=2,Ea=Ae("LayoutGroup",{direction:Ma,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Pa,reverseOrder:!1});class Ca{build(e){Ue("LayoutGroup",Ea);const t=e.world;e.addSystemToSchedule(tn.PreUpdate,on([],()=>{const e=t.getEntitiesWithComponents([Ea,yo,Je]);for(const n of e){const e=t.get(n,Ea),s=t.get(n,yo),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,yo)&&t.has(e,je)&&o.push({entity:e,rect:t.get(e,yo)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=Ro(s,n),a=Io(s,n),l=s.pivot.x,c=s.pivot.y,u=e.padding,d=e.direction===Ma;let h=0;for(let n=0;n<o.length;n++){const s=o[n],i=Ro(s.rect,s.entity),f=Io(s.rect,s.entity),p=s.rect.pivot.x,m=s.rect.pivot.y;let g,y;d?(g=-l*r+u.left+h+p*i,y=e.childAlignment===Pa?(1-c)*a-u.top-(1-m)*f:e.childAlignment===Ta?-c*a+u.bottom+m*f:(.5-c)*a+.5*(u.bottom-u.top)+(m-.5)*f,h+=i,n<o.length-1&&(h+=e.spacing)):(g=e.childAlignment===Pa?-l*r+u.left+p*i:e.childAlignment===Ta?(1-l)*r-u.right-(1-p)*i:(.5-l)*r+.5*(u.left-u.right)+(p-.5)*i,y=(1-c)*a-u.top-h-(1-m)*f,h+=f,n<o.length-1&&(h+=e.spacing));const _=t.get(s.entity,je);_.position.x=g,_.position.y=y,t.insert(s.entity,je,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}}const Aa=new Ca;class Ra{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(tn.PostUpdate,on([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const Ia=new Ra;async function ka(e,t,n){const s=e.getResource(Gi);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function Fa(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 Ba=pt({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),za=pt(null,"PhysicsAPI");function Wa(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Ua(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class $a{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(Ba,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Fa(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(tn.PostUpdate,on([mt(wt)],a=>{const l=r.getEntitiesWithComponents([lt,je]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,lt),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=Wa(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),Da(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===ht.Kinematic){const e=Wa(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 d=a,h=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=Wa(n.worldRotation),i=a-n.worldPosition.x,o=l-n.worldPosition.y,r=Math.cos(-s),u=Math.sin(-s);d=(i*r-o*u)/(0!==n.worldScale.x?n.worldScale.x:1),h=(i*u+o*r)/(0!==n.worldScale.y?n.worldScale.y:1),f=c-s}}u.position.x=d,u.position.y=h;const p=Ua(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(Ba,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(za,Oa._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function Da(e,t,n){const s=e.world;if(s.has(n,ct)){const e=s.get(n,ct);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,ut)){const e=s.get(n,ut);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,dt)){const e=s.get(n,dt);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 Oa{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(Oa.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 La={nearest:0,linear:1},Ha={repeat:0,clamp:1,mirror:2};function ja(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=La[s.filterMode??"linear"]??1,a=Ha[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 Va(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 Xa(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,d=a+a,h=l+l,f=c+c,p=a*d,m=a*h,g=a*f,y=l*h,_=l*f,w=c*f,x=u*d,v=u*h,b=u*f;return new Float32Array([(1-(y+w))*i,(m+b)*i,(g-v)*i,0,(m-b)*o,(1-(p+w))*o,(_+x)*o,0,(g+v)*r,(_-x)*r,(1-(p+y))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function Na(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=ps(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]=ja(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 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,n,s,i){const o={};for(const r of s.entities)for(const s of r.components){const r=ms(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 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),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const f=n.loadSkeleton(d,h,s,s.length,r);if(t._free(d),f<0)continue;o[a]=f;const p=Va(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=ja(e,o,!1),a=e.getResourceManager().getTextureGLId(r);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(n,o,h,s,i)),r){const e={gravity:a?.gravity??{...ce},fixedTimestep:a?.fixedTimestep??ue,subStepCount:a?.subStepCount??4};new $a("",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=ps(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=ja(e,c,!1),d=e.getResourceManager();s[o]=d.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=ps(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=Pn.createShader(e.vertexSource,e.fragmentSource),s[i]=r),n[o]=Pn.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=ps(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=Wn(s),r=new Map;for(const t of o)try{const s=await n.loadPixels(t);r.set(t,ja(e,s))}catch{r.set(t,0)}Dn(Un(i,s,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(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=ps(t.type);for(const o of i){if("tilemap"!==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=as(JSON.parse(t));if(!s)continue;const o=[];for(const t of s.tilesets){const s=ls(i,t.image);let r=0;try{const t=await n.loadPixels(s);r=ja(e,t),qn(r,t.width,t.height)}catch{}o.push({textureHandle:r,columns:t.columns})}Jn(i,{tileWidth:s.tileWidth,tileHeight:s.tileHeight,layers:s.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${i}`,e)}}}}}(n,s,i),await async function(e,t){const n=[],s=new Set;for(const t of e.entities)for(const e of t.components){const t=ps(e.type);for(const i of t){if("audio"!==i.type)continue;const t=e.data[i.field];"string"==typeof t&&t&&!s.has(t)&&(s.add(t),n.push(t))}}0!==n.length&&(t?await Promise.all(n.map(async e=>{try{const n=await t.readBinary(e);await Xn.preloadFromData(e,n.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await Xn.preloadAll(n).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(s,i),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=ps(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=vs(t.world,s);if(c&&t.hasResource(Gi))for(const e of m.values())t.world.insert(e,ot,{scene:c,persistent:!1});if(o&&h){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=ms(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}(h,s,d,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,d=a?.timeScale??1;u&&s.update(r,l*d);let h=0;if(c.has(o,je)){const e=Xa(c.get(o,je),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>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),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(r,e,c,u,d,f);const p=n.HEAPU32[d>>2],m=n.HEAPU32[f>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*i),y=new Uint16Array(n.HEAPU8.buffer,u,o),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,_>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(y),t.renderer_submitTriangles(_,i,w,o,p,m,h),t._free(_),t._free(w),n._free(c),n._free(u),n._free(d),n._free(f)}h&&t._free(h)}})}(t,n,o,h,e)}if(l){const e=t.getResource(Cs);e&&e.setAddressableManifest(l)}}function Ya(e,t,n){return{name:e,async setup(){await Na({...n,sceneData:t,sceneName:e})}}}async function qa(e){const{app:t,firstScene:n,aspectRatio:s}=e;eo(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(Gi);for(const t of e.scenes)o.register(Ya(t.name,t.data,i));n&&(o.setInitial(n),await o.load(n)),void 0!==s&&Ps(t.world,s)}class Ga{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=ms(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=ps(e.type);for(const i of o){const o=e.data[i.field];"string"==typeof o&&o&&("font"===i.type?(s.add(o),t.add(o)):"material"===i.type||"anim-clip"===i.type||"tilemap"===i.type?t.add(o):"audio"===i.type&&n.add(o))}}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 Ka="__preview__";class Ja{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(Gi);t.register({name:Ka,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Ka),this.loadPromise_=t.load(Ka).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 Ga(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await Na({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:n,spineModule:s,sceneName:Ka})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([Ye]);for(const s of n){if(e.get(s,Ye).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(Gi).getScene(Ka),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,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(Gi);await e.switchTo(Ka),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 Qa={create(e){const t=e.depth??!0,n="linear"===e.filter,s=(t?1:0)|(n?2:0),i=Di.createRenderTarget(e.width,e.height,s);return{_handle:i,textureId:Di.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:n?"linear":"nearest"}},release(e){Di.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Di.releaseRenderTarget(e._handle),Qa.create({width:t,height:n,depth:e._depth,filter:e._filter})),begin(e,t){Di.begin(t,e._handle)},end(){Di.end()},getDepthTexture:e=>Di.getTargetDepthTexture(e._handle)};var Za;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Za||(Za={}));class el{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Za[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Za.Debug:console.debug(t,n);break;case Za.Info:console.log(t,n);break;case Za.Warn:console.warn(t,n);break;case Za.Error:console.error(t,n)}}}class tl{constructor(){this.handlers_=[],this.minLevel_=Za.Info,this.addHandler(new el)}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(Za.Debug,e,t,n)}info(e,t,n){this.log(Za.Info,e,t,n)}warn(e,t,n){this.log(Za.Warn,e,t,n)}error(e,t,n){this.log(Za.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 nl=new tl;function sl(){return nl}function il(e){nl.setMinLevel(e)}function ol(e,t,n){nl.debug(e,t,n)}function rl(e,t,n){nl.info(e,t,n)}function al(e,t,n){nl.warn(e,t,n)}function ll(e,t,n){nl.error(e,t,n)}const cl={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},ul={Running:0,Paused:1,Completed:2,Cancelled:3},dl={None:0,Restart:1,PingPong:2};const hl=1.70158,fl=2.70158,pl=2.5949095;const ml=2*Math.PI/3,gl=2*Math.PI/4.5;const yl=7.5625,_l=2.75;const wl=1e-6;function xl(e,t,n){switch(e){case cl.Linear:return t;case cl.EaseInQuad:return function(e){return e*e}(t);case cl.EaseOutQuad:return function(e){return e*(2-e)}(t);case cl.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case cl.EaseInCubic:return function(e){return e*e*e}(t);case cl.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case cl.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case cl.EaseInBack:return function(e){return fl*e*e*e-hl*e*e}(t);case cl.EaseOutBack:return function(e){const t=e-1;return 1+fl*t*t*t+hl*t*t}(t);case cl.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-pl)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+pl)+2)/2}(t);case cl.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*ml)}(t);case cl.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*ml)+1}(t);case cl.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*gl)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*gl)/2+1}(t);case cl.EaseOutBounce:return function(e){return e<1/_l?yl*e*e:e<2/_l?yl*(e-=1.5/_l)*e+.75:e<2.5/_l?yl*(e-=2.25/_l)*e+.9375:yl*(e-=2.625/_l)*e+.984375}(t);case cl.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)<wl)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)<wl)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 cl.Step:return function(e){return e<1?0:1}(t);default:return t}}const vl=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??cl.Linear,bezierPoints:null,state:ul.Running,loop:i?.loop??dl.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)===ul.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==ul.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=xl(t.easing,n,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*s),n>=1){if(t.loop!==dl.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===dl.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=ul.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===ul.Running&&(t.state=ul.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===ul.Paused&&(t.state=ul.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=ul.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:ul.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 bl{constructor(e){this.id=e}get state(){return vl.getState(this.id)}bezier(e,t,n,s){return vl.setBezier(this.id,e,t,n,s),this}then(e){return e instanceof bl?vl.setSequenceNext(this.id,e.id):vl.setSequenceNextExternal(this.id,e),this}pause(){vl.pause(this.id)}resume(){vl.resume(this.id)}cancel(){vl.cancel(this.id)}}const Sl={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 Ml{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 bl?(vl.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 Pl=null,Tl=null;function El(e,t){Pl=e,Tl=t,vl.init(e,t)}function Cl(){vl.shutdown(),Pl=null,Tl=null}function Al(){if(!Pl)throw new Error("Tween API not initialized");return Pl}function Rl(){if(!Tl)throw new Error("Tween API not initialized");return Tl}const Il={to(e,t,n,s,i,o){const r=Al(),a=Rl(),l=o?.easing??cl.Linear,c=o?.delay??0,u=o?.loop??dl.None,d=o?.loopCount??0,h=r._anim_createTween(a,e,t,n,s,i,l,c,u,d);return new Ml(r,a,h)},value(e,t,n,s,i){const o=vl.create(e,t,n,s,i);return new bl(o)},cancel(e){Al()._anim_cancelTween(Rl(),e.entity)},cancelAll(e){Al()._anim_cancelAllTweens(Rl(),e)},update(e){Al()._anim_updateTweens(Rl(),e),vl.update(e)}};class kl{constructor(){this.name="AnimationPlugin"}build(e){El(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(tn.Update,on([mt(wt)],e=>{Il.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(tn.Update,on([mt(wt)],e=>{Vn(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){Cl()}}const Fl=new kl;var Bl;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(Bl||(Bl={}));const zl={model:Bl.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function Wl(e,t=zl){const{model:n,refDistance:s,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(n){case Bl.Linear:{const e=i-s;if(e<=0)return 1;a=1-(Math.min(Math.max(r,s),i)-s)/e;break}case Bl.Inverse:a=s/Math.max(r,s);break;case Bl.Exponential:a=Math.pow(Math.max(r,s)/s,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function Ul(e,t,n,s,i){const o=e-n;return Math.max(-1,Math.min(1,o/i))}const $l=Ae("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:Bl.Inverse,rolloff:1,priority:0,enabled:!0}),Dl=Ae("AudioListener",{enabled:!0});class Ol{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;Xn.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(tn.PreUpdate,on([mt(wt)],t=>{if(!(!wr()||br()))return void(c&&(l=!1,c=!1));c=!0;const s=e.world;let i=0,u=0,d=!1;const h=s.getEntitiesWithComponents([Dl,Xe]);for(const e of h){if(s.get(e,Dl).enabled){const t=s.get(e,Xe);i=t.position.x,u=t.position.y,d=!0;break}}const f=s.getEntitiesWithComponents([$l]);a.clear();for(const e of f){const t=s.get(e,$l);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=Xn.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}d||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=s.tryGet?.(e,Xe),a=r?.position.x??0,h=r?.position.y??0,f=a-i,p=h-u,m=Wl(Math.sqrt(f*f+p*p),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=Ul(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(),Xn.dispose()}}const Ll=new Ol;let Hl=null,jl=null;function Vl(e,t){Hl=e,jl=t}function Xl(){Hl=null,jl=null}const Nl={update(e){Hl&&jl&&Hl.particle_update?.(jl,e)},play(e){Hl&&jl&&Hl.particle_play?.(jl,e)},stop(e){Hl&&jl&&Hl.particle_stop?.(jl,e)},reset(e){Hl&&jl&&Hl.particle_reset?.(jl,e)},getAliveCount:e=>Hl?Hl.particle_getAliveCount?.(e)??0:0};class Yl{constructor(){this.name="ParticlePlugin"}build(e){Vl(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(tn.Update,on([mt(wt)],e=>{Nl.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){Xl()}}const ql=new Yl,Gl=1e6;class Kl{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.sourceEntityKeys_=new Map}build(e){ts(e.wasmModule);const t=e.world,n=this.initializedLayers_,s=this.sourceEntityKeys_;e.pipeline?.setTilemapRenderer(()=>{const i=e.getResource(mn),o=i?.valid?i.worldLeft:-1e6,r=i?.valid?i.worldBottom:-1e6,a=i?.valid?i.worldRight:Gl,l=i?.valid?i.worldTop:Gl,c=t.getEntitiesWithComponents([os,je]);for(const e of c){const s=t.tryGet(e,os),i=t.tryGet(e,je);if(!s||!i)continue;const c=s.texture;if(!c)continue;const u=Gn(c);if(!u)continue;if(!n.has(e)){if(ss.initLayer(e,s.width,s.height,s.tileWidth,s.tileHeight),s.tiles.length>0){const t=new Uint16Array(s.tiles.length);for(let e=0;e<s.tiles.length;e++)t[e]=s.tiles[e];ss.setTiles(e,t)}n.add(e)}const d=s.tileWidth/u.width,h=s.tileHeight/u.height;ss.submitLayer(e,c,s.layer,0,s.tilesetColumns,d,h,i.worldPosition.x,i.worldPosition.y,o,r,a,l)}const u=t.getEntitiesWithComponents([is,je]);for(const e of u){if(t.tryGet(e,os))continue;const i=t.tryGet(e,is),c=t.tryGet(e,je);if(!i?.source||!c)continue;const u=Qn(i.source);if(!u)continue;if(!s.has(e)){const t=[];for(let s=0;s<u.layers.length;s++){const i=1073741824+256*e+s,o=u.layers[s];ss.initLayer(i,o.width,o.height,u.tileWidth,u.tileHeight),o.tiles.length>0&&ss.setTiles(i,o.tiles),t.push(i),n.add(i)}s.set(e,t)}const d=s.get(e);for(let e=0;e<u.layers.length&&e<d.length;e++){const t=d[e],n=u.tilesets[0];if(!n)continue;const s=Gn(n.textureHandle);if(!s)continue;const i=u.tileWidth/s.width,h=u.tileHeight/s.height;ss.submitLayer(t,n.textureHandle,e,0,n.columns,i,h,c.worldPosition.x,c.worldPosition.y,o,r,a,l)}}})}cleanup(){for(const e of this.initializedLayers_)ss.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),Kn(),ns()}}const Jl=new Kl;function Ql(e,t){return e.toFixed(t)}function Zl(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}class ec{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">${Ql(e.fps,1)}</span> Frame: <span style="color:#d19a66">${Ql(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>${Zl(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${Ql(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 tc(){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 nc=pt(tc(),"Stats");class sc{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 ic="StatsCollect";class oc{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 rc{constructor(e){this.name="Stats",this.collector_=new oc,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(nc,tc());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new ec(e,this.options_.position)}const t=this.collector_,n=this.overlay_,s=on([mt(wt),{_type:"get_world"}],(s,i)=>{t.pushFrame(s.delta);const o=e.getResource(nc);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(ic),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=Di.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:ic});e.addSystemToSchedule(tn.Last,s)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const ac=new rc;class lc{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 cc(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 uc(e){const{app:t,module:n,assets:s,scenes:i,firstScene:o}=e,r=t.getResource(Cs);r&&(r.registerEmbeddedAssets(s),r.setEmbeddedOnly(!0));const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await cc(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 cc(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new lc(s);await qa({app:t,module:n,provider:c,scenes:i,firstScene:o,spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()}const dc=[Yo,ar,mr,Dr,qr,Tr,Qr,sa,ca,jr,kr,da,ma,xa,Sa,Aa,Ia],hc=[...dc,Fl,Ll,ql,Jl];function fc(e,t){return function(e,t){const n=Zi.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ys(e),bn(e),ui(e),_i(e),Ui(e),Li(e);const i=new Vi;n.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=oo(e,s,t,i));const r=n.getResource(mn);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(mn,{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;Di.setClearColor(e.x,e.y,e.z,e.w)}const u=(h()-o)/1e3;let d;if(Di.resize(t,l),n.hasResource(Gi)){const e=n.getResource(Gi).getActiveScenes();e.length>0&&(d=new Set(e))}i.setActiveScenes(d??null);const f=oo(e,s,t,l,n.world,d);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:to,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,cameraEntity:e.entity})}Di.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(tn.First,l),n.addSystemToSchedule(tn.Last,c),n.addPlugin(Rs),n.addPlugin(Ls),n.addPlugin(pn),n.addPlugin(Qi),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:hc,...t})}class pc{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 mc(e){return(t,n)=>(u(e,t).then(e=>{n(e.instance,e.module)}),{})}async function gc(e,t){try{return await e({instantiateWasm:mc(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}async function yc(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:mc("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=fc(a,{glContextHandle:u,getViewportSize:()=>({width:o.width,height:o.height})});e.runtimeConfig&&me(d,e.runtimeConfig);let h=null;e.spineFactory&&(h=await gc(e.spineFactory,"spine.wasm"));let f=null;e.physicsFactory&&(f=await gc(e.physicsFactory,"physics.wasm"));const p=new pc(i),m=[];for(const t of e.sceneNames){const e=await l(`scenes/${t}.json`);m.push({name:t,data:JSON.parse(e)})}await qa({app:d,module:a,provider:p,scenes:m,firstScene:e.firstScene,spineModule:h,physicsModule:f,physicsConfig:e.physicsConfig,manifest:n,aspectRatio:o.width/o.height}),d.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{zt as Added,kl as AnimationPlugin,Zi as App,As as AssetPlugin,Is as AssetRefCounter,Es as AssetServer,Cs as Assets,Bn as AsyncCache,Bl as AttenuationModel,Xn as Audio,p as AudioBus,Dl as AudioListener,m as AudioMixer,Ol as AudioPlugin,g as AudioPool,$l as AudioSource,Qe as BitmapText,gn as BlendMode,ht as BodyType,ct as BoxCollider,dr as Button,ur as ButtonState,Ye as Camera,qe as Canvas,dt as CapsuleCollider,Wt as Changed,Je as Children,ut as CircleCollider,Le as ClearFlags,Xt as Commands,Yt 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,de as DEFAULT_SPINE_SKIN,se as DEFAULT_SPRITE_SIZE,ne as DEFAULT_TEXT_CANVAS_SIZE,oi as DataType,Jr as DragPlugin,Kr as DragState,Gr as Draggable,Js as Draw,va as Dropdown,ba as DropdownPlugin,cl as EasingType,et as EmitterShape,Nt as EntityCommands,Qt as EventReader,en as EventReaderInstance,Kt as EventRegistry,Jt as EventWriter,Zt as EventWriterInstance,mo as FillDirection,Br as FillMethod,zr as FillOrigin,Rr as FocusManager,Ar as FocusManagerState,ua as FocusPlugin,Cr as Focusable,sc as FrameHistory,ji as GLDebug,fi as Geometry,nn as GetWorld,ge as INVALID_ENTITY,_e as INVALID_FONT,we as INVALID_MATERIAL,ye as INVALID_TEXTURE,Wr as Image,$r as ImagePlugin,Fr as ImageType,hn as Input,fn as InputPlugin,dn as InputState,lr as Interactable,Ca as LayoutGroupPlugin,ga as ListView,wa as ListViewPlugin,Ve as LocalTransform,Za as LogLevel,tl as Logger,dl as LoopMode,Pn as Material,zn as MaterialLoader,Ft as Mut,it as Name,Ke as Parent,Nl as Particle,nt as ParticleEasing,st as ParticleEmitter,Yl as ParticlePlugin,Oa as Physics,Ba as PhysicsEvents,$a as PhysicsPlugin,bi as PostProcess,xi as PostProcessStack,rt as PostProcessVolume,$s as PrefabServer,Ds as Prefabs,Os as PrefabsPlugin,Ja as PreviewPlugin,Xr as ProgressBar,Vr as ProgressBarDirection,Yr as ProgressBarPlugin,Oe as ProjectionType,Lt as Query,Ht as QueryInstance,jt as Removed,Vt as RemovedQueryInstance,Vi as RenderPipeline,Bi as RenderStage,Qa as RenderTexture,Di as Renderer,mt as Res,gt as ResMut,lt as RigidBody,he as RuntimeConfig,ha as SafeArea,pa as SafeAreaPlugin,He as ScaleMode,Gi as SceneManager,qi as SceneManagerState,ot as SceneOwner,tn as Schedule,Zr as ScrollView,na as ScrollViewPlugin,Fn as ShaderSources,tt as SimulationSpace,oa as Slider,ia as SliderDirection,la as SliderPlugin,Ze as SpineAnimation,Ne as Sprite,jn as SpriteAnimator,nc as Stats,oc as StatsCollector,ec as StatsOverlay,rc as StatsPlugin,un as SystemRunner,jo as Text,Oo as TextAlign,Er as TextInput,Ir as TextInputPlugin,Ho as TextOverflow,No as TextPlugin,Vo as TextRenderer,Lo as TextVerticalAlign,is as Tilemap,ss as TilemapAPI,os as TilemapLayer,Kl as TilemapPlugin,wt as Time,Or as Toggle,Hr as TogglePlugin,je as Transform,Il as Tween,Ml as TweenHandle,ul as TweenState,Sl as TweenTarget,mn as UICameraInfo,hr as UIEventQueue,fr as UIEvents,cr as UIInteraction,Pr as UIInteractionPlugin,pr as UILayoutPlugin,Ko as UIMask,rr as UIMaskPlugin,yo as UIRect,Ra as UIRenderOrderPlugin,Ge as Velocity,pc as WeChatAssetProvider,Ga as WebAssetProvider,kt as World,Xe as WorldTransform,ln as addStartupSystem,an as addSystem,cn as addSystemToSchedule,Fl as animationPlugin,me as applyBuildRuntimeConfig,Mo as applyDirectionalFill,fe as applyRuntimeConfig,Rs as assetPlugin,Ll as audioPlugin,Wl as calculateAttenuation,Ul as calculatePanning,Fi as cleanupAllPostProcessVolumes,ki as cleanupPostProcessVolume,Hn as clearAnimClips,ii as clearDrawCallbacks,Kn as clearTextureDimensionsCache,Zn as clearTilemapSourceCache,ke as clearUserComponents,Se as color,vo as computeFillAnchors,So as computeFillSize,bo as computeHandleAnchors,go as computeUIRectLayout,or as createMaskProcessor,Ya as createRuntimeSceneConfig,fc as createWebApp,ol as debug,tc as defaultFrameStats,Ae as defineComponent,qt as defineEvent,pt as defineResource,on as defineSystem,Re as defineTag,Qr as dragPlugin,Sa as dropdownPlugin,ll as error,Wn as extractAnimClipTexturePaths,Ts as findEntityByName,eo as flushPendingSystems,da as focusPlugin,C as getAddressableType,A as getAddressableTypeByEditorType,I as getAllAssetExtensions,Ci as getAllEffectDefs,Ln as getAnimClip,D as getAssetBuildTransform,z as getAssetMimeType,T as getAssetTypeEntry,$e as getComponent,ps as getComponentAssetFieldDescriptors,fs as getComponentAssetFields,at as getComponentDefaults,_s as getComponentEntityFields,ms as getComponentSpineFieldDescriptor,F as getCustomExtensions,E as getEditorType,Ti as getEffectDef,Ei as getEffectTypes,sl as getLogger,t as getPlatform,s as getPlatformType,Gn as getTextureDimensions,Qn as getTilemapSource,Ie as getUserComponent,B as getWeChatPackOptions,Dr as imagePlugin,rl as info,Ys as initDrawAPI,Li as initGLDebugAPI,ui as initGeometryAPI,bn as initMaterialAPI,Vl as initParticleAPI,uc as initPlayableRuntime,_i as initPostProcessAPI,Ui as initRendererAPI,qa as initRuntime,ts as initTilemapAPI,El as initTweenAPI,yc as initWeChatRuntime,pn as inputPlugin,Fs as instantiatePrefab,Jo as intersectRects,Qo as invertMatrix4,ze as isBuiltinComponent,W as isCustomExtension,wr as isEditor,R as isKnownAssetExtension,n as isPlatformInitialized,br as isPlayMode,xr as isRuntime,yn as isTextureRef,i as isWeChat,o as isWeb,Aa as layoutGroupPlugin,xa as listViewPlugin,Ms as loadComponent,Fa as loadPhysicsModule,Na as loadRuntimeScene,vs as loadSceneData,bs as loadSceneWithAssets,us as loadTiledMap,k as looksLikeAssetPath,Un as parseAnimClipData,cs as parseTiledMap,as as parseTmjJson,ql as particlePlugin,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,sr as pointInOBB,er as pointInWorldRect,Ls as prefabsPlugin,qr as progressBarPlugin,Me as quat,Dn as registerAnimClip,$ as registerAssetBuildTransform,Ue as registerComponent,hs as registerComponentAssetFields,ys as registerComponentEntityFields,ni as registerDrawCallback,ks as registerEmbeddedAssets,kn as registerMaterialCallback,qn as registerTextureDimensions,Jn as registerTilemapSource,ws as remapEntityFields,ls as resolveRelativePath,ma as safeAreaPlugin,Qi as sceneManagerPlugin,Zo as screenToWorld,sa as scrollViewPlugin,_r as setEditorMode,_a as setListViewRenderer,il as setLogLevel,vr as setPlayMode,Mt as setWasmErrorHandler,qs as shutdownDrawAPI,Hi as shutdownGLDebugAPI,di as shutdownGeometryAPI,Sn as shutdownMaterialAPI,Xl as shutdownParticleAPI,wi as shutdownPostProcessAPI,$i as shutdownRendererAPI,ns as shutdownTilemapAPI,Cl as shutdownTweenAPI,ca as sliderPlugin,Vn as spriteAnimatorSystemUpdate,ac as statsPlugin,ko as syncFillSpriteSize,Ii as syncPostProcessVolume,kr as textInputPlugin,Yo as textPlugin,Jl as tilemapPlugin,U as toBuildPath,jr as togglePlugin,ka as transitionTo,Tr as uiInteractionPlugin,mr as uiLayoutPlugin,ar as uiMaskPlugin,dc as uiPlugins,Ia as uiRenderOrderPlugin,On as unregisterAnimClip,Fe as unregisterComponent,si as unregisterDrawCallback,Ps as updateCameraAspectRatio,xe as vec2,ve as vec3,be as vec4,al as warn,Ki as wrapSceneSystem,X as wxFileExists,N as wxFileExistsSync,G as wxGetImagePixels,q as wxLoadImage,K as wxLoadImagePixels,j as wxReadFile,V 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 d(e,n){return t().createCanvas(e,n)}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),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 y{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 _{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}}async loadBufferFromData(e,t){return this.loadBuffer(e)}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 y(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 b=[{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},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0}],v={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 b)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 C(e){return T(e)?.editorType??"unknown"}function E(e){return T(e)?.addressableType??null}function A(e){for(const t of b)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 b)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 v[e.toLowerCase()]}function U(e){const t=T(e);return t?.wechatPackInclude??!1}function W(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 $(e,t){for(const n of b)n.editorType===e&&(n.buildTransform=t)}function D(e){return T(e)?.buildTransform}let L=null;function O(){return L||(L=wx.getFileSystemManager()),L}function H(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if(U(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)=>{O().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(H(e,t.errMsg)))}})})}function V(e,t="utf-8"){return new Promise((n,s)=>{O().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(H(e,t.errMsg)))}})})}function X(e){return new Promise(t=>{O().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function N(e){const t=O();try{return t.accessSync(e),!0}catch{return!1}}function Y(e,t){return new Promise((n,s)=>{O().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 O().readFileSync(e)}(W(e))}async readTextFile(e){return function(e,t="utf-8"){return O().readFileSync(e,t)}(W(e))}async fileExists(e){return N(W(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 _}},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,de="default",he={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=he.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=he.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=he.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=he.canvasMatchWidthOrHeight)}const pe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function me(e,t){if(void 0!==t.maxDeltaTime&&(he.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(he.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(he.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(he.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(he.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");he.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&&(he.canvasScaleMode=pe[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(he.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight)}const ge=0,ye=4294967295,_e=4294967295,we=0,xe=(e=0,t=0)=>({x:e,y:t}),be=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),ve=(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 Ce(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 Ee(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function Ae(e,t){const n=Ue.get(e)??Ee().get(e);if(n)return n;const s=Ce(e,t);return Ee().set(e,s),Ue.set(e,s),Be(e,t,!1),s}function Re(e){const t=Ue.get(e)??Ee().get(e);if(t)return t;const n=Ce(e,{});return Ee().set(e,n),Ue.set(e,n),Be(e,{},!0),n}function Ie(e){return Ee().get(e)}function ke(){const e=Ee();for(const t of e.keys())Ue.delete(t);e.clear()}function Fe(e){Ee().delete(e),Ue.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 Ue=new Map;function We(e,t){Ue.set(e,t)}function $e(e){return Ue.get(e)??Ie(e)}function De(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return Ue.set(e,n),n}const Le={Perspective:0,Orthographic:1},Oe={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}}),Ve=je,Xe=je,Ne=De("Sprite",{texture:ye,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=De("Camera",{projectionType:Le.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:Oe.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:_e,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={Point:0,Circle:1,Rectangle:2,Cone:3},tt={World:0,Local:1},nt={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},st=De("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:et.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:nt.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:nt.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:ye,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:tt.World,enabled:!0}),it=Ae("Name",{value:""}),ot=Ae("SceneOwner",{scene:"",persistent:!1}),rt=Ae("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});function at(e){const t=$e(e);return t?Pe(t._default):null}const lt=De("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ct=De("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ut=De("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),dt=De("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ht={Static:0,Kinematic:1,Dynamic:2};let ft=0;function pt(e,t){const n=++ft;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function mt(e){return{_type:"res",_resource:e}}function gt(e){return{_type:"res_mut",_resource:e}}class yt{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 _t{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 yt(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const wt=pt({delta:0,elapsed:0,frameCount:0},"Time");function xt(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=bt(t[e]),o=bt(i);"null"!==n&&"undefined"!==n&&(n!==o&&null!=i&&s.push({field:e,expected:n,actual:o,value:i}))}return s}function bt(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function vt(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 St=null;function Mt(e){St=e}function Pt(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),St&&St(e,t)}function Tt(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 Ct=1;const Et=new WeakMap;function At(e){let t=Et.get(e);return void 0===t&&(t=Ct++,Et.set(e,t)),t}const Rt=[];function It(e,t=[],n=[]){Rt.length=0;for(const t of e)Rt.push(At(t));Rt.sort((e,t)=>e-t);let s=Rt.join(",");if(t.length>0){Rt.length=0;for(const e of t)Rt.push(At(e));Rt.sort((e,t)=>e-t),s+="|+"+Rt.join(",")}if(n.length>0){Rt.length=0;for(const e of n)Rt.push(At(e));Rt.sort((e,t)=>e-t),s+="|-"+Rt.join(",")}return s}class kt{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 Pt(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){Pt(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){Pt(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Pt(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{const s=t._default,i=n;let o=i;for(const e of Object.keys(i))e in s||(o===i&&(o={...i}),delete o[e]);this.getBuiltinMethods(t._cppName).add(e,Tt(o))}catch(n){Pt(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 Pt(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=t._default,i={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&e in s&&(i[e]=t);const e=xt(t._name,s,i);if(e.length>0)throw new Error(vt(t._name,e))}const o={...t._default,...i};let r=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);r=!n.has(e),n.add(e,Tt(o))}catch(n){Pt(n,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),o}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 Pt(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 Pt(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){Pt(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=xt(t._name,t._default,e);if(i.length>0)throw new Error(vt(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 Ue)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=Ee();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??It(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 Ft(e){return{_type:"mut",_component:e}}function Bt(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function zt(e){return{_filterType:"added",_component:e}}function Ut(e){return{_filterType:"changed",_component:e}}function Wt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function $t(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Dt(e){return Bt(e)||Wt(e)||$t(e)?e._component:e}function Lt(e,t=[],n=[]){const s=[],i=[],o=[];return e.forEach((e,t)=>{Bt(e)&&s.push(t),Wt(e)?i.push({index:t,component:e._component}):$t(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:o,with:(...s)=>Lt(e,[...t,...s],n),without:(...s)=>Lt(e,t,[...n,...s])}}function Ot(...e){return Lt(e)}class Ht{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(Dt),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_=It(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 jt(e){return{_type:"removed",_component:e}}class Vt{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 Xt(){return{_type:"commands"}}class Nt{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 Yt{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Nt(this,null);return this.spawned_.push(e),e}entity(e){return new Nt(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 qt(e){return{_id:Symbol(`Event_${e}`),_name:e}}class Gt{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 Kt{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Gt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Gt,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function Jt(e){return{_type:"event_writer",_event:e}}function Qt(e){return{_type:"event_reader",_event:e}}class Zt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class en{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var tn;function nn(){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"}(tn||(tn={}));let sn=0;function on(e,t,n){const s=++sn;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function rn(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function an(e){rn().push({schedule:tn.Update,system:e})}function ln(e){rn().push({schedule:tn.Startup,system:e})}function cn(e,t){rn().push({schedule:e,system:t})}class un{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 Yt&&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 Ht(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 Yt(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 Zt(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new en(n)}case"removed":{const t=e;return new Vt(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class dn{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 hn=pt(new dn,"Input");class fn{constructor(e){this.target_=e??null}build(e){const n=new dn;e.insertResource(hn,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(tn.Last,on([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const pn=new fn,mn=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},"UICameraInfo");var gn;function yn(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"}(gn||(gn={}));let _n=null,wn=null,xn=1;const bn=new Map;function vn(e){_n=e,wn=e.getResourceManager(),kn()}function Sn(){0!==Cn&&_n&&(_n._free(Cn),Cn=0),bn.clear(),xn=1,Tn=!1,An.clear(),Rn=null,wn=null,_n=null}function Mn(){if(!wn)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return wn}const Pn={createShader:(e,t)=>Mn().createShader(e,t),releaseShader(e){e>0&&Mn().releaseShader(e)},create(e){const t=xn++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??gn.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 bn.set(t,n),t},get:e=>bn.get(e),setUniform(e,t,n){const s=bn.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,_n?.invalidateMaterialCache(e))},getUniform(e,t){const n=bn.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=bn.get(e);n&&(n.blendMode=t,_n?.invalidateMaterialCache(e))},getBlendMode(e){const t=bn.get(e);return t?.blendMode??gn.Normal},setDepthTest(e,t){const n=bn.get(e);n&&(n.depthTest=t,_n?.invalidateMaterialCache(e))},getShader(e){const t=bn.get(e);return t?.shader??0},release(e){bn.delete(e),_n?.invalidateMaterialCache(e)},isValid:e=>bn.has(e),releaseAll(){bn.clear(),_n?.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??gn.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=bn.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=xn++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return bn.set(n,s),n},toAssetData(e,t){const n=bn.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=bn.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Tn=!1,Cn=0;const En=16384,An=new Map;let Rn=null;function In(e){const t=(0===Cn&&_n&&(Cn=_n._malloc(En)),Cn);if(0===t||!_n)return{ptr:0,count:0};let n=0,s=0;const i=_n.HEAPU8,o=_n.HEAPU32,r=_n.HEAPF32;for(const[a,l]of e){if(yn(l))continue;let e=An.get(a);e||(Rn||(Rn=new TextEncoder),e=Rn.encode(a),An.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(n+(4+u+4+16)>En){console.warn(`[ESEngine] Material uniform buffer full (${n}/${En} bytes), skipping remaining uniforms`);break}o[t+n>>2]=c,n+=4,i.set(e,t+n),n+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)r[t+n>>2]=h[e],n+=4;s++}return{ptr:t,count:s}}function kn(){if(!_n||Tn)return;_n.materialDataProvider=(e,t,n,s,i)=>{const o=bn.get(e);if(!o)return _n.HEAPU32[t>>2]=0,_n.HEAPU32[n>>2]=0,_n.HEAPU32[s>>2]=0,void(_n.HEAPU32[i>>2]=0);_n.HEAPU32[t>>2]=o.shader,_n.HEAPU32[n>>2]=o.blendMode;const{ptr:r,count:a}=In(o.uniforms);_n.HEAPU32[s>>2]=r,_n.HEAPU32[i>>2]=a},Tn=!0}const Fn={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 Bn{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 zn{constructor(e,t=""){this.cache_=new Bn,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&&(Pn.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Pn.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:Pn.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 Un(e){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function Wn(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 $n=new Map;function Dn(e){$n.set(e.name,e)}function Ln(e){$n.delete(e)}function On(e){return $n.get(e)}function Hn(){$n.clear()}const jn=Ae("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function Vn(e,t){const n=e.getEntitiesWithComponents([jn]);for(const s of n){const n=e.get(s,jn);if(!n.enabled||!n.playing||!n.clip)continue;const i=$n.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,Ne)){const t=i.frames[n.currentFrame],o=e.get(s,Ne);o.texture=t.texture,t.uvOffset&&(o.uvOffset=t.uvOffset,o.uvScale=t.uvScale),e.insert(s,Ne,o)}a&&e.insert(s,jn,n)}}class Xn{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 async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const n=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,n)}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}}}}Xn.mixer_=null,Xn.bufferCache_=new Map,Xn.bgmHandle_=null,Xn.bgmVolume_=1,Xn.fadeAnimId_=0,Xn.disposed_=!1;const Nn=new Map,Yn=new Map;function qn(e,t,n){Nn.set(e,{width:t,height:n})}function Gn(e){return Nn.get(e)}function Kn(){Nn.clear()}function Jn(e,t){Yn.set(e,t)}function Qn(e){return Yn.get(e)}function Zn(){Yn.clear()}let es=null;function ts(e){es=e}function ns(){es=null}const ss={initLayer(e,t,n,s,i){es?.tilemap_initLayer(e,t,n,s,i)},destroyLayer(e){es?.tilemap_destroyLayer(e)},setTile(e,t,n,s){es?.tilemap_setTile(e,t,n,s)},getTile:(e,t,n)=>es?es.tilemap_getTile(e,t,n):0,fillRect(e,t,n,s,i,o){es?.tilemap_fillRect(e,t,n,s,i,o)},setTiles(e,t){if(!es)return;const n=t.byteLength,s=es._malloc(n);new Uint16Array(es.HEAPU8.buffer,s,t.length).set(t),es.tilemap_setTiles(e,s,t.length),es._free(s)},hasLayer:e=>!!es&&es.tilemap_hasLayer(e),submitLayer(e,t,n,s,i,o,r,a,l,c,u,d,h,f,p,m,g,y,_,w){es?.tilemap_submitLayer(e,t,n,s,i,o,r,a,l,c,u,d,h,f,p,m,g,y,_,w)}},is=Ae("Tilemap",{source:""}),os=Ae("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[],tint:{r:1,g:1,b:1,a:1},opacity:1,visible:!0,parallaxFactor:{x:1,y:1}});function rs(e){if(0===e)return{r:1,g:1,b:1,a:1};const t=(e>>>24&255)/255;return{r:(e>>>16&255)/255,g:(e>>>8&255)/255,b:(255&e)/255,a:0===t?1:t}}function as(e){if(!e)return{r:1,g:1,b:1,a:1};const t=e.startsWith("#")?e.slice(1):e;if(8===t.length){const e=parseInt(t.slice(0,2),16)/255;return{r:parseInt(t.slice(2,4),16)/255,g:parseInt(t.slice(4,6),16)/255,b:parseInt(t.slice(6,8),16)/255,a:e}}if(6===t.length){return{r:parseInt(t.slice(0,2),16)/255,g:parseInt(t.slice(2,4),16)/255,b:parseInt(t.slice(4,6),16)/255,a:1}}return{r:1,g:1,b:1,a:1}}function ls(e,t){if(0===e)return 0;let n=0;2147483648&e&&(n|=8192),1073741824&e&&(n|=16384),536870912&e&&(n|=32768);return(536870911&e)-t+1|n}function cs(e){const t=e.width,n=e.height,s=e.tilewidth??0,i=e.tileheight??0;if(!(t&&n&&s&&i))return null;const o=e.tilesets,r=[],a=[];if(o)for(const e of o){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??s,tileHeight:e.tileheight??i,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const s=e.width??t,i=e.height??n,o=!1!==e.visible,r=e.data,l=new Uint16Array(s*i);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=ls(r[t],e)}const u="number"==typeof e.opacity?e.opacity:1,d=as(e.tintcolor),h="number"==typeof e.parallaxx?e.parallaxx:1,f="number"==typeof e.parallaxy?e.parallaxy:1;c.push({name:e.name??"",width:s,height:i,visible:o,tiles:l,opacity:u,tintColor:d,parallaxX:h,parallaxY:f})}const u=[],d=[];if(l)for(const e of l){if("objectgroup"!==e.type)continue;const t=e.objects;if(!t)continue;const n=[];for(const e of t){const t=new Map,s=e.properties;if(s)for(const e of s)t.set(e.name,e.value);let i="rect",o=null;if(e.ellipse)i="ellipse";else if(e.point)i="point";else if(e.polygon){i="polygon";const t=e.polygon;o=[];for(const e of t)o.push(e.x,e.y)}else if(e.polyline){i="polygon";const t=e.polyline;o=[];for(const e of t)o.push(e.x,e.y)}n.push({shape:i,x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0,rotation:e.rotation??0,vertices:o,properties:t})}u.push({name:e.name??"",objects:n})}if(o)for(const e of o){const t=e.firstgid??1,n=e.tiles;if(n)for(const e of n){const n=e.properties;if(n)for(const s of n)"collision"===s.name&&!0===s.value&&d.push(e.id+t)}}return{width:t,height:n,tileWidth:s,tileHeight:i,layers:c,tilesets:r,objectGroups:u,collisionTileIds:d}}function us(e,t){const n=e.lastIndexOf("/"),s=((n>=0?e.substring(0,n+1):"")+t).split("/"),i=[];for(const e of s)".."===e?i.pop():"."!==e&&""!==e&&i.push(e);return i.join("/")}async function ds(e,t){const n=es;if(!n)return null;const s=new TextEncoder,i=s.encode(e),o=n._malloc(i.byteLength);n.HEAPU8.set(i,o);const r=n.tiled_loadMap(o,i.byteLength);if(n._free(o),0===r)return null;try{const e=n.tiled_getExternalTilesetCount(r);for(let i=0;i<e;i++){const e=n.tiled_getExternalTilesetSource(r,i);if(!t)return n.tiled_freeMap(r),null;const o=await t(e),a=s.encode(o),l=n._malloc(a.byteLength);n.HEAPU8.set(a,l);const c=n.tiled_loadExternalTileset(r,i,l,a.byteLength);if(n._free(l),!c)return n.tiled_freeMap(r),null}if(!n.tiled_finalize(r))return n.tiled_freeMap(r),null;const i={width:n.tiled_getMapWidth(r),height:n.tiled_getMapHeight(r),tileWidth:n.tiled_getMapTileWidth(r),tileHeight:n.tiled_getMapTileHeight(r),layers:[],tilesets:[],objectGroups:[],collisionTileIds:[]},o=n.tiled_getLayerCount(r);for(let e=0;e<o;e++){const t=n.tiled_getLayerWidth(r,e),s=n.tiled_getLayerHeight(r,e),o=t*s,a=2*o,l=n._malloc(a);n.tiled_getLayerTiles(r,e,l,o);const c=new Uint16Array(o);c.set(new Uint16Array(n.HEAPU8.buffer,l,o)),n._free(l),i.layers.push({name:n.tiled_getLayerName(r,e),width:t,height:s,visible:n.tiled_getLayerVisible(r,e),tiles:c,opacity:n.tiled_getLayerOpacity(r,e),tintColor:n.tiled_getLayerTintColor?rs(n.tiled_getLayerTintColor(r,e)):{r:1,g:1,b:1,a:1},parallaxX:n.tiled_getLayerParallaxX(r,e),parallaxY:n.tiled_getLayerParallaxY(r,e)})}const a=n.tiled_getTilesetCount(r);for(let e=0;e<a;e++)i.tilesets.push({name:n.tiled_getTilesetName(r,e),image:n.tiled_getTilesetImage(r,e),tileWidth:n.tiled_getTilesetTileWidth(r,e),tileHeight:n.tiled_getTilesetTileHeight(r,e),columns:n.tiled_getTilesetColumns(r,e),tileCount:n.tiled_getTilesetTileCount(r,e)});return n.tiled_freeMap(r),i}catch{return n.tiled_freeMap(r),null}}const hs=Math.PI/180;function fs(e,t,n,s,i,o){const r=function(e,t,n,s){const i=new Uint8Array(t*n),o=[],r=(o,r)=>{if(o>=t||r>=n)return!1;const a=r*t+o;if(i[a])return!1;const l=8191&e[a];return 0!==l&&s.has(l)};for(let e=0;e<n;e++)for(let s=0;s<t;s++){if(!r(s,e))continue;let a=1;for(;r(s+a,e);)a++;let l=1,c=!0;for(;c;){const t=e+l;if(t>=n)break;for(let e=0;e<a;e++)if(!r(s+e,t)){c=!1;break}c&&l++}for(let n=0;n<l;n++)for(let o=0;o<a;o++)i[(e+n)*t+(s+o)]=1;o.push({col:s,row:e,width:a,height:l})}return o}(t.tiles,t.width,t.height,s),a=[],l=n.tileWidth,c=n.tileHeight,u=n.height*c;for(const t of r){const n=t.width*l,s=t.height*c,r=i+t.col*l+.5*n,d=o+(u-t.row*c)-.5*s,h=e.spawn();e.insert(h,je,{position:{x:r,y:d,z:0}}),e.insert(h,lt,{bodyType:ht.Static}),e.insert(h,ct,{halfExtents:{x:.5*n,y:.5*s}}),a.push(h)}return a}function ps(e,t,n,s={}){const i=[],o=t.tilesets[0];let r=0;for(const s of t.layers){if(!s.visible)continue;const a=e.spawn();e.insert(a,je,{});const l=o?n.get(o.image)??0:0,c=o?.columns??1;e.insert(a,os,{width:s.width,height:s.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:r,tiles:Array.from(s.tiles),tint:{...s.tintColor},opacity:s.opacity,visible:s.visible,parallaxFactor:{x:s.parallaxX,y:s.parallaxY}}),i.push(a),r++}if(!1!==s.generateObjectCollision&&t.objectGroups.length>0){const n=function(e,t,n,s){const i=[],o=t.height*t.tileHeight;for(const r of t.objectGroups)for(const t of r.objects){if("point"===t.shape)continue;const r=e.spawn(),a=t.x,l=t.y,c=n+a+.5*t.width,u=s+(o-l)-.5*t.height,d=-t.rotation*hs;if(e.insert(r,je,{position:{x:c,y:u,z:0}}),e.insert(r,lt,{bodyType:ht.Static}),"ellipse"===t.shape){const n=.5*Math.max(t.width,t.height);e.insert(r,ut,{radius:n})}else if("polygon"===t.shape&&t.vertices){let n=1/0,s=1/0,i=-1/0,o=-1/0;for(let e=0;e<t.vertices.length;e+=2){const r=t.vertices[e],a=t.vertices[e+1];r<n&&(n=r),r>i&&(i=r),a<s&&(s=a),a>o&&(o=a)}const a=i-n,l=o-s,c=.5*(n+i),u=.5*(s+o);e.insert(r,ct,{halfExtents:{x:.5*a,y:.5*l},offset:{x:c,y:-u}})}else e.insert(r,ct,{halfExtents:{x:.5*t.width,y:.5*t.height}});if(0!==d){const t=.5*d;e.insert(r,je,{position:{x:c,y:u,z:0},rotation:{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}})}i.push(r)}return i}(e,t,0,0);i.push(...n)}const a=new Set(s.collisionTileIds??t.collisionTileIds);if(a.size>0)for(const n of t.layers){if(!n.visible)continue;const s=fs(e,n,t,a,0,0);i.push(...s)}return i}const ms=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"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}]]);function gs(e,t){ms.set(e,t)}function ys(e){const t=ms.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 _s(e){return ms.get(e)?.fields??[]}function ws(e){return ms.get(e)?.spine??null}const xs=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function bs(e,t){xs.set(e,t)}function vs(e){return xs.get(e)}function Ss(e,t){const n=xs.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 Ms(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,it,{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)Ss(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 Ps(e,t){return Ms(e,t)}async function Ts(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 Cs.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=ms.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=[...Cs.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=ms.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=Ms(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 Cs=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),qn(r.handle,r.width,r.height)}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=Un(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);Dn(Wn(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 Xn.preloadAll(s).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=cs(await t.loadJson(e));if(!i)return void console.warn(`Failed to parse tilemap: ${e}`);const o=[];for(const r of i.tilesets){const i=us(e,r.image);let a=0;try{const e=n?`${n}/${i}`:`/${i}`,o=await t.loadTexture(e);a=o.handle,s.set(i,e),qn(o.handle,o.width,o.height)}catch(e){console.warn(`Failed to load tileset texture: ${i}`,e)}o.push({textureHandle:a,columns:r.columns})}Jn(e,{tileWidth:i.tileWidth,tileHeight:i.tileHeight,layers:i.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(i),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=$e(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 As(e,t){const n=e.getEntitiesWithComponents([Ye]);for(const s of n){const n=e.get(s,Ye);n&&(n.aspectRatio=t,e.insert(s,Ye,n))}}function Rs(e,t){const n=e.getEntitiesWithComponents([it]);for(const s of n){const n=e.get(s,it);if(n&&n.value===t)return s}return null}class Is{constructor(e){this.textureCache_=new Bn,this.shaderCache_=new Bn,this.jsonCache_=new Bn,this.textCache_=new Bn,this.binaryCache_=new Bn,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Bn,this.prefabCache_=new Bn,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(he.textCanvasSize,he.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 zn(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(),Pn.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,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),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 ys(e.type)){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}const n=ws(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 Ts(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 Pn.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 Pn.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(W(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 ks=pt(null,"Assets");class Fs{build(e){const t=e.wasmModule;t?e.insertResource(ks,new Is(t)):console.warn("AssetPlugin: No WASM module available")}}const Bs=new Fs;class zs{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 Us(e,t){const n=e.getResource(ks);n&&n.registerEmbeddedAssets(t)}async function Ws(e,t,n){const{entities:s,rootId:i}=await Ds(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 Ts(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 $s=10;async function Ds(e,t,n,s,i,o=0){if(o>$s)throw new Error(`Prefab nesting depth exceeded ${$s}. 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 Ds(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,d={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};Ls(d.components,r),Os(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 Ls(e,t){for(const n of e){const e=vs(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 Os(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 Hs{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 Ws(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const js=pt(null,"Prefabs");class Vs{constructor(){this.name="PrefabsPlugin",this.dependencies=[ks]}build(e){const t=e.getResource(ks);e.insertResource(js,new Hs(e.world,t))}}const Xs=new Vs;let Ns=null,Ys=0,qs=0,Gs=0;const Ks=new Float32Array(256);function Js(e){Ns=e,Ys=Ns._malloc(64),qs=Ns._malloc(64),Gs=Ns._malloc(1024)}function Qs(){Ns&&(Ys&&(Ns._free(Ys),Ys=0),qs&&(Ns._free(qs),qs=0),Gs&&(Ns._free(Gs),Gs=0)),Ns=null}function Zs(){if(!Ns)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Ns}const ei={r:1,g:1,b:1,a:1},ti={begin(e){const t=Zs();try{t.HEAPF32.set(e,Ys/4),t.draw_begin(Ys)}catch(e){Pt(e,"Draw.begin")}},end(){try{Zs().draw_end()}catch(e){Pt(e,"Draw.end")}},line(e,t,n,s=1){try{Zs().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Pt(e,"Draw.line")}},rect(e,t,n,s=!0){try{Zs().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Pt(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{Zs().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Pt(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{Zs().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Pt(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{Zs().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Pt(e,"Draw.circleOutline")}},texture(e,t,n,s=ei){try{Zs().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){Pt(e,"Draw.texture")}},textureRotated(e,t,n,s,i=ei){try{Zs().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){Pt(e,"Draw.textureRotated")}},setLayer(e){Zs().draw_setLayer(e)},setDepth(e){Zs().draw_setDepth(e)},getDrawCallCount:()=>Ns?Ns.draw_getDrawCallCount():0,getPrimitiveCount:()=>Ns?Ns.draw_getPrimitiveCount():0,setBlendMode(e){Zs().draw_setBlendMode(e)},setDepthTest(e){Zs().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=Zs();s.HEAPF32.set(n,qs/4),s.draw_mesh(e,t,qs)}catch(n){Pt(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=Zs(),i=Pn.get(t);if(!i)return;if(ti.setBlendMode(i.blendMode),ti.setDepthTest(i.depthTest),0===i.uniforms.size)return void ti.drawMesh(e,i.shader,n);let o;if(s.HEAPF32.set(n,qs/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,n]of i.uniforms){const s=ii(t);if(!(s<0)){if(yn(n))Ks[o++]=10,Ks[o++]=s,Ks[o++]=n.slot??e++,Ks[o++]=n.textureId;else if("number"==typeof n)Ks[o++]=1,Ks[o++]=s,Ks[o++]=n;else if(Array.isArray(n)){Ks[o++]=n.length,Ks[o++]=s;for(let e=0;e<n.length;e++)Ks[o++]=n[e]}else"w"in n?(Ks[o++]=4,Ks[o++]=s,Ks[o++]=n.x,Ks[o++]=n.y,Ks[o++]=n.z,Ks[o++]=n.w):"z"in n?(Ks[o++]=3,Ks[o++]=s,Ks[o++]=n.x,Ks[o++]=n.y,Ks[o++]=n.z):(Ks[o++]=2,Ks[o++]=s,Ks[o++]=n.x,Ks[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(Ks.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void s.draw_mesh(e,i.shader,qs);s.HEAPF32.set(i.cachedBuffer_.subarray(0,o),Gs/4),s.draw_meshWithUniforms(e,i.shader,qs,Gs,o)}catch(n){Pt(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},ni={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},si=new Set;function ii(e){const t=ni[e];return void 0!==t?t:(si.has(e)||(si.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(ni).join(", ")}`)),-1)}const oi=new Map;function ri(e,t,n){oi.set(e,{fn:t,scene:n??""})}function ai(e){oi.delete(e)}function li(){oi.clear()}var ci;!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"}(ci||(ci={}));let ui=null,di=0,hi=0,fi=0;function pi(e){ui=e,di=ui._malloc(262144),hi=ui._malloc(65536),fi=ui._malloc(256)}function mi(){ui&&(di&&ui._free(di),hi&&ui._free(hi),fi&&ui._free(fi),di=0,hi=0,fi=0),ui=null}function gi(){if(!ui)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ui}const yi={create(e){const t=gi(),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,di/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,fi,i).set(o),t.geometry_init(n,di,s,fi,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,hi,s).set(e.indices),t.geometry_setIndices16(n,hi,s)}else{new Uint32Array(t.HEAPU8.buffer,hi,s).set(e.indices),t.geometry_setIndices32(n,hi,s)}}return n},updateVertices(e,t,n=0){const s=gi(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,di/4),s.geometry_updateVertices(e,di,i,n)},release(e){e>0&&gi().geometry_release(e)},isValid:e=>!(!ui||e<=0)&&ui.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return yi.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:ci.Float2},{name:"a_texCoord",type:ci.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 yi.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:ci.Float2},{name:"a_texCoord",type:ci.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 yi.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:ci.Float2},{name:"a_texCoord",type:ci.Float2}],indices:new Uint16Array(r)})}};let _i=1;const wi=new Map,xi=new Map;function bi(){return wi}function vi(){return xi}class Si{constructor(){this.passes_=[],this.destroyed_=!1,this.id=_i++,wi.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}setEnabled(e,t){const n=this.passes_.find(t=>t.name===e);return n&&(n.enabled=t),this}setUniform(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.floatUniforms.set(t,n),this}setUniformVec4(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.vec4Uniforms.set(t,{...n}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of xi)t===this&&xi.delete(e);wi.delete(this.id)}}}const Mi="#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";let Pi=null;function Ti(e){Pi=e}function Ci(){for(const e of bi().values())e.destroy();bi().clear(),vi().clear(),Pi&&Ai.isInitialized()&&Ai.shutdown(),Pi=null}function Ei(){if(!Pi)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Pi}const Ai={createStack:()=>new Si,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");vi().set(e,t)},unbind(e){vi().delete(e)},getStack:e=>vi().get(e)??null,init(e,t){try{return Ei().postprocess_init(e,t)}catch(n){return Pt(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ei().postprocess_shutdown()}catch(e){Pt(e,"PostProcess.shutdown")}},resize(e,t){try{Ei().postprocess_resize(e,t)}catch(n){Pt(n,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!Pi)return!1;try{return Pi.postprocess_isInitialized()}catch(e){return Pt(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ei().postprocess_setBypass(e)}catch(e){Pt(e,"PostProcess.setBypass")}},setOutputViewport(e,t,n,s){try{Ei().postprocess_setOutputViewport(e,t,n,s)}catch(e){Pt(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=vi().get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(Ai.isInitialized()||Ai.init(1,1),Ai.setBypass(!1),function(e){const t=Ei();try{t.postprocess_clearPasses()}catch(e){return void Pt(e,"PostProcess._applyForCamera:clearPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addPass(n.name,n.shader)}catch(e){Pt(e,`PostProcess._applyForCamera:addPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setUniformFloat(n.name,e,s)}catch(t){Pt(t,`PostProcess._applyForCamera:setUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){Pt(t,`PostProcess._applyForCamera:setUniformVec4("${n.name}", "${e}")`)}}}(t)):Ai.setBypass(!0)},_resetAfterCamera(){try{Ei().postprocess_clearPasses(),Ei().postprocess_setBypass(!0)}catch(e){Pt(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of vi().keys())e(t)||vi().delete(t)},screenStack:null,setScreenStack(e){Ai.screenStack=e},_beginScreenCapture(){try{Ei().postprocess_beginScreenCapture()}catch(e){Pt(e,"PostProcess._beginScreenCapture")}},_endScreenCapture(){try{Ei().postprocess_endScreenCapture()}catch(e){Pt(e,"PostProcess._endScreenCapture")}},_applyScreenStack(){const e=Ai.screenStack;if(!e||e.isDestroyed||0===e.enabledPassCount)return;const t=Ei();try{t.postprocess_clearScreenPasses()}catch(e){return void Pt(e,"PostProcess._applyScreenStack:clearScreenPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addScreenPass(n.name,n.shader)}catch(e){Pt(e,`PostProcess._applyScreenStack:addScreenPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setScreenUniformFloat(n.name,e,s)}catch(t){Pt(t,`PostProcess._applyScreenStack:setScreenUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setScreenUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){Pt(t,`PostProcess._applyScreenStack:setScreenUniformVec4("${n.name}", "${e}")`)}}},_executeScreenPasses(){try{Ei().postprocess_executeScreenPasses()}catch(e){Pt(e,"PostProcess._executeScreenPasses")}},createBlur:()=>Pn.createShader(Mi,"#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:()=>Pn.createShader(Mi,"#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:()=>Pn.createShader(Mi,"#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"),createBloom:()=>Pn.createShader(Mi,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_threshold;\nuniform float u_intensity;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 texelSize = 1.0 / u_resolution;\n\n vec3 bloom = vec3(0.0);\n float total = 0.0;\n for (float x = -3.0; x <= 3.0; x += 1.0) {\n for (float y = -3.0; y <= 3.0; y += 1.0) {\n vec2 offset = vec2(x, y) * texelSize * u_radius;\n vec4 s = texture(u_texture, v_texCoord + offset);\n float brightness = dot(s.rgb, vec3(0.2126, 0.7152, 0.0722));\n float w = max(brightness - u_threshold, 0.0);\n bloom += s.rgb * w;\n total += w;\n }\n }\n if (total > 0.0) bloom /= total;\n\n fragColor = vec4(color.rgb + bloom * u_intensity, color.a);\n}\n"),createChromaticAberration:()=>Pn.createShader(Mi,"#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")},Ri=new Map;function Ii(e){Ri.set(e.type,e)}function ki(e){return Ri.get(e)}function Fi(){return Array.from(Ri.keys())}function Bi(){return Array.from(Ri.values())}Ii({type:"blur",label:"Blur",factory:()=>Ai.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),Ii({type:"bloom",label:"Bloom",factory:()=>Ai.createBloom(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:2,step:.01,defaultValue:.8},{name:"u_intensity",label:"Intensity",min:0,max:10,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:0,max:20,step:.1,defaultValue:4}]}),Ii({type:"vignette",label:"Vignette",factory:()=>Ai.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:3,step:.01,defaultValue:.8},{name:"u_softness",label:"Softness",min:0,max:2,step:.01,defaultValue:.3}]}),Ii({type:"grayscale",label:"Grayscale",factory:()=>Ai.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),Ii({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>Ai.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const zi=new Map,Ui=new Map;function Wi(e,t){let n=zi.get(e),s=Ui.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(n||(n=Ai.createStack(),zi.set(e,n)),s||(s=new Map,Ui.set(e,s));n.passCount>0;){const e=n.passes;n.removePass(e[e.length-1].name)}for(const e of i){const t=ki(e.type);if(!t)continue;let i=s.get(e.type);void 0===i&&(i=t.factory(),s.set(e.type,i)),n.addPass(e.type,i);for(const s of t.uniforms){const t=e.uniforms[s.name]??s.defaultValue;n.setUniform(e.type,s.name,t)}}Ai.bind(e,n)}else if(n&&(Ai.unbind(e),n.destroy(),zi.delete(e)),s){for(const e of s.values())Pn.releaseShader(e);Ui.delete(e)}}function $i(e){const t=zi.get(e);t&&(Ai.unbind(e),t.destroy(),zi.delete(e));const n=Ui.get(e);if(n){for(const e of n.values())Pn.releaseShader(e);Ui.delete(e)}}function Di(){for(const e of zi.keys())$i(e)}const Li=pt({enabled:!0},"PostProcessVolumeConfig"),Oi=new Map,Hi=new Map;function ji(e){const t=Hi.get(e);if(void 0!==t)return t;const n=ki(e);if(!n)return null;const s=n.factory();return Hi.set(e,s),s}function Vi(e,t){if(0===t.size){const t=Oi.get(e);return void(t&&(Ai.unbind(e),t.destroy(),Oi.delete(e)))}let n=Oi.get(e);for(n||(n=Ai.createStack(),Oi.set(e,n));n.passCount>0;){const e=n.passes;n.removePass(e[e.length-1].name)}for(const[e,s]of t){if(!s.enabled)continue;const t=ji(e);if(null!==t){n.addPass(e,t);for(const[t,i]of s.uniforms)n.setUniform(e,t,i)}}n.enabledPassCount>0?Ai.bind(e,n):Ai.unbind(e)}const Xi=on([Ot(rt,je)],e=>{const t=[];for(const[n,s,i]of e)t.push({data:s,tx:{x:i.position.x,y:i.position.y}});if(0===t.length)return;const n=[];for(const{data:e,tx:s}of t)e.isGlobal&&n.push({data:e,factor:1});if(n.length>0){const e=function(e){const t=new Map,n=[...e].sort((e,t)=>e.data.priority-t.data.priority);for(const{data:e,factor:s}of n)if(!(s<=0))for(const n of e.effects){if(!n.enabled)continue;const e=t.get(n.type);if(e)for(const[t,i]of Object.entries(n.uniforms)){const n=e.uniforms.get(t)??0;e.uniforms.set(t,n+(i-n)*s)}else{const e=new Map;for(const[t,i]of Object.entries(n.uniforms))e.set(t,i*s);t.set(n.type,{enabled:!0,uniforms:e})}}return t}(n);for(const[t]of Oi)Vi(t,e)}},{name:"PostProcessVolumeSystem"});class Ni{constructor(){this.name="PostProcessPlugin"}build(e){e.insertResource(Li,{enabled:!0}),e.addSystemToSchedule(tn.PostUpdate,Xi)}cleanup(){Di(),function(){for(const[e,t]of Oi)Ai.unbind(e),t.destroy();Oi.clear();for(const e of Hi.values())Pn.releaseShader(e);Hi.clear()}(),Ai.setScreenStack(null)}}const Yi=new Ni;var qi;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(qi||(qi={}));let Gi=null,Ki=0;function Ji(e){Gi=e,Ki=Gi._malloc(64)}function Qi(){Gi&&Ki&&(Gi._free(Ki),Ki=0),Gi=null}const Zi={init(e,t){Gi?.renderer_init(e,t)},resize(e,t){Gi?.renderer_resize(e,t)},begin(e,t){if(Gi&&Ki)try{Gi.HEAPF32.set(e,Ki/4),Gi.renderer_begin(Ki,t??0)}catch(e){Pt(e,"Renderer.begin")}},flush(){try{Gi?.renderer_flush()}catch(e){Pt(e,"Renderer.flush")}},end(){try{Gi?.renderer_end()}catch(e){Pt(e,"Renderer.end")}},submitSprites(e){if(Gi)try{Gi.renderer_submitSprites(e._cpp)}catch(e){Pt(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Gi)try{Gi.renderer_submitBitmapText(e._cpp)}catch(e){Pt(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Gi)try{Gi.renderer_submitSpine?.(e._cpp)}catch(e){Pt(e,"Renderer.submitSpine")}},submitParticles(e){if(Gi)try{Gi.renderer_submitParticles?.(e._cpp)}catch(e){Pt(e,"Renderer.submitParticles")}},setStage(e){Gi?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Gi?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Gi?.renderer_releaseTarget(e)},getTargetTexture:e=>Gi?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Gi?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Gi?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Gi?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){Gi?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){Gi?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Gi?Gi.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Gi?{drawCalls:Gi.renderer_getDrawCalls(),triangles:Gi.renderer_getTriangles(),sprites:Gi.renderer_getSprites(),text:Gi.renderer_getText(),spine:Gi.renderer_getSpine?.()??0,meshes:Gi.renderer_getMeshes(),culled:Gi.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let eo=null;function to(e){eo=e}function no(){eo=null}const so={enable(){eo?.gl_enableErrorCheck(!0)},disable(){eo?.gl_enableErrorCheck(!1)},check:e=>eo?.gl_checkErrors(e)??0,diagnose(){eo?.renderer_diagnose()}};class io{constructor(){this.spineRenderer_=null,this.tilemapRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}setTilemapRenderer(e){this.tilemapRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}beginScreenCapture(){Ai.screenStack&&Ai.screenStack.enabledPassCount>0&&(Ai.isInitialized()||Ai.init(1,1),Ai._applyScreenStack(),Ai._beginScreenCapture())}endScreenCapture(){Ai.screenStack&&Ai.screenStack.enabledPassCount>0&&(Ai._endScreenCapture(),Ai._executeScreenPasses())}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:o}=e;s===this.lastWidth_&&i===this.lastHeight_||(Zi.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),Zi.setViewport(0,0,s,i),Zi.clearBuffers(3),Zi.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),this.tilemapRenderer_&&this.tilemapRenderer_(),Zi.submitSprites(t),Zi.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Zi.submitSpine(t),Zi.submitParticles(t),Zi.flush(),this.executeDrawCallbacks(n,o),Zi.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==Ai.getStack(r);a&&(Ai._applyForCamera(r),Ai.resize(s.w,s.h),Ai.setOutputViewport(s.x,s.y,s.w,s.h)),Zi.setViewport(s.x,s.y,s.w,s.h),Zi.setScissor(s.x,s.y,s.w,s.h,!0),Zi.clearBuffers(i),Zi.setScissor(0,0,0,0,!1),Zi.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),this.tilemapRenderer_&&this.tilemapRenderer_(),Zi.submitSprites(t),Zi.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Zi.submitSpine(t),Zi.submitParticles(t),Zi.flush(),this.executeDrawCallbacks(n,o),Zi.end(),a&&Ai._resetAfterCamera()}executeDrawCallbacks(e,t){const n=oi;if(n.size>0){ti.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)}ti.end();for(const e of s)ai(e)}}}const oo="__scene_transition_overlay__";class ro{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class ao{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,ot,{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),ri(e,t,this.instance_.config.name)}bindPostProcess(e,t){Ai.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){Ai.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,ot)){const n=this.app_.world.get(e,ot);n.persistent=t,this.app_.world.insert(e,ot,n)}}}class lo{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}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())ai(t);for(const t of e.postProcessBindings.keys())Ai.unbind(t)}this.transition_&&(ai(oo),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}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??he.sceneTransitionDuration,i=t.color??{...he.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},ri(oo,()=>{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;ti.setLayer(9999),ti.setDepth(9999),ti.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,ai(oo),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,ai(oo),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 ro(t);this.scenes_.set(e,n);const s=new ao(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(ks)?this.app_.getResource(ks):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 ro(t);this.scenes_.set(e,n);const s=new ao(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(ks)?this.app_.getResource(ks):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,ot)){if(this.app_.world.get(e,ot).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())ai(e);n.drawCallbacks.clear();for(const e of n.postProcessBindings.keys())Ai.unbind(e);n.postProcessBindings.clear(),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(ks)&&(i.assetServer=this.app_.getResource(ks));const o=await Ts(this.app_.world,s,i);e.loadedAssets=n;for(const n of o.values())e.entities.add(n),this.app_.world.insert(n,ot,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=uo(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(ks)?this.app_.getResource(ks):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)Pn.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,Ne)){const t=n.get(e,Ne);s.sprite=t.color.a,t.color.a=0,n.insert(e,Ne,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,Ne)){const t=n.get(e,Ne);t.color.a=s.sprite,n.insert(e,Ne,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.postProcessBindings.values())n.setAllPassesEnabled(t)}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 co=pt(null,"SceneManager");function uo(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(co).getSceneStatus(t)&&n._fn(...s)}}}const ho=on([gt(co),mt(wt)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),fo={name:"SceneManager",build(e){const t=new lo(e);e.insertResource(co,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(co),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(tn.Startup,n),e.addSystemToSchedule(tn.Last,ho)}};class po{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 Kt,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 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(tn.Last);else{this.runSchedule(tn.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(tn.FixedPreUpdate),this.runSchedule(tn.FixedUpdate),this.runSchedule(tn.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(tn.PreUpdate),this.runSchedule(tn.Update),this.runSchedule(tn.PostUpdate),this.runSchedule(tn.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new kt,this.resources_=new _t;for(const e of Object.values(tn))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new po}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(tn.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(tn.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 Mt(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(co).register(e),this}setInitialScene(e){return this.getResource(co).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new un(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(wt)||this.resources_.insert(wt,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(tn.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(tn.Last);else{this.runSchedule(tn.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(tn.FixedPreUpdate),this.runSchedule(tn.FixedUpdate),this.runSchedule(tn.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(tn.PreUpdate),this.runSchedule(tn.Update),this.runSchedule(tn.PostUpdate),this.runSchedule(tn.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new un(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(wt,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(tn.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1,li();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=[no,Qi,Ci,mi,Sn,Qs];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(tn[e],performance.now()-s)}updateTime(e){const t=this.resources_.get(wt);t.delta=e,t.elapsed+=e,t.frameCount++}}function mo(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 go=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function yo(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 _o=[];function wo(e){if(e<_o.length)return _o[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 _o.push(t),t}function xo(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,ot);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,d=0;if(i.projectionType===Le.Orthographic){if(d=i.orthoSize,l){d=yo(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=d*r,a=vo(-u,u,-d,d,-i.farPlane,i.farPlane)}else a=Mo(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const h=To(o.position.x,o.position.y,o.position.z),f=wo(c.length);f.entity=e,f.viewProjection.set(Eo(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 bo=new Float32Array(16);function vo(e,t,n,s,i,o){const r=bo;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 So=new Float32Array(16);function Mo(e,t,n,s){const i=So;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 Po=new Float32Array(16);function To(e,t,n){const s=Po;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 Co=new Float32Array(16);function Eo(e,t){const n=Co;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 Ao={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function Ro(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,d=o.bottom+e.y*l,h=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=d+n.y-i.y*r.y,g=p+i.y):(p=d+n.y,g=h+s.y);const y=Math.max(0,m-f),_=Math.max(0,g-p);return{originX:f+r.x*y,originY:p+r.y*_,width:y,height:_,rect:{left:f,bottom:p,right:m,top:g}}}const Io=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 ko=null,Fo=null;function Bo(e,t){e.has(t,Ne)||e.insert(t,Ne,{texture:ye,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 zo(e,t){switch(e){case Ao.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Ao.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Ao.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 Uo(e,t){switch(e){case Ao.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case Ao.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case Ao.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 Wo(e,t,n,s){switch(e){case Ao.BottomToTop:case Ao.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function $o(e,t,n,s){if(!e.has(t,Io))return;const i=e.get(t,Io),o=zo(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,Io,i)}function Do(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Lo(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Oo(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(Lo(r.charCodeAt(0))&&s.length>0&&Lo(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!Lo(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 Ho(e){let t=1;for(;t<e;)t*=2;return t}function jo(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 Vo(e,t){if(ko&&Fo){const e=ko.getUIRectComputedWidth(Fo,t);if(e>0)return e}return e.size.x}function Xo(e,t){if(ko&&Fo){const e=ko.getUIRectComputedHeight(Fo,t);if(e>0)return e}return e.size.y}function No(e,t,n,s,i,o){if(!e.has(t,Ne))return;const r=e.get(t,Ne);let a,l;switch(n){case Ao.BottomToTop:case Ao.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,Ne,r))}function Yo(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 qo(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function Go(e,t,n,s,i){if(!e.has(t,Io))return;const o=e.get(t,Io),r=Ro(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,Ne)){const n=e.get(t,Ne);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,Ne,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 Ko(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 Jo=.1,Qo=30,Zo={r:.3,g:.5,b:.8,a:1},er={Left:0,Center:1,Right:2},tr={Top:0,Middle:1,Bottom:2},nr={Visible:0,Clip:1,Ellipsis:2},sr=Ae("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:er.Left,verticalAlign:tr.Top,wordWrap:!0,overflow:nr.Visible,lineHeight:1.2});class ir{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=d(he.textCanvasSize,he.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,Ho(this.frameMaxW_)),e.height=Math.max(e.height,Ho(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Ho(this.frameMaxW_),e.height=Ho(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=Oo(n,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===nr.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),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,Ho(f)),s.height=Math.max(s.height,Ho(p)));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;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===nr.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 tr.Top:x=u;break;case tr.Middle:x=u+(p-2*u-w)/2;break;case tr.Bottom:x=p-w-u;break;default:x=u}x<0&&(x=0)}else x=u;let b=x;for(const t of l){let s;switch(e.align){case er.Left:s=u;break;case er.Center:s=f/2;break;case er.Right:s=f-u;break;default:s=u}n.fillText(t,s,b),b+=c}i&&e.overflow===nr.Clip&&n.restore();const v=n.getImageData(0,0,f,p),S=new Uint8Array(v.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 er.Left:return"left";case er.Center:return"center";case er.Right:return"right"}}}const or=Ko({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?Vo(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Xo(e.uiRect,e.entity):0});class rr{build(e){We("Text",sr);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new ir(t),s=e.world,i=new Map;e.addSystemToSchedule(tn.PreUpdate,on([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,sr));for(const e of i.keys())if(!s.valid(e)||!s.has(e,sr)){if(s.valid(e)&&s.has(e,Ne)){const t=s.get(e,Ne);s.insert(e,Ne,{texture:ye,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([sr]);for(const t of e){const e=s.get(t,sr),o=s.has(t,Io)?s.get(t,Io):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!or.changed(a,r)){if(s.has(t,Ne)&&s.get(t,Ne).texture!==ye)continue}Bo(s,t);const l=o?{size:{x:Vo(o,t),y:Xo(o,t)}}:null,c=n.renderForEntity(t,e,l),u=s.get(t,Ne);s.insert(t,Ne,{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,or.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const ar=new rr,lr=0,cr=1,ur=De("UIMask",{enabled:!0,mode:lr});function dr(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 hr(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],d=e[8],h=e[9],f=e[10],p=e[11],m=e[12],g=e[13],y=e[14],_=e[15],w=s*l-i*a,x=s*c-o*a,b=s*u-r*a,v=i*c-o*l,S=i*u-r*l,M=o*u-r*c,P=d*g-h*m,T=d*y-f*m,C=d*_-p*m,E=h*y-f*g,A=h*_-p*g,R=f*_-p*y;let I=w*R-x*A+b*E+v*C-S*T+M*P;return 0===I||(I=1/I,n[0]=(l*R-c*A+u*E)*I,n[1]=(o*A-i*R-r*E)*I,n[2]=(g*M-y*S+_*v)*I,n[3]=(f*S-h*M-p*v)*I,n[4]=(c*C-a*R-u*T)*I,n[5]=(s*R-o*C+r*T)*I,n[6]=(y*b-m*M-_*x)*I,n[7]=(d*M-f*b+p*x)*I,n[8]=(a*A-l*C+u*P)*I,n[9]=(i*C-s*A-r*P)*I,n[10]=(m*S-g*b+_*w)*I,n[11]=(h*b-d*S-p*w)*I,n[12]=(l*T-a*E-c*P)*I,n[13]=(s*E-i*T+o*P)*I,n[14]=(g*x-m*v-y*w)*I,n[15]=(d*v-h*x+f*w)*I),n}function fr(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],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:u/d}}function pr(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 mr(e,t){return 2*Math.atan2(e,t)}function gr(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 yr(e,t,n,s,i,o,r,a,l,c){const u=mr(l,c),d=Math.sin(-u),h=Math.cos(-u),f=e-n,p=t-s,m=f*h-p*d+n,g=f*d+p*h+s;return m>=n-i*r&&m<=n+i*(1-r)&&g>=s-o*a&&g<=s+o*(1-a)}function _r(e,t,n,s,i,o,r){if(!e.has(t,Io)||!e.has(t,je))return null;const a=e.get(t,Io),l=e.get(t,je),c=Vo(a,t)*l.worldScale.x,u=Xo(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),y=-u*p,_=u*(1-p),w=mr(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),b=Math.sin(w),v=[[d+m*x-y*b,h+m*b+y*x],[d+g*x-y*b,h+g*b+y*x],[d+g*x-_*b,h+g*b+_*x],[d+m*x-_*b,h+m*b+_*x]];let S=1/0,M=1/0,P=-1/0,T=-1/0;for(const[e,t]of v){const[a,l]=gr(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 wr(e,t){return(n,s,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([ur]);if(0===l.length)return;const c=[],u=[],d=new Set,h=new Set;for(const e of l){const n=t.get(e,ur);n.enabled&&(d.add(e),n.mode===cr?(u.push(e),h.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;Yo(t,e,e=>{if(i.has(e)){if(t.get(e,ur).mode===lr)return n=!1,!0}return!1}),n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(i.has(n)){if(t.get(n,ur).mode===lr){const e=_r(t,n,o,r,a,l,c);e&&(s=dr(u,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=_r(t,e,o,r,a,l,c);n&&d(e,n)}}(e,t,n,c,d,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;Yo(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,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class xr{build(e){if(We("UIMask",ur),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(wr(e.wasmModule,e.world))}}const br=new xr,vr=De("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),Sr=De("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Mr={Normal:0,Hovered:1,Pressed:2,Disabled:3},Pr=Ae("Button",{state:Mr.Normal,transition:null});class Tr{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 Cr=pt(new Tr,"UIEvents");class Er{build(e){We("UIRect",Io);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){ko=e,Fo=t}(n,s);e.addSystemToSchedule(tn.PreUpdate,on([mt(mn)],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(tn.PostUpdate,on([mt(mn)],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(tn.PostUpdate,on([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const Ar=new Er;let Rr=!1,Ir=!1;function kr(e){Rr=e}function Fr(){return Rr}function Br(){return!Rr}function zr(e){Ir=e}function Ur(){return Ir}const Wr=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&&(hr(t,e),n=!1),e)}}();function $r(e,t,n,s){t.emit(n,s,n),Yo(e,n,i=>{if(!e.has(i,vr))return!1;const o=e.get(i,vr);return o.enabled&&t.emit(i,s,n),o.blockRaycast})}class Dr{build(e){We("Interactable",vr),We("Button",Pr);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new Tr;e.insertResource(Cr,i);let o=null,r=null;e.addSystemToSchedule(tn.PreUpdate,on([mt(hn),mt(mn)],(e,a)=>{if(i.drain(),Fr()&&!Ur())return;const l=t.getEntitiesWithComponents([Sr]);for(const e of l){const n=t.get(e,Sr);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,Sr,n))}if(!a.valid)return;const c=f(),u=e.mouseX*c,d=a.screenH-e.mouseY*c;Wr.update(a.viewProjection);const h=fr(u,d,Wr.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);n.uiHitTest_update(s,h.x,h.y,p,m,g);const y=n.uiHitTest_getHitEntity(),_=4294967295===y?null:y;if(null===o||t.valid(o)||(o=null),o!==_){if(null!==o&&t.valid(o)&&t.has(o,Sr)){const e=t.get(o,Sr);e.hovered=!1,t.insert(o,Sr,e),i.emit(o,"hover_exit")}if(null!==_){qo(t,_,Sr);const e=t.get(_,Sr);e.hovered=!0,t.insert(_,Sr,e),i.emit(_,"hover_enter")}o=_}if(m&&null!==_){const e=t.get(_,Sr);e.pressed=!0,e.justPressed=!0,t.insert(_,Sr,e),r=_,$r(t,i,_,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,Sr)){const e=t.get(r,Sr);e.pressed=!1,e.justReleased=!0,t.insert(r,Sr,e),$r(t,i,r,"release"),r===o&&$r(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(tn.Update,on([],()=>{const e=t.getEntitiesWithComponents([Pr]);for(const n of e){if(qo(t,n,vr,{enabled:!0}),!t.has(n,Sr))continue;const e=t.get(n,Sr),s=t.get(n,Pr),i=t.get(n,vr),o=!a.has(n),r=s.state;if(i.enabled?e.pressed?s.state=Mr.Pressed:e.hovered?s.state=Mr.Hovered:s.state=Mr.Normal:s.state=Mr.Disabled,o&&a.add(n),(o||r!==s.state)&&s.transition&&t.has(n,Ne)){const o=t.get(n,Ne);o.color=Do(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,Ne,o)}}},{name:"ButtonSystem"}))}}const Lr=new Dr,Or=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}),Hr=Ae("Focusable",{tabIndex:0,isFocused:!1});class jr{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 Vr=pt(new jr,"FocusManager");class Xr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(We("TextInput",Or),Fr()&&!Ur())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,i=d(he.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(Vr);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,Or)?s:null}const g=()=>{l||null===m()||b()},y=()=>{l=!0},_=()=>{l=!1,b()},w=t=>{const s=m();if(null===s)return;if("Escape"===t.key)return void v();const i=n.get(s,Or);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(Cr).emit(s,"submit"),void v()}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,Or);s.focused=!1,s.dirty=!0;e.getResource(Vr).blur()}};function b(){const t=m();if(null===t)return;const s=n.get(t,Or);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(Cr).emit(t,"change")}s.cursorPos=p.selectionStart??i.length,s.dirty=!0,S()}function v(){const t=m();if(null!==t){const e=n.get(t,Or);e.focused=!1,e.dirty=!0}e.getResource(Vr).blur(),p.blur()}function S(){c=!0,u=0}p.addEventListener("input",g),p.addEventListener("compositionstart",y),p.addEventListener("compositionend",_),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",g),p.removeEventListener("compositionstart",y),p.removeEventListener("compositionend",_),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,d){(i.width<u||i.height<d)&&(i.width=Ho(Math.max(i.width,u)),i.height=Ho(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),y=l.padding;if(l.multiline){const e=Oo(o,p,u-2*y);let t=y;for(const n of e)o.fillText(n,y,t),t+=g}else{const e=(d-l.fontSize)/2;o.fillText(p,y,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=Oo(o,l.value,u-2*y);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=y+o.measureText(c).width,n=y+r*g,s=g}else t=y+o.measureText(e).width,n=(d-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 _=o.getImageData(0,0,u,d),w=new Uint8Array(_.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 b=s.get(e);void 0!==b&&x.releaseTexture(b);const v=x.createTexture(u,d,r,w.length,1,!0);s.set(e,v);const S=n.get(e,Ne);S.texture=v,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},n.insert(e,Ne,S)}e.addSystemToSchedule(tn.Update,on([mt(Vr)],e=>{const t=n.getEntitiesWithComponents([Or]);for(const e of t)qo(n,e,Hr,{tabIndex:0,isFocused:!1}),qo(n,e,vr,{enabled:!0,blockRaycast:!0});const s=m();if(s!==M){if(null!==M&&n.valid(M)&&n.has(M,Or)){const e=n.get(M,Or);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,Or);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(tn.PreUpdate,on([],()=>{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;n.get(o,Or).dirty=!0}const r=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Or)||(r.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([Or,Io]);for(const e of a){const t=n.get(e,Or);if(!t.dirty)continue;const s=n.get(e,Io),i=Math.ceil(s.size.x),o=Math.ceil(s.size.y);i<=0||o<=0||(Bo(n,e),P(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Nr=new Xr,Yr={Simple:0,Sliced:1,Tiled:2,Filled:3},qr={Horizontal:0,Vertical:1},Gr={Left:0,Right:1,Bottom:2,Top:3},Kr=Ae("Image",{texture:ye,color:{r:1,g:1,b:1,a:1},imageType:Yr.Simple,fillMethod:qr.Horizontal,fillOrigin:Gr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Jr=Ko({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?Vo(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Xo(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class Qr{build(e){We("Image",Kr);const t=e.world,n=new Map;e.addSystemToSchedule(tn.PreUpdate,on([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,Kr)||n.delete(e);const e=t.getEntitiesWithComponents([Kr]);for(const s of e){const e=t.get(s,Kr),i=t.has(s,Io)?t.get(s,Io):null,o={image:e,uiRect:i,entity:s},r=n.get(s);if(r&&!Jr.changed(r,o))continue;Bo(t,s);const a=t.get(s,Ne);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=Vo(i,s),a.size.y=Xo(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Yr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===qr.Horizontal?e.fillOrigin===Gr.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===Gr.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===Yr.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,Ne,a),n.set(s,Jr.take(o))}else a.color.a=0,t.insert(s,Ne,a),n.set(s,Jr.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const Zr=new Qr,ea=Ae("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),ta=Ae("ToggleGroup",{allowSwitchOff:!1});class na{build(e){We("Toggle",ea),We("ToggleGroup",ta);const t=e.world,n=new Set;e.addSystemToSchedule(tn.Update,on([mt(Cr)],e=>{const s=t.getEntitiesWithComponents([ea]);if(!Fr()||Ur()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,ea);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,ea,s)):i.set(s.group,e))}const o=new Map;for(const e of s){const n=t.get(e,ea);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(qo(t,n,vr,{enabled:!0}),!t.has(n,Sr))continue;const s=t.get(n,Sr),i=t.get(n,ea),r=t.get(n,vr);if(s.justPressed&&r.enabled){const s=i.group,r=0!==s&&t.valid(s)&&t.has(s,ta);if(i.isOn&&r){if(!t.get(s,ta).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,ea,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,ea);i.isOn&&(i.isOn=!1,t.insert(s,ea,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,Ne)){const e=t.get(n,Ne);e.color=Do(i.transition,r.enabled,s.pressed,s.hovered),t.insert(n,Ne,e)}}}for(const e of s){const n=t.get(e,ea);if(n.graphicEntity&&t.valid(n.graphicEntity)&&t.has(n.graphicEntity,Ne)){const e=t.get(n.graphicEntity,Ne);e.enabled=n.isOn,t.insert(n.graphicEntity,Ne,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const sa=new na,ia=Ao,oa=Ae("ProgressBar",{value:0,fillEntity:0,direction:Ao.LeftToRight});function ra(e,t,n,s){if(!e.has(t,Io))return;const i=e.get(t,Io),o=n/2,r=s/2,a={left:-o,bottom:-r,right:o,top:r},l=Ro(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,Ne)){const n=e.get(t,Ne);n.size.x===l.width&&n.size.y===l.height||(n.size.x=l.width,n.size.y=l.height,e.insert(t,Ne,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 aa{build(e){We("ProgressBar",oa);const t=e.world;e.addSystemToSchedule(tn.PreUpdate,on([],()=>{const e=t.getEntitiesWithComponents([oa,Io]);for(const n of e){const e=t.get(n,oa);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,Io),i=Math.max(0,Math.min(1,e.value));$o(t,e.fillEntity,e.direction,i);const o=Vo(s,n),r=Xo(s,n);ra(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const la=new aa,ca=Ae("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),ua=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 da{build(e){We("Draggable",ca),We("DragState",ua);const t=e.world,n=e.getResource(Cr);let s=null,i={x:0,y:0},o=null;e.addSystemToSchedule(tn.PreUpdate,on([mt(hn),mt(mn)],(e,r)=>{if(Fr()&&!Ur())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([ca,Sr]);let n=null,o=-1/0,r=-1;for(const s of e){if(!t.get(s,ca).enabled)continue;if(t.get(s,Sr).hovered){let e=0;t.has(s,Ne)&&(e=t.get(s,Ne).layer);const i=jo(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,ua)||t.insert(n,ua);const e=t.get(n,ua),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,ua)){t.get(s,ua).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,ca);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=s,s=null;t.get(o,ua).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,ua))return void(o=null);const s=t.get(o,ua),i=t.get(o,ca),r=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+r,u=s.startWorldPos.y+l;const d=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=d.x,u=d.y;const h=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-h,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=mr(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 ha=new da,fa=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 pa(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 ma(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 ga{build(e){We("ScrollView",fa);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(tn.PostUpdate,on([mt(hn),mt(mn),mt(wt)],(e,i,o)=>{const r=Fr()&&!Ur(),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([fa,Io]);for(const o of l){qo(t,o,ur,{enabled:!0,mode:lr});const l=t.get(o,fa),c=t.get(o,Io);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 d=Vo(c,o),h=Xo(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,Io)){const e=t.get(r,Io);a=Vo(e,r)||e.size.x,l=Xo(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,Ne)){const e=t.get(r,Ne);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<n&&(n=d),h>s&&(s=h),f<i&&(i=f),p>o&&(o=p)}0===f&&(f=s-n),0===p&&(p=o-i)}const m=Math.max(0,f-d),g=Math.max(0,p-h);if(!r&&i.valid){qo(t,o,vr,{enabled:!0,blockRaycast:!0});const n=t.has(o,Sr)?t.get(o,Sr):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=pa(l.scrollX,0,m,d);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=pa(l.scrollY,0,g,h);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*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(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=pa(l.scrollY,0,g,h);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=pa(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=ma(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)<Jo&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Jo?(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=ma(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)<Jo&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Jo?(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,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 ya=new ga,_a=Ao,wa=Ae("Slider",{value:0,minValue:0,maxValue:1,direction:Ao.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function xa(e,t,n,s,i,o){const r=Vo(s,i)*n.worldScale.x,a=Xo(s,i)*n.worldScale.y,l=mr(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),d=e-n.worldPosition.x,h=t-n.worldPosition.y,f=d*u-h*c,p=d*c+h*u,m=-s.pivot.x*r,g=-s.pivot.y*a;switch(o){case Ao.LeftToRight:return r>0?(f-m)/r:0;case Ao.RightToLeft:return r>0?1-(f-m)/r:0;case Ao.BottomToTop:return a>0?(p-g)/a:0;case Ao.TopToBottom:return a>0?1-(p-g)/a:0}}function ba(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case Ao.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case Ao.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case Ao.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case Ao.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class va{build(e){We("Slider",wa);const t=e.world;let n=null;e.addSystemToSchedule(tn.PreUpdate,on([mt(hn),mt(mn),mt(Cr)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const o=t.getEntitiesWithComponents([wa,Io]);for(const r of o){const o=t.get(r,wa),a=t.get(r,Io);if(!Fr()||Ur()){if(t.has(r,je)){qo(t,r,vr,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&qo(t,o.handleEntity,vr,{enabled:!0,blockRaycast:!1});const l=t.get(r,je),c=t.has(r,Sr)?t.get(r,Sr):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Sr)&&(u=t.get(o.handleEntity,Sr).justPressed),u&&(n=r),n===r&&e.isMouseButtonDown(0)){let e=xa(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,wa,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=Vo(a,r),d=Xo(a,r),h={left:-u/2,bottom:-d/2,right:u/2,top:d/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&($o(t,o.fillEntity,o.direction,c),Go(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Io)){const e=t.get(o.handleEntity,Io);ba(e,o.direction,c),t.insert(o.handleEntity,Io,e),Go(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Sa=new va;class Ma{build(e){We("Focusable",Hr);const t=e.world,n=new jr;e.insertResource(Vr,n),e.addSystemToSchedule(tn.Update,on([mt(hn),mt(Cr)],(e,s)=>{if(Fr()&&!Ur())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([Hr]);for(const e of i){if(!t.has(e,Sr))continue;t.get(e,Sr).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,vr)){if(!t.get(n,vr).enabled)continue}const s=t.get(n,Hr);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,Hr)){t.get(i,Hr).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,Hr).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const Pa=new Ma,Ta=Ae("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function Ca(){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 Ea{build(e){We("SafeArea",Ta);const t=e.world;let n=Ca(),s=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=Ca(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=Ca(),s=!0});e.addSystemToSchedule(tn.PreUpdate,on([mt(mn)],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([Ta,Io]);for(const e of u){const s=t.get(e,Ta),i=t.get(e,Io),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,Io,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const Aa=new Ea,Ra=Ae("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Ia=null;function ka(e,t){if(!Ia)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=Ia.get(e);n?n.renderer=t:Ia.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}class Fa{build(e){We("ListView",Ra);const t=e.world,n=new Map;Ia=n,e.addSystemToSchedule(tn.PostUpdate,on([mt(hn)],e=>{const s=Fr()&&!Ur();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([Ra,Io]);for(const o of i){qo(t,o,vr,{enabled:!0,blockRaycast:!0}),qo(t,o,ur,{enabled:!0,mode:lr});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,Ra),a=t.get(o,Io),l=Xo(a,o),c=Vo(a,o);if(!s){const n=t.has(o,Sr)?t.get(o,Sr):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 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,n]of i.itemEntities)(e<d||e>=h)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=d;e<h;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,it,{value:`ListItem_${e}`}),t.insert(n,Io,{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=d,i.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const Ba=new Fa,za=Ae("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class Ua{build(e){We("Dropdown",za);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,Ne)){const n=t.get(e,Ne);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&t.insert(e,Ne,{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,Ne),r=o.size.x,a=o.size.y;s.ddWidth=r;const l=n.options.length*Qo;t.insert(i,Io,{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,Ne,{texture:ye,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)*Qo;t.insert(o,it,{value:`Option_${e}`}),t.insert(o,Io,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Qo},offsetMax:{x:0,y:0},size:{x:r,y:Qo},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,Ne,{texture:ye,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:Qo},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,vr,{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,sr,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:er.Left,verticalAlign:tr.Middle,wordWrap:!1,overflow:nr.Clip,lineHeight:1.2}),t.insert(c,Io,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:Qo},pivot:{x:.5,y:.5}}),t.setParent(c,o),s.textEntities.push(c)}d(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,sr))return;const s=t.get(n,sr);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,sr,{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,vr)&&t.insert(e,vr,{enabled:n,blockRaycast:!0,raycastTarget:!0}),t.has(e,Ne))){const s=t.get(e,Ne);t.insert(e,Ne,{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 d(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s)||!t.has(s,Ne))continue;const i=n===e.highlightIndex?{...Zo}:{r:.95,g:.95,b:.95,a:1};t.insert(s,Ne,{texture:ye,color:i,size:{x:e.ddWidth,y:Qo},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 n of e.optionEntities){if(!t.valid(n)||!t.has(n,Sr))continue;if(t.get(n,Sr).hovered)return!0}return!1}e.addSystemToSchedule(tn.Update,on([mt(hn),mt(Cr)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=Fr()&&!Ur(),p=t.getEntitiesWithComponents([za]);for(const m of p){const p=t.get(m,za);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;qo(t,m,vr,{enabled:!0,blockRaycast:!0});const y=t.has(m,Sr)?t.get(m,Sr):null;if(y?.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,Sr))continue;if(t.get(n,Sr).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,Sr))continue;if(t.get(s,Sr).hovered){n=e;break}}n>=0&&n!==g.highlightIndex&&(g.highlightIndex=n,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)&&(y?.hovered||h(g)||r(m,p,g))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}}const Wa=new Ua,$a=0,Da=0,La=2,Oa=Ae("LayoutGroup",{direction:$a,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Da,reverseOrder:!1});class Ha{build(e){We("LayoutGroup",Oa);const t=e.world;e.addSystemToSchedule(tn.PreUpdate,on([],()=>{const e=t.getEntitiesWithComponents([Oa,Io,Je]);for(const n of e){const e=t.get(n,Oa),s=t.get(n,Io),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,Io)&&t.has(e,je)&&o.push({entity:e,rect:t.get(e,Io)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=Vo(s,n),a=Xo(s,n),l=s.pivot.x,c=s.pivot.y,u=e.padding,d=e.direction===$a;let h=0;for(let n=0;n<o.length;n++){const s=o[n],i=Vo(s.rect,s.entity),f=Xo(s.rect,s.entity),p=s.rect.pivot.x,m=s.rect.pivot.y;let g,y;d?(g=-l*r+u.left+h+p*i,y=e.childAlignment===Da?(1-c)*a-u.top-(1-m)*f:e.childAlignment===La?-c*a+u.bottom+m*f:(.5-c)*a+.5*(u.bottom-u.top)+(m-.5)*f,h+=i,n<o.length-1&&(h+=e.spacing)):(g=e.childAlignment===Da?-l*r+u.left+p*i:e.childAlignment===La?(1-l)*r-u.right-(1-p)*i:(.5-l)*r+.5*(u.left-u.right)+(p-.5)*i,y=(1-c)*a-u.top-h-(1-m)*f,h+=f,n<o.length-1&&(h+=e.spacing));const _=t.get(s.entity,je);_.position.x=g,_.position.y=y,t.insert(s.entity,je,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}}const ja=new Ha;class Va{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(tn.PostUpdate,on([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const Xa=new Va;async function Na(e,t,n){const s=e.getResource(co);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function Ya(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 qa=pt({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),Ga={r:.2,g:.4,b:1,a:.7},Ka={r:.2,g:1,b:.2,a:.7},Ja={r:.2,g:1,b:1,a:.7},Qa={r:1,g:1,b:.2,a:.5},Za={r:1,g:.2,b:.2,a:.8},el={r:1,g:.2,b:.2,a:1},tl=1.5,nl=16;function sl(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function il(e){switch(e){case ht.Static:return Ga;case ht.Kinematic:return Ja;default:return Ka}}function ol(e,t,n,s,i,o){const r=Math.cos(i),a=Math.sin(i),l=[{x:-n,y:-s},{x:n,y:-s},{x:n,y:s},{x:-n,y:s}].map(n=>({x:e+n.x*r-n.y*a,y:t+n.x*a+n.y*r}));for(let e=0;e<4;e++)ti.line(l[e],l[(e+1)%4],o,tl)}function rl(e,t,n,s,i,o){const r=Math.cos(i),a=Math.sin(i),l=(n,s)=>({x:e+n*r-s*a,y:t+n*a+s*r}),c=l(-n,s),u=l(n,s),d=l(-n,-s),h=l(n,-s);ti.line(c,d,o,tl),ti.line(u,h,o,tl);for(let e=0;e<nl;e++){const t=e/nl*Math.PI,i=(e+1)/nl*Math.PI,r=l(-n*Math.cos(t),s+n*Math.sin(t)),a=l(-n*Math.cos(i),s+n*Math.sin(i));ti.line(r,a,o,tl)}for(let e=0;e<nl;e++){const t=Math.PI+e/nl*Math.PI,i=Math.PI+(e+1)/nl*Math.PI,r=l(-n*Math.cos(t),-s+n*Math.sin(t)),a=l(-n*Math.cos(i),-s+n*Math.sin(i));ti.line(r,a,o,tl)}}function al(e,t,n,s){const i=e+.5*n,o=t+.5*s;ti.line({x:e,y:t},{x:i,y:o},Za,tl);const r=Math.sqrt(n*n+s*s);if(r<1)return;const a=Math.PI/6,l=n/r,c=s/r,u=i-6*(l*Math.cos(a)-c*Math.sin(a)),d=o-6*(l*Math.sin(a)+c*Math.cos(a)),h=i-6*(l*Math.cos(a)+c*Math.sin(a)),f=o-6*(-l*Math.sin(a)+c*Math.cos(a));ti.line({x:i,y:o},{x:u,y:d},Za,tl),ti.line({x:i,y:o},{x:h,y:f},Za,tl)}function ll(e,t,n){const s=e.getResource(qa);if(!s||!s.enabled)return;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=e.world.getEntitiesWithComponents([lt,je]);let r=null;s.showVelocity&&e.hasResource(t)&&(r=e.getResource(t));for(const t of o){const n=e.world.get(t,lt);if(!n.enabled)continue;const o=e.world.get(t,je),a=o.worldPosition.x,l=o.worldPosition.y,c=sl(o.worldRotation);if(s.showColliders){if(e.world.has(t,ct)){const s=e.world.get(t,ct),o=s.isSensor?Qa:il(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,d=Math.cos(c),h=Math.sin(c);ol(a+r*d-u*h,l+r*h+u*d,s.halfExtents.x*i,s.halfExtents.y*i,c,o)}if(e.world.has(t,ut)){const s=e.world.get(t,ut),o=s.isSensor?Qa:il(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,d=Math.cos(c),h=Math.sin(c),f=a+r*d-u*h,p=l+r*h+u*d;ti.circleOutline({x:f,y:p},s.radius*i,o,tl,32)}if(e.world.has(t,dt)){const s=e.world.get(t,dt),o=s.isSensor?Qa:il(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,d=Math.cos(c),h=Math.sin(c);rl(a+r*d-u*h,l+r*h+u*d,s.radius*i,s.halfHeight*i,c,o)}}if(s.showVelocity&&r&&n.bodyType===ht.Dynamic){const e=r.getLinearVelocity(t);al(a,l,e.x*i,e.y*i)}}if(s.showContacts&&e.hasResource(n)){const t=e.getResource(n);for(const e of t.collisionEnters)ti.circle({x:e.contactX,y:e.contactY},3,el,!0,32)}}const cl=pt({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),ul=pt(null,"PhysicsAPI");function dl(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function hl(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class fl{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(cl,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Ya(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(tn.PostUpdate,on([mt(wt)],a=>{const l=r.getEntitiesWithComponents([lt,je]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,lt),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=dl(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),pl(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===ht.Kinematic){const e=dl(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 d=a,h=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=dl(n.worldRotation),i=a-n.worldPosition.x,o=l-n.worldPosition.y,r=Math.cos(-s),u=Math.sin(-s);d=(i*r-o*u)/(0!==n.worldScale.x?n.worldScale.x:1),h=(i*u+o*r)/(0!==n.worldScale.y?n.worldScale.y:1),f=c-s}}u.position.x=d,u.position.y=h;const p=hl(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(cl,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(ul,ml._fromModule(s)),function(e,t,n){e.insertResource(qa,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),ri("physics-debug-draw",()=>{ll(e,t,n)})}(e,ul,cl),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function pl(e,t,n){const s=e.world;if(s.has(n,ct)){const e=s.get(n,ct);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,ut)){const e=s.get(n,ut);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,dt)){const e=s.get(n,dt);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 ml{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(ml.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)}static setDebugDraw(e,t){const n=e.getResource(qa);n&&(n.enabled=t,e.insertResource(qa,n))}static setDebugDrawConfig(e,t){const n=e.getResource(qa);n&&e.insertResource(qa,{...n,...t})}}const gl={nearest:0,linear:1},yl={repeat:0,clamp:1,mirror:2};function _l(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=gl[s.filterMode??"linear"]??1,a=yl[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 wl(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 xl(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,d=a+a,h=l+l,f=c+c,p=a*d,m=a*h,g=a*f,y=l*h,_=l*f,w=c*f,x=u*d,b=u*h,v=u*f;return new Float32Array([(1-(y+w))*i,(m+v)*i,(g-b)*i,0,(m-v)*o,(1-(p+w))*o,(_+x)*o,0,(g+b)*r,(_-x)*r,(1-(p+y))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function bl(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=_s(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]=_l(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 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,n,s,i){const o={};for(const r of s.entities)for(const s of r.components){const r=ws(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 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),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const f=n.loadSkeleton(d,h,s,s.length,r);if(t._free(d),f<0)continue;o[a]=f;const p=wl(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=_l(e,o,!1),a=e.getResourceManager().getTextureGLId(r);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(n,o,h,s,i)),r){const e={gravity:a?.gravity??{...ce},fixedTimestep:a?.fixedTimestep??ue,subStepCount:a?.subStepCount??4};new fl("",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=_s(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=_l(e,c,!1),d=e.getResourceManager();s[o]=d.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=_s(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=Pn.createShader(e.vertexSource,e.fragmentSource),s[i]=r),n[o]=Pn.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=_s(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=Un(s),r=new Map;for(const t of o)try{const s=await n.loadPixels(t);r.set(t,_l(e,s))}catch{r.set(t,0)}Dn(Wn(i,s,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(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=_s(t.type);for(const o of i){if("tilemap"!==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=cs(JSON.parse(t));if(!s)continue;const o=[];for(const t of s.tilesets){const s=us(i,t.image);let r=0;try{const t=await n.loadPixels(s);r=_l(e,t),qn(r,t.width,t.height)}catch{}o.push({textureHandle:r,columns:t.columns})}Jn(i,{tileWidth:s.tileWidth,tileHeight:s.tileHeight,layers:s.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${i}`,e)}}}}}(n,s,i),await async function(e,t){const n=[],s=new Set;for(const t of e.entities)for(const e of t.components){const t=_s(e.type);for(const i of t){if("audio"!==i.type)continue;const t=e.data[i.field];"string"==typeof t&&t&&!s.has(t)&&(s.add(t),n.push(t))}}0!==n.length&&(t?await Promise.all(n.map(async e=>{try{const n=await t.readBinary(e);await Xn.preloadFromData(e,n.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await Xn.preloadAll(n).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(s,i),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=_s(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=Ps(t.world,s);if(c&&t.hasResource(co))for(const e of m.values())t.world.insert(e,ot,{scene:c,persistent:!1});if(o&&h){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=ws(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}(h,s,d,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,d=a?.timeScale??1;u&&s.update(r,l*d);let h=0;if(c.has(o,je)){const e=xl(c.get(o,je),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>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),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(r,e,c,u,d,f);const p=n.HEAPU32[d>>2],m=n.HEAPU32[f>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*i),y=new Uint16Array(n.HEAPU8.buffer,u,o),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,_>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(y),t.renderer_submitTriangles(_,i,w,o,p,m,h),t._free(_),t._free(w),n._free(c),n._free(u),n._free(d),n._free(f)}h&&t._free(h)}})}(t,n,o,h,e)}if(l){const e=t.getResource(ks);e&&e.setAddressableManifest(l)}}function vl(e,t,n){return{name:e,async setup(){await bl({...n,sceneData:t,sceneName:e})}}}async function Sl(e){const{app:t,firstScene:n,aspectRatio:s}=e;mo(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(co);for(const t of e.scenes)o.register(vl(t.name,t.data,i));n&&(o.setInitial(n),await o.load(n)),void 0!==s&&As(t.world,s)}class Ml{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=ws(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=_s(e.type);for(const i of o){const o=e.data[i.field];"string"==typeof o&&o&&("font"===i.type?(s.add(o),t.add(o)):"material"===i.type||"anim-clip"===i.type||"tilemap"===i.type?t.add(o):"audio"===i.type&&n.add(o))}}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 Pl="__preview__";class Tl{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(co);t.register({name:Pl,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Pl),this.loadPromise_=t.load(Pl).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 Ml(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await bl({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:n,spineModule:s,sceneName:Pl})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([Ye]);for(const s of n){if(e.get(s,Ye).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(co).getScene(Pl),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:Le.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Oe.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(co);await e.switchTo(Pl),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 Cl={create(e){const t=e.depth??!0,n="linear"===e.filter,s=(t?1:0)|(n?2:0),i=Zi.createRenderTarget(e.width,e.height,s);return{_handle:i,textureId:Zi.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:n?"linear":"nearest"}},release(e){Zi.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Zi.releaseRenderTarget(e._handle),Cl.create({width:t,height:n,depth:e._depth,filter:e._filter})),begin(e,t){Zi.begin(t,e._handle)},end(){Zi.end()},getDepthTexture:e=>Zi.getTargetDepthTexture(e._handle)};var El;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(El||(El={}));class Al{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${El[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case El.Debug:console.debug(t,n);break;case El.Info:console.log(t,n);break;case El.Warn:console.warn(t,n);break;case El.Error:console.error(t,n)}}}class Rl{constructor(){this.handlers_=[],this.minLevel_=El.Info,this.addHandler(new Al)}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(El.Debug,e,t,n)}info(e,t,n){this.log(El.Info,e,t,n)}warn(e,t,n){this.log(El.Warn,e,t,n)}error(e,t,n){this.log(El.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 Il=new Rl;function kl(){return Il}function Fl(e){Il.setMinLevel(e)}function Bl(e,t,n){Il.debug(e,t,n)}function zl(e,t,n){Il.info(e,t,n)}function Ul(e,t,n){Il.warn(e,t,n)}function Wl(e,t,n){Il.error(e,t,n)}const $l={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},Dl={Running:0,Paused:1,Completed:2,Cancelled:3},Ll={None:0,Restart:1,PingPong:2};const Ol=1.70158,Hl=2.70158,jl=2.5949095;const Vl=2*Math.PI/3,Xl=2*Math.PI/4.5;const Nl=7.5625,Yl=2.75;const ql=1e-6;function Gl(e,t,n){switch(e){case $l.Linear:return t;case $l.EaseInQuad:return function(e){return e*e}(t);case $l.EaseOutQuad:return function(e){return e*(2-e)}(t);case $l.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case $l.EaseInCubic:return function(e){return e*e*e}(t);case $l.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case $l.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case $l.EaseInBack:return function(e){return Hl*e*e*e-Ol*e*e}(t);case $l.EaseOutBack:return function(e){const t=e-1;return 1+Hl*t*t*t+Ol*t*t}(t);case $l.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-jl)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+jl)+2)/2}(t);case $l.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*Vl)}(t);case $l.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*Vl)+1}(t);case $l.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*Xl)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*Xl)/2+1}(t);case $l.EaseOutBounce:return function(e){return e<1/Yl?Nl*e*e:e<2/Yl?Nl*(e-=1.5/Yl)*e+.75:e<2.5/Yl?Nl*(e-=2.25/Yl)*e+.9375:Nl*(e-=2.625/Yl)*e+.984375}(t);case $l.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)<ql)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)<ql)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 $l.Step:return function(e){return e<1?0:1}(t);default:return t}}const Kl=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??$l.Linear,bezierPoints:null,state:Dl.Running,loop:i?.loop??Ll.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)===Dl.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==Dl.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=Gl(t.easing,n,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*s),n>=1){if(t.loop!==Ll.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===Ll.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=Dl.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===Dl.Running&&(t.state=Dl.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===Dl.Paused&&(t.state=Dl.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=Dl.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:Dl.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 Jl{constructor(e){this.id=e}get state(){return Kl.getState(this.id)}bezier(e,t,n,s){return Kl.setBezier(this.id,e,t,n,s),this}then(e){return e instanceof Jl?Kl.setSequenceNext(this.id,e.id):Kl.setSequenceNextExternal(this.id,e),this}pause(){Kl.pause(this.id)}resume(){Kl.resume(this.id)}cancel(){Kl.cancel(this.id)}}const Ql={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 Zl{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 Jl?(Kl.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 ec=null,tc=null;function nc(e,t){ec=e,tc=t,Kl.init(e,t)}function sc(){Kl.shutdown(),ec=null,tc=null}function ic(){if(!ec)throw new Error("Tween API not initialized");return ec}function oc(){if(!tc)throw new Error("Tween API not initialized");return tc}const rc={to(e,t,n,s,i,o){const r=ic(),a=oc(),l=o?.easing??$l.Linear,c=o?.delay??0,u=o?.loop??Ll.None,d=o?.loopCount??0,h=r._anim_createTween(a,e,t,n,s,i,l,c,u,d);return new Zl(r,a,h)},value(e,t,n,s,i){const o=Kl.create(e,t,n,s,i);return new Jl(o)},cancel(e){ic()._anim_cancelTween(oc(),e.entity)},cancelAll(e){ic()._anim_cancelAllTweens(oc(),e)},update(e){ic()._anim_updateTweens(oc(),e),Kl.update(e)}};class ac{constructor(){this.name="AnimationPlugin"}build(e){nc(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(tn.Update,on([mt(wt)],e=>{rc.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(tn.Update,on([mt(wt)],e=>{Vn(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){sc()}}const lc=new ac;var cc;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(cc||(cc={}));const uc={model:cc.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function dc(e,t=uc){const{model:n,refDistance:s,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(n){case cc.Linear:{const e=i-s;if(e<=0)return 1;a=1-(Math.min(Math.max(r,s),i)-s)/e;break}case cc.Inverse:a=s/Math.max(r,s);break;case cc.Exponential:a=Math.pow(Math.max(r,s)/s,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function hc(e,t,n,s,i){const o=e-n;return Math.max(-1,Math.min(1,o/i))}const fc=Ae("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:cc.Inverse,rolloff:1,priority:0,enabled:!0}),pc=Ae("AudioListener",{enabled:!0});class mc{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;Xn.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(tn.PreUpdate,on([mt(wt)],t=>{if(!(!Fr()||Ur()))return void(c&&(l=!1,c=!1));c=!0;const s=e.world;let i=0,u=0,d=!1;const h=s.getEntitiesWithComponents([pc,Xe]);for(const e of h){if(s.get(e,pc).enabled){const t=s.get(e,Xe);i=t.position.x,u=t.position.y,d=!0;break}}const f=s.getEntitiesWithComponents([fc]);a.clear();for(const e of f){const t=s.get(e,fc);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=Xn.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}d||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=s.tryGet?.(e,Xe),a=r?.position.x??0,h=r?.position.y??0,f=a-i,p=h-u,m=dc(Math.sqrt(f*f+p*p),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=hc(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(),Xn.dispose()}}const gc=new mc;let yc=null,_c=null;function wc(e,t){yc=e,_c=t}function xc(){yc=null,_c=null}const bc={update(e){yc&&_c&&yc.particle_update?.(_c,e)},play(e){yc&&_c&&yc.particle_play?.(_c,e)},stop(e){yc&&_c&&yc.particle_stop?.(_c,e)},reset(e){yc&&_c&&yc.particle_reset?.(_c,e)},getAliveCount:e=>yc?yc.particle_getAliveCount?.(e)??0:0};class vc{constructor(){this.name="ParticlePlugin"}build(e){wc(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(tn.Update,on([mt(wt)],e=>{bc.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){xc()}}const Sc=new vc,Mc=1e6;class Pc{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.sourceEntityKeys_=new Map}build(e){ts(e.wasmModule);const t=e.world,n=this.initializedLayers_,s=this.sourceEntityKeys_;e.pipeline?.setTilemapRenderer(()=>{const i=e.getResource(mn),o=i?.valid?i.worldLeft:-1e6,r=i?.valid?i.worldBottom:-1e6,a=i?.valid?i.worldRight:Mc,l=i?.valid?i.worldTop:Mc,c=t.getEntitiesWithComponents([os,je]);for(const e of c){const s=t.tryGet(e,os),i=t.tryGet(e,je);if(!s||!i)continue;if(!s.visible)continue;const c=s.texture;if(!c)continue;const u=Gn(c);if(!u)continue;if(!n.has(e)){if(ss.initLayer(e,s.width,s.height,s.tileWidth,s.tileHeight),s.tiles.length>0){const t=new Uint16Array(s.tiles.length);for(let e=0;e<s.tiles.length;e++)t[e]=s.tiles[e];ss.setTiles(e,t)}n.add(e)}const d=s.tileWidth/u.width,h=s.tileHeight/u.height,f=s.tint,p=s.parallaxFactor;ss.submitLayer(e,c,s.layer,0,s.tilesetColumns,d,h,i.worldPosition.x,i.worldPosition.y,o,r,a,l,f.r,f.g,f.b,f.a,s.opacity,p.x,p.y)}const u=t.getEntitiesWithComponents([is,je]);for(const e of u){if(t.tryGet(e,os))continue;const i=t.tryGet(e,is),c=t.tryGet(e,je);if(!i?.source||!c)continue;const u=Qn(i.source);if(!u)continue;if(!s.has(e)){const t=[];for(let s=0;s<u.layers.length;s++){const i=1073741824+256*e+s,o=u.layers[s];ss.initLayer(i,o.width,o.height,u.tileWidth,u.tileHeight),o.tiles.length>0&&ss.setTiles(i,o.tiles),t.push(i),n.add(i)}s.set(e,t)}const d=s.get(e);for(let e=0;e<u.layers.length&&e<d.length;e++){const t=d[e],n=u.tilesets[0];if(!n)continue;const s=Gn(n.textureHandle);if(!s)continue;const i=u.tileWidth/s.width,h=u.tileHeight/s.height;ss.submitLayer(t,n.textureHandle,e,0,n.columns,i,h,c.worldPosition.x,c.worldPosition.y,o,r,a,l,1,1,1,1,1,1,1)}}})}cleanup(){for(const e of this.initializedLayers_)ss.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),Kn(),ns()}}const Tc=new Pc;function Cc(e,t){return e.toFixed(t)}function Ec(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}class Ac{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">${Cc(e.fps,1)}</span> Frame: <span style="color:#d19a66">${Cc(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>${Ec(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${Cc(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 Rc(){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 Ic=pt(Rc(),"Stats");class kc{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 Fc="StatsCollect";class Bc{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 zc{constructor(e){this.name="Stats",this.collector_=new Bc,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(Ic,Rc());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new Ac(e,this.options_.position)}const t=this.collector_,n=this.overlay_,s=on([mt(wt),{_type:"get_world"}],(s,i)=>{t.pushFrame(s.delta);const o=e.getResource(Ic);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(Fc),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=Zi.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:Fc});e.addSystemToSchedule(tn.Last,s)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const Uc=new zc;class Wc{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 $c(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 Dc(e){const{app:t,module:n,assets:s,scenes:i,firstScene:o}=e,r=t.getResource(ks);r&&(r.registerEmbeddedAssets(s),r.setEmbeddedOnly(!0));const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await $c(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 $c(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new Wc(s);await Sl({app:t,module:n,provider:c,scenes:i,firstScene:o,spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()}const Lc=[ar,br,Ar,Zr,la,Lr,ha,ya,Sa,sa,Nr,Pa,Aa,Ba,Wa,ja,Xa],Oc=[...Lc,lc,gc,Sc,Tc,Yi];function Hc(e,t){return function(e,t){const n=po.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Js(e),vn(e),pi(e),Ti(e),Ji(e),to(e);const i=new io;n.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=xo(e,s,t,i));const r=n.getResource(mn);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(mn,{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;Zi.setClearColor(e.x,e.y,e.z,e.w)}const u=(h()-o)/1e3;let d;if(Zi.resize(t,l),n.hasResource(co)){const e=n.getResource(co).getActiveScenes();e.length>0&&(d=new Set(e))}i.setActiveScenes(d??null);const f=xo(e,s,t,l,n.world,d);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:go,width:t,height:l,elapsed:u});else{i.beginScreenCapture();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,cameraEntity:e.entity})}i.endScreenCapture(),Zi.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(tn.First,l),n.addSystemToSchedule(tn.Last,c),n.addPlugin(Bs),n.addPlugin(Xs),n.addPlugin(pn),n.addPlugin(fo),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Oc,...t})}class jc{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 Vc(e){return(t,n)=>(u(e,t).then(e=>{n(e.instance,e.module)}),{})}async function Xc(e,t){try{return await e({instantiateWasm:Vc(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}async function Nc(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=W(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:Vc("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=Hc(a,{glContextHandle:u,getViewportSize:()=>({width:o.width,height:o.height})});e.runtimeConfig&&me(d,e.runtimeConfig);let h=null;e.spineFactory&&(h=await Xc(e.spineFactory,"spine.wasm"));let f=null;e.physicsFactory&&(f=await Xc(e.physicsFactory,"physics.wasm"));const p=new jc(i),m=[];for(const t of e.sceneNames){const e=await l(`scenes/${t}.json`);m.push({name:t,data:JSON.parse(e)})}await Sl({app:d,module:a,provider:p,scenes:m,firstScene:e.firstScene,spineModule:h,physicsModule:f,physicsConfig:e.physicsConfig,manifest:n,aspectRatio:o.width/o.height}),d.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{zt as Added,ac as AnimationPlugin,po as App,Fs as AssetPlugin,zs as AssetRefCounter,Is as AssetServer,ks as Assets,Bn as AsyncCache,cc as AttenuationModel,Xn as Audio,p as AudioBus,pc as AudioListener,m as AudioMixer,mc as AudioPlugin,g as AudioPool,fc as AudioSource,Qe as BitmapText,gn as BlendMode,ht as BodyType,ct as BoxCollider,Pr as Button,Mr as ButtonState,Ye as Camera,qe as Canvas,dt as CapsuleCollider,Ut as Changed,Je as Children,ut as CircleCollider,Oe as ClearFlags,Xt as Commands,Yt 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,de as DEFAULT_SPINE_SKIN,se as DEFAULT_SPRITE_SIZE,ne as DEFAULT_TEXT_CANVAS_SIZE,ci as DataType,da as DragPlugin,ua as DragState,ca as Draggable,ti as Draw,za as Dropdown,Ua as DropdownPlugin,$l as EasingType,et as EmitterShape,Nt as EntityCommands,Qt as EventReader,en as EventReaderInstance,Kt as EventRegistry,Jt as EventWriter,Zt as EventWriterInstance,Ao as FillDirection,qr as FillMethod,Gr as FillOrigin,Vr as FocusManager,jr as FocusManagerState,Ma as FocusPlugin,Hr as Focusable,kc as FrameHistory,so as GLDebug,yi as Geometry,nn as GetWorld,ge as INVALID_ENTITY,_e as INVALID_FONT,we as INVALID_MATERIAL,ye as INVALID_TEXTURE,Kr as Image,Qr as ImagePlugin,Yr as ImageType,hn as Input,fn as InputPlugin,dn as InputState,vr as Interactable,Ha as LayoutGroupPlugin,Ra as ListView,Fa as ListViewPlugin,Ve as LocalTransform,El as LogLevel,Rl as Logger,Ll as LoopMode,Pn as Material,zn as MaterialLoader,Ft as Mut,it as Name,Ke as Parent,bc as Particle,nt as ParticleEasing,st as ParticleEmitter,vc as ParticlePlugin,ml as Physics,cl as PhysicsEvents,fl as PhysicsPlugin,Ai as PostProcess,Ni as PostProcessPlugin,Si as PostProcessStack,rt as PostProcessVolume,Hs as PrefabServer,js as Prefabs,Vs as PrefabsPlugin,Tl as PreviewPlugin,oa as ProgressBar,ia as ProgressBarDirection,aa as ProgressBarPlugin,Le as ProjectionType,Ot as Query,Ht as QueryInstance,jt as Removed,Vt as RemovedQueryInstance,io as RenderPipeline,qi as RenderStage,Cl as RenderTexture,Zi as Renderer,mt as Res,gt as ResMut,lt as RigidBody,he as RuntimeConfig,Ta as SafeArea,Ea as SafeAreaPlugin,He as ScaleMode,co as SceneManager,lo as SceneManagerState,ot as SceneOwner,tn as Schedule,fa as ScrollView,ga as ScrollViewPlugin,Fn as ShaderSources,tt as SimulationSpace,wa as Slider,_a as SliderDirection,va as SliderPlugin,Ze as SpineAnimation,Ne as Sprite,jn as SpriteAnimator,Ic as Stats,Bc as StatsCollector,Ac as StatsOverlay,zc as StatsPlugin,un as SystemRunner,sr as Text,er as TextAlign,Or as TextInput,Xr as TextInputPlugin,nr as TextOverflow,rr as TextPlugin,ir as TextRenderer,tr as TextVerticalAlign,is as Tilemap,ss as TilemapAPI,os as TilemapLayer,Pc as TilemapPlugin,wt as Time,ea as Toggle,na as TogglePlugin,je as Transform,rc as Tween,Zl as TweenHandle,Dl as TweenState,Ql as TweenTarget,mn as UICameraInfo,Tr as UIEventQueue,Cr as UIEvents,Sr as UIInteraction,Dr as UIInteractionPlugin,Er as UILayoutPlugin,ur as UIMask,xr as UIMaskPlugin,Io as UIRect,Va as UIRenderOrderPlugin,Ge as Velocity,jc as WeChatAssetProvider,Ml as WebAssetProvider,kt as World,Xe as WorldTransform,ln as addStartupSystem,an as addSystem,cn as addSystemToSchedule,lc as animationPlugin,me as applyBuildRuntimeConfig,$o as applyDirectionalFill,fe as applyRuntimeConfig,Bs as assetPlugin,gc as audioPlugin,dc as calculateAttenuation,hc as calculatePanning,Di as cleanupAllPostProcessVolumes,$i as cleanupPostProcessVolume,Hn as clearAnimClips,li as clearDrawCallbacks,Kn as clearTextureDimensionsCache,Zn as clearTilemapSourceCache,ke as clearUserComponents,Se as color,zo as computeFillAnchors,Wo as computeFillSize,Uo as computeHandleAnchors,Ro as computeUIRectLayout,wr as createMaskProcessor,vl as createRuntimeSceneConfig,Hc as createWebApp,Bl as debug,Rc as defaultFrameStats,Ae as defineComponent,qt as defineEvent,pt as defineResource,on as defineSystem,Re as defineTag,ha as dragPlugin,Wa as dropdownPlugin,Wl as error,Un as extractAnimClipTexturePaths,Rs as findEntityByName,mo as flushPendingSystems,Pa as focusPlugin,E as getAddressableType,A as getAddressableTypeByEditorType,I as getAllAssetExtensions,Bi as getAllEffectDefs,On as getAnimClip,D as getAssetBuildTransform,z as getAssetMimeType,T as getAssetTypeEntry,$e as getComponent,_s as getComponentAssetFieldDescriptors,ys as getComponentAssetFields,at as getComponentDefaults,vs as getComponentEntityFields,ws as getComponentSpineFieldDescriptor,F as getCustomExtensions,C as getEditorType,ki as getEffectDef,Fi as getEffectTypes,kl as getLogger,t as getPlatform,s as getPlatformType,Gn as getTextureDimensions,Qn as getTilemapSource,Ie as getUserComponent,B as getWeChatPackOptions,Zr as imagePlugin,zl as info,Js as initDrawAPI,to as initGLDebugAPI,pi as initGeometryAPI,vn as initMaterialAPI,wc as initParticleAPI,Dc as initPlayableRuntime,Ti as initPostProcessAPI,Ji as initRendererAPI,Sl as initRuntime,ts as initTilemapAPI,nc as initTweenAPI,Nc as initWeChatRuntime,pn as inputPlugin,Ws as instantiatePrefab,dr as intersectRects,hr as invertMatrix4,ze as isBuiltinComponent,U as isCustomExtension,Fr as isEditor,R as isKnownAssetExtension,n as isPlatformInitialized,Ur as isPlayMode,Br as isRuntime,yn as isTextureRef,i as isWeChat,o as isWeb,ja as layoutGroupPlugin,Ba as listViewPlugin,Es as loadComponent,Ya as loadPhysicsModule,bl as loadRuntimeScene,Ps as loadSceneData,Ts as loadSceneWithAssets,ps as loadTiledMap,k as looksLikeAssetPath,Wn as parseAnimClipData,ds as parseTiledMap,cs as parseTmjJson,Sc as particlePlugin,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,yr as pointInOBB,pr as pointInWorldRect,Yi as postProcessPlugin,Xs as prefabsPlugin,la as progressBarPlugin,Me as quat,Dn as registerAnimClip,$ as registerAssetBuildTransform,We as registerComponent,gs as registerComponentAssetFields,bs as registerComponentEntityFields,ri as registerDrawCallback,Us as registerEmbeddedAssets,kn as registerMaterialCallback,qn as registerTextureDimensions,Jn as registerTilemapSource,Ss as remapEntityFields,us as resolveRelativePath,Aa as safeAreaPlugin,fo as sceneManagerPlugin,fr as screenToWorld,ya as scrollViewPlugin,kr as setEditorMode,ka as setListViewRenderer,Fl as setLogLevel,zr as setPlayMode,Mt as setWasmErrorHandler,Qs as shutdownDrawAPI,no as shutdownGLDebugAPI,mi as shutdownGeometryAPI,Sn as shutdownMaterialAPI,xc as shutdownParticleAPI,Ci as shutdownPostProcessAPI,Qi as shutdownRendererAPI,ns as shutdownTilemapAPI,sc as shutdownTweenAPI,Sa as sliderPlugin,Vn as spriteAnimatorSystemUpdate,Uc as statsPlugin,No as syncFillSpriteSize,Wi as syncPostProcessVolume,Nr as textInputPlugin,ar as textPlugin,Tc as tilemapPlugin,W as toBuildPath,sa as togglePlugin,Na as transitionTo,Lr as uiInteractionPlugin,Ar as uiLayoutPlugin,br as uiMaskPlugin,Lc as uiPlugins,Xa as uiRenderOrderPlugin,Ln as unregisterAnimClip,Fe as unregisterComponent,ai as unregisterDrawCallback,As as updateCameraAspectRatio,xe as vec2,be as vec3,ve as vec4,Ul as warn,uo as wrapSceneSystem,X as wxFileExists,N as wxFileExistsSync,G as wxGetImagePixels,q as wxLoadImage,K as wxLoadImagePixels,j as wxReadFile,V as wxReadTextFile,Y as wxWriteFile};
//# sourceMappingURL=index.wechat.js.map
diff --git a/desktop/public/sdk/esm/esengine.d.ts b/desktop/public/sdk/esm/esengine.d.ts
index c9bd55bbb..98a4ce641 100644
--- a/desktop/public/sdk/esm/esengine.d.ts
+++ b/desktop/public/sdk/esm/esengine.d.ts
@@ -369,6 +369,15 @@ interface PostProcessVolumeData$1 {
enabled: boolean;
uniforms: Record<string, number>;
}[];
+ isGlobal: boolean;
+ shape: 'box' | 'sphere';
+ size: {
+ x: number;
+ y: number;
+ };
+ priority: number;
+ weight: number;
+ blendDistance: number;
}
declare const PostProcessVolume: ComponentDef<PostProcessVolumeData$1>;
@@ -848,6 +857,13 @@ interface ESEngineModule {
postprocess_clearPasses(): void;
postprocess_setOutputTarget(fboId: number): void;
postprocess_setOutputViewport(x: number, y: number, w: number, h: number): void;
+ postprocess_beginScreenCapture(): void;
+ postprocess_endScreenCapture(): void;
+ postprocess_executeScreenPasses(): void;
+ postprocess_addScreenPass(name: string, shaderHandle: number): number;
+ postprocess_clearScreenPasses(): void;
+ postprocess_setScreenUniformFloat(passName: string, uniform: string, value: number): void;
+ postprocess_setScreenUniformVec4(passName: string, uniform: string, x: number, y: number, z: number, w: number): void;
renderer_init(width: number, height: number): void;
renderer_resize(width: number, height: number): void;
renderer_begin(matrixPtr: number, targetHandle: number): void;
@@ -1272,6 +1288,8 @@ declare class RenderPipeline {
get maskProcessor(): MaskProcessorFn | null;
setMaskProcessor(fn: MaskProcessorFn | null): void;
setActiveScenes(scenes: Set<string> | null): void;
+ beginScreenCapture(): void;
+ endScreenCapture(): void;
render(params: RenderParams): void;
renderCamera(params: CameraRenderParams): void;
private executeDrawCallbacks;
@@ -1923,13 +1941,6 @@ declare function registerDrawCallback(id: string, fn: DrawCallback, scene?: stri
declare function unregisterDrawCallback(id: string): void;
declare function clearDrawCallbacks(): void;
-/**
- * @file postprocess.ts
- * @brief Per-camera post-processing effects API
- */
-
-declare function initPostProcessAPI(wasmModule: ESEngineModule): void;
-declare function shutdownPostProcessAPI(): void;
interface PassConfig {
name: string;
shader: ShaderHandle;
@@ -1954,6 +1965,9 @@ declare class PostProcessStack {
get isDestroyed(): boolean;
destroy(): void;
}
+
+declare function initPostProcessAPI(wasmModule: ESEngineModule): void;
+declare function shutdownPostProcessAPI(): void;
declare const PostProcess: {
createStack(): PostProcessStack;
bind(camera: Entity, stack: PostProcessStack): void;
@@ -1968,12 +1982,19 @@ declare const PostProcess: {
_applyForCamera(camera: Entity): void;
_resetAfterCamera(): void;
_cleanupDestroyedCameras(isValid: (e: Entity) => boolean): void;
+ screenStack: PostProcessStack | null;
+ setScreenStack(stack: PostProcessStack | null): void;
+ _beginScreenCapture(): void;
+ _endScreenCapture(): void;
+ _applyScreenStack(): void;
+ _executeScreenPasses(): void;
createBlur(): ShaderHandle;
createVignette(): ShaderHandle;
createGrayscale(): ShaderHandle;
createBloom(): ShaderHandle;
createChromaticAberration(): ShaderHandle;
};
+
interface EffectUniformDef {
name: string;
label: string;
@@ -1991,6 +2012,7 @@ interface EffectDef {
declare function getEffectDef(type: string): EffectDef | undefined;
declare function getEffectTypes(): string[];
declare function getAllEffectDefs(): EffectDef[];
+
interface PostProcessEffectData {
type: string;
enabled: boolean;
@@ -1998,11 +2020,27 @@ interface PostProcessEffectData {
}
interface PostProcessVolumeData {
effects: PostProcessEffectData[];
+ isGlobal: boolean;
+ shape: 'box' | 'sphere';
+ size: {
+ x: number;
+ y: number;
+ };
+ priority: number;
+ weight: number;
+ blendDistance: number;
}
declare function syncPostProcessVolume(camera: Entity, data: PostProcessVolumeData): void;
declare function cleanupPostProcessVolume(camera: Entity): void;
declare function cleanupAllPostProcessVolumes(): void;
+declare class PostProcessPlugin implements Plugin {
+ name: string;
+ build(app: App): void;
+ cleanup(): void;
+}
+declare const postProcessPlugin: PostProcessPlugin;
+
type SceneStatus = 'loading' | 'running' | 'paused' | 'sleeping' | 'unloading';
interface SceneConfig {
name: string;
@@ -3466,6 +3504,13 @@ declare function isRuntime(): boolean;
declare function setPlayMode(active: boolean): void;
declare function isPlayMode(): boolean;
+interface PhysicsDebugDrawConfig {
+ enabled: boolean;
+ showColliders: boolean;
+ showVelocity: boolean;
+ showContacts: boolean;
+}
+
interface PhysicsPluginConfig {
gravity?: Vec2;
fixedTimestep?: number;
@@ -3515,6 +3560,8 @@ declare class Physics {
getAngularVelocity(entity: Entity): number;
applyTorque(entity: Entity, torque: number): void;
applyAngularImpulse(entity: Entity, impulse: number): void;
+ static setDebugDraw(app: App, enabled: boolean): void;
+ static setDebugDrawConfig(app: App, config: Partial<PhysicsDebugDrawConfig>): void;
}
/**
@@ -3897,6 +3944,18 @@ interface TilemapLayerData {
tilesetColumns: number;
layer: number;
tiles: number[];
+ tint: {
+ r: number;
+ g: number;
+ b: number;
+ a: number;
+ };
+ opacity: number;
+ visible: boolean;
+ parallaxFactor: {
+ x: number;
+ y: number;
+ };
}
declare const Tilemap: ComponentDef<TilemapData>;
declare const TilemapLayer: ComponentDef<TilemapLayerData>;
@@ -3911,7 +3970,7 @@ declare const TilemapAPI: {
fillRect(entity: number, x: number, y: number, w: number, h: number, tileId: number): void;
setTiles(entity: number, tiles: Uint16Array): void;
hasLayer(entity: number): boolean;
- submitLayer(entity: number, textureId: number, sortLayer: number, depth: number, tilesetColumns: number, uvTileWidth: number, uvTileHeight: number, originX: number, originY: number, camLeft: number, camBottom: number, camRight: number, camTop: number): void;
+ submitLayer(entity: number, textureId: number, sortLayer: number, depth: number, tilesetColumns: number, uvTileWidth: number, uvTileHeight: number, originX: number, originY: number, camLeft: number, camBottom: number, camRight: number, camTop: number, tintR: number, tintG: number, tintB: number, tintA: number, opacity: number, parallaxX: number, parallaxY: number): void;
};
declare class TilemapPlugin implements Plugin {
@@ -3929,6 +3988,15 @@ interface TiledLayerData {
height: number;
visible: boolean;
tiles: Uint16Array;
+ opacity: number;
+ tintColor: {
+ r: number;
+ g: number;
+ b: number;
+ a: number;
+ };
+ parallaxX: number;
+ parallaxY: number;
}
interface TiledTilesetData {
name: string;
@@ -3938,6 +4006,21 @@ interface TiledTilesetData {
columns: number;
tileCount: number;
}
+type TiledObjectShape = 'rect' | 'ellipse' | 'polygon' | 'point';
+interface TiledObjectData {
+ shape: TiledObjectShape;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ rotation: number;
+ vertices: number[] | null;
+ properties: Map<string, unknown>;
+}
+interface TiledObjectGroupData {
+ name: string;
+ objects: TiledObjectData[];
+}
interface TiledMapData {
width: number;
height: number;
@@ -3945,11 +4028,17 @@ interface TiledMapData {
tileHeight: number;
layers: TiledLayerData[];
tilesets: TiledTilesetData[];
+ objectGroups: TiledObjectGroupData[];
+ collisionTileIds: number[];
}
declare function parseTmjJson(json: Record<string, unknown>): TiledMapData | null;
declare function resolveRelativePath(basePath: string, relativePath: string): string;
declare function parseTiledMap(jsonString: string, resolveExternal?: (source: string) => Promise<string>): Promise<TiledMapData | null>;
-declare function loadTiledMap(world: World, mapData: TiledMapData, textureHandles: Map<string, number>): Entity[];
+interface TilemapLoadOptions {
+ generateObjectCollision?: boolean;
+ collisionTileIds?: number[];
+}
+declare function loadTiledMap(world: World, mapData: TiledMapData, textureHandles: Map<string, number>, options?: TilemapLoadOptions): Entity[];
interface TextureDimensions {
width: number;
@@ -4079,5 +4168,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, EmitterShape, 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, Particle, ParticleEasing, ParticleEmitter$1 as ParticleEmitter, ParticlePlugin, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PostProcessStack, PostProcessVolume, 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, SimulationSpace, 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, Tilemap, TilemapAPI, TilemapLayer, TilemapPlugin, 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, cleanupAllPostProcessVolumes, cleanupPostProcessVolume, clearAnimClips, clearDrawCallbacks, clearTextureDimensionsCache, clearTilemapSourceCache, 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, getAllEffectDefs, getAnimClip, getAssetBuildTransform, getAssetMimeType, getAssetTypeEntry, getComponent, getComponentAssetFieldDescriptors, getComponentAssetFields, getComponentDefaults, getComponentEntityFields, getComponentSpineFieldDescriptor, getCustomExtensions, getEditorType, getEffectDef, getEffectTypes, getLogger, getPlatform, getPlatformType, getTextureDimensions, getTilemapSource, getUserComponent, getWeChatPackOptions, imagePlugin, info, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initParticleAPI, initPlayableRuntime, initPostProcessAPI, initRendererAPI, initRuntime, initTilemapAPI, initTweenAPI, inputPlugin, instantiatePrefab, intersectRects, invertMatrix4, isBuiltinComponent, isCustomExtension, isEditor, isKnownAssetExtension, isPlatformInitialized, isPlayMode, isRuntime, isTextureRef, isWeChat, isWeb, layoutGroupPlugin, listViewPlugin, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, loadTiledMap, looksLikeAssetPath, parseAnimClipData, parseTiledMap, parseTmjJson, particlePlugin, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInOBB, pointInWorldRect, prefabsPlugin, progressBarPlugin, quat, registerAnimClip, registerAssetBuildTransform, registerComponent, registerComponentAssetFields, registerComponentEntityFields, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, registerTextureDimensions, registerTilemapSource, remapEntityFields, resolveRelativePath, safeAreaPlugin, sceneManagerPlugin, screenToWorld, scrollViewPlugin, setEditorMode, setListViewRenderer, setLogLevel, setPlayMode, setWasmErrorHandler, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownParticleAPI, shutdownPostProcessAPI, shutdownRendererAPI, shutdownTilemapAPI, shutdownTweenAPI, sliderPlugin, spriteAnimatorSystemUpdate, statsPlugin, syncFillSpriteSize, syncPostProcessVolume, textInputPlugin, textPlugin, tilemapPlugin, toBuildPath, togglePlugin, transitionTo, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, uiPlugins, uiRenderOrderPlugin, unregisterAnimClip, unregisterComponent, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, warn, wrapSceneSystem };
+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, EmitterShape, 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, Particle, ParticleEasing, ParticleEmitter$1 as ParticleEmitter, ParticlePlugin, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PostProcessPlugin, PostProcessStack, PostProcessVolume, 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, SimulationSpace, 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, Tilemap, TilemapAPI, TilemapLayer, TilemapPlugin, 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, cleanupAllPostProcessVolumes, cleanupPostProcessVolume, clearAnimClips, clearDrawCallbacks, clearTextureDimensionsCache, clearTilemapSourceCache, 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, getAllEffectDefs, getAnimClip, getAssetBuildTransform, getAssetMimeType, getAssetTypeEntry, getComponent, getComponentAssetFieldDescriptors, getComponentAssetFields, getComponentDefaults, getComponentEntityFields, getComponentSpineFieldDescriptor, getCustomExtensions, getEditorType, getEffectDef, getEffectTypes, getLogger, getPlatform, getPlatformType, getTextureDimensions, getTilemapSource, getUserComponent, getWeChatPackOptions, imagePlugin, info, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initParticleAPI, initPlayableRuntime, initPostProcessAPI, initRendererAPI, initRuntime, initTilemapAPI, initTweenAPI, inputPlugin, instantiatePrefab, intersectRects, invertMatrix4, isBuiltinComponent, isCustomExtension, isEditor, isKnownAssetExtension, isPlatformInitialized, isPlayMode, isRuntime, isTextureRef, isWeChat, isWeb, layoutGroupPlugin, listViewPlugin, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, loadTiledMap, looksLikeAssetPath, parseAnimClipData, parseTiledMap, parseTmjJson, particlePlugin, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInOBB, pointInWorldRect, postProcessPlugin, prefabsPlugin, progressBarPlugin, quat, registerAnimClip, registerAssetBuildTransform, registerComponent, registerComponentAssetFields, registerComponentEntityFields, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, registerTextureDimensions, registerTilemapSource, remapEntityFields, resolveRelativePath, safeAreaPlugin, sceneManagerPlugin, screenToWorld, scrollViewPlugin, setEditorMode, setListViewRenderer, setLogLevel, setPlayMode, setWasmErrorHandler, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownParticleAPI, shutdownPostProcessAPI, shutdownRendererAPI, shutdownTilemapAPI, shutdownTweenAPI, sliderPlugin, spriteAnimatorSystemUpdate, statsPlugin, syncFillSpriteSize, syncPostProcessVolume, textInputPlugin, textPlugin, tilemapPlugin, 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, EffectDef, EffectUniformDef, Entity, EventDef, EventReaderDescriptor, EventWriterDescriptor, FileLoadOptions, FocusableData, FontHandle, FrameSnapshot, FrameStats, GeometryHandle, GeometryOptions, GetWorldDescriptor, ImageData, InferParam, InferParams, InstantiatePrefabOptions, InstantiatePrefabResult, InteractableData, LayoutRect, LayoutResult, ListViewData, ListViewItemRenderer, LoadRuntimeSceneOptions, LoadedMaterial, LoadedTilemapLayer, LoadedTilemapSource, LoadedTilemapTileset, LocalTransformData, LogEntry, LogHandler, MaskProcessorFn, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, NameData, ParentData, ParticleEmitterData, PhysicsEventsData, PhysicsModuleFactory, PhysicsPluginConfig, PhysicsWasmModule, PlatformAdapter, PlatformAudioBackend, PlatformRequestOptions, PlatformResponse, PlatformType, PlayConfig, PlayableRuntimeConfig, Plugin, PluginDependency, PooledAudioNode, PostProcessEffectData, PostProcessVolumeData$1 as PostProcessVolumeData, 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, TextureDimensions, TextureHandle, TextureInfo, TextureRef, TiledLayerData, TiledMapData, TiledTilesetData, TilemapData, TilemapLayerData, 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.js
index e7b939827..d1447cd89 100644
--- a/desktop/public/sdk/esm/esengine.js
+++ b/desktop/public/sdk/esm/esengine.js
@@ -1,2 +1,2 @@
-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function 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 d(e,n){return t().createCanvas(e,n)}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),n=e.parent?this.buses_.get(e.parent):this.master;return n&&n.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,n,s,i,o,r){this.playing_=!0,this.stopped_=!1,this.pausedAt_=0,this.id=e,this.source_=t,this.buffer_=n,this.poolNode_=s,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 n=this.loadingUrls_.get(e);if(n)return n;const s=this.doLoadBuffer_(e);this.loadingUrls_.set(e,s);try{return await s}finally{this.loadingUrls_.delete(e)}}async loadBufferFromData(e,t){if(!this.context_)throw new Error("AudioContext not initialized");const n=this.urlToId_.get(e);if(void 0!==n&&this.buffers_.has(n)){return{id:n,duration:this.buffers_.get(n).duration}}let s;try{s=await this.context_.decodeAudioData(t)}catch(t){throw new Error(`Failed to decode audio ${e}: ${t.message}`)}const i=++this.nextBufferId_;return this.buffers_.set(i,s),this.urlToId_.set(e,i),{id:i,duration:s.duration}}async doLoadBuffer_(e){const n=await t().readFile(e);return this.loadBufferFromData(e,n)}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 n=this.buffers_.get(e.id);if(!n)throw new Error(`Buffer ${e.id} not found`);const s=this.pool_.acquire(),i=this.context_.createBufferSource();i.buffer=n,i.loop=t.loop??!1,i.playbackRate.value=t.playbackRate??1,i.connect(s.gain),s.source=i,s.gain.gain.value=t.volume??1,s.panner.pan.value=t.pan??0;const o=t.bus??"sfx",r=this.mixer_.getBus(o)??this.mixer_.sfx;s.panner.connect(r.node);const a=t.startOffset??0;i.start(0,a);const l=++this.nextHandleId_;return new g(l,i,n,s,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 n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async loadImagePixels(e){const t=this.createImage();await new Promise((n,s)=>{t.crossOrigin="anonymous",t.onload=()=>n(),t.onerror=()=>s(new Error(`Failed to load image: ${e}`)),t.src=e});const n=this.createCanvas(t.width,t.height).getContext("2d");n.drawImage(t,0,0);const s=n.getImageData(0,0,t.width,t.height);return{width:t.width,height:t.height,pixels:new Uint8Array(s.data.buffer)}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.module}}createImage(){return new Image}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),i=t=>e.onKeyUp(t.code),o=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},r=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},u=()=>{e.onPointerUp(0)},d=t=>{const n=t;let s=n.deltaX,i=n.deltaY;1===n.deltaMode?(s*=16,i*=16):2===n.deltaMode&&(s*=window.innerWidth,i*=window.innerHeight),e.onWheel(s,i)};document.addEventListener("keydown",s),document.addEventListener("keyup",i),n.addEventListener("mousemove",o),n.addEventListener("mousedown",r),document.addEventListener("mouseup",a),n.addEventListener("touchstart",l),n.addEventListener("touchmove",c),n.addEventListener("touchend",u),n.addEventListener("wheel",d),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",i),n.removeEventListener("mousemove",o),n.removeEventListener("mousedown",r),document.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",u),n.removeEventListener("wheel",d)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new y}},x=1920,v=1080,b=100,S=512,M={x:100,y:100},T="Arial",P=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 L=0,$=4294967295,D=4294967295,O=0,H=(e=0,t=0)=>({x:e,y:t}),W=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),V=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),N=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),j=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function X(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(X);const t={};for(const n in e)t[n]=X(e[n]);return t}let Y=0;function q(e,t){const n=++Y,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?{...X(t),...e}:X(t):e?{...t,...e}:{...t}}}function G(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function K(e,t){const n=se.get(e)??G().get(e);if(n)return n;const s=q(e,t);return G().set(e,s),se.set(e,s),te(e,t,!1),s}function J(e){const t=se.get(e)??G().get(e);if(t)return t;const n=q(e,{});return G().set(e,n),se.set(e,n),te(e,{},!0),n}function Q(e){return G().get(e)}function Z(){const e=G();for(const t of e.keys())se.delete(t);e.clear()}function ee(e){G().delete(e),se.delete(e)}function te(e,t,n){const s=globalThis;s.__esengine_registerComponent&&s.__esengine_registerComponent(e,t,n)}function ne(e){return!0===e._builtin}const se=new Map;function ie(e,t){se.set(e,t)}function oe(e){return se.get(e)??Q(e)}function re(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return se.set(e,n),n}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}}),de=ue,he=ue,fe=re("Sprite",{texture:$,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:D,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={Point:0,Circle:1,Rectangle:2,Cone:3},be={World:0,Local:1},Se={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},Me=re("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:ve.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:Se.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:Se.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:$,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:be.World,enabled:!0}),Te=K("Name",{value:""}),Pe=K("SceneOwner",{scene:"",persistent:!1}),Ee=K("PostProcessVolume",{effects:[]});function Ce(e){const t=oe(e);return t?X(t._default):null}const Ae=re("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Re=re("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ie=re("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ke=re("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Fe={Static:0,Kinematic:1,Dynamic:2};let Be=0;function ze(e,t){const n=++Be;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function Ue(e){return{_type:"res",_resource:e}}function Le(e){return{_type:"res_mut",_resource:e}}class $e{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class De{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new $e(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Oe=ze({delta:0,elapsed:0,frameCount:0},"Time");function He(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=We(t[e]),o=We(i);"null"!==n&&"undefined"!==n&&(n!==o&&null!=i&&s.push({field:e,expected:n,actual:o,value:i}))}return s}function We(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Ve(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 Ne=null;function je(e){Ne=e}function Xe(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Ne&&Ne(e,t)}function Ye(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 qe=1;const Ge=new WeakMap;function Ke(e){let t=Ge.get(e);return void 0===t&&(t=qe++,Ge.set(e,t)),t}const Je=[];function Qe(e,t=[],n=[]){Je.length=0;for(const t of e)Je.push(Ke(t));Je.sort((e,t)=>e-t);let s=Je.join(",");if(t.length>0){Je.length=0;for(const e of t)Je.push(Ke(e));Je.sort((e,t)=>e-t),s+="|+"+Je.join(",")}if(n.length>0){Je.length=0;for(const e of n)Je.push(Ke(e));Je.sort((e,t)=>e-t),s+="|-"+Je.join(",")}return s}class Ze{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 Xe(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){Xe(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){Xe(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Xe(t,`removeParent(entity=${e})`)}}insert(e,t,n){return ne(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(ne(t)){if(this.cppRegistry_)try{const s=t._default,i=n;let o=i;for(const e of Object.keys(i))e in s||(o===i&&(o={...i}),delete o[e]);this.getBuiltinMethods(t._cppName).add(e,Ye(o))}catch(n){Xe(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 ne(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return ne(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(ne(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return Xe(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.");ne(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=t._default,i={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&e in s&&(i[e]=t);const e=He(t._name,s,i);if(e.length>0)throw new Error(Ve(t._name,e))}const o={...t._default,...i};let r=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);r=!n.has(e),n.add(e,Ye(o))}catch(n){Xe(n,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),o}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 Xe(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 Xe(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){Xe(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=He(t._name,t._default,e);if(i.length>0)throw new Error(Ve(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 se)if(ne(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=G();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??Qe(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(!ne(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 et(e){return{_type:"mut",_component:e}}function tt(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function nt(e){return{_filterType:"added",_component:e}}function st(e){return{_filterType:"changed",_component:e}}function it(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function ot(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function rt(e){return tt(e)||it(e)||ot(e)?e._component:e}function at(e,t=[],n=[]){const s=[],i=[],o=[];return e.forEach((e,t)=>{tt(e)&&s.push(t),it(e)?i.push({index:t,component:e._component}):ot(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:o,with:(...s)=>at(e,[...t,...s],n),without:(...s)=>at(e,t,[...n,...s])}}function lt(...e){return at(e)}class ct{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(rt),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_=Qe(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 ut(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 ht(){return{_type:"commands"}}class ft{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=ne(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 pt{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ft(this,null);return this.spawned_.push(e),e}entity(e){return new ft(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 mt(e){return{_id:Symbol(`Event_${e}`),_name:e}}class _t{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 gt{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new _t)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new _t,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 wt(e){return{_type:"event_reader",_event:e}}class xt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class vt{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var bt;function St(){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"}(bt||(bt={}));let Mt=0;function Tt(e,t,n){const s=++Mt;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Pt(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function Et(e){Pt().push({schedule:bt.Update,system:e})}function Ct(e){Pt().push({schedule:bt.Startup,system:e})}function At(e,t){Pt().push({schedule:e,system:t})}class Rt{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 pt&&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 ct(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 pt(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 xt(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new vt(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 It{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const kt=ze(new It,"Input");class Ft{constructor(e){this.target_=e??null}build(e){const n=new It;e.insertResource(kt,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(bt.Last,Tt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Bt=new Ft,zt=ze({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var Ut;function Lt(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"}(Ut||(Ut={}));let $t=null,Dt=null,Ot=1;const Ht=new Map;function Wt(e){$t=e,Dt=e.getResourceManager(),Qt()}function Vt(){0!==Yt&&$t&&($t._free(Yt),Yt=0),Ht.clear(),Ot=1,Xt=!1,Gt.clear(),Kt=null,Dt=null,$t=null}function Nt(){if(!Dt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Dt}const jt={createShader:(e,t)=>Nt().createShader(e,t),releaseShader(e){e>0&&Nt().releaseShader(e)},create(e){const t=Ot++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Ut.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 Ht.set(t,n),t},get:e=>Ht.get(e),setUniform(e,t,n){const s=Ht.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,$t?.invalidateMaterialCache(e))},getUniform(e,t){const n=Ht.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Ht.get(e);n&&(n.blendMode=t,$t?.invalidateMaterialCache(e))},getBlendMode(e){const t=Ht.get(e);return t?.blendMode??Ut.Normal},setDepthTest(e,t){const n=Ht.get(e);n&&(n.depthTest=t,$t?.invalidateMaterialCache(e))},getShader(e){const t=Ht.get(e);return t?.shader??0},release(e){Ht.delete(e),$t?.invalidateMaterialCache(e)},isValid:e=>Ht.has(e),releaseAll(){Ht.clear(),$t?.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??Ut.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ht.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Ot++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ht.set(n,s),n},toAssetData(e,t){const n=Ht.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=Ht.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Xt=!1,Yt=0;const qt=16384,Gt=new Map;let Kt=null;function Jt(e){const t=(0===Yt&&$t&&(Yt=$t._malloc(qt)),Yt);if(0===t||!$t)return{ptr:0,count:0};let n=0,s=0;const i=$t.HEAPU8,o=$t.HEAPU32,r=$t.HEAPF32;for(const[a,l]of e){if(Lt(l))continue;let e=Gt.get(a);e||(Kt||(Kt=new TextEncoder),e=Kt.encode(a),Gt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(n+(4+u+4+16)>qt){console.warn(`[ESEngine] Material uniform buffer full (${n}/${qt} bytes), skipping remaining uniforms`);break}o[t+n>>2]=c,n+=4,i.set(e,t+n),n+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)r[t+n>>2]=h[e],n+=4;s++}return{ptr:t,count:s}}function Qt(){if(!$t||Xt)return;$t.materialDataProvider=(e,t,n,s,i)=>{const o=Ht.get(e);if(!o)return $t.HEAPU32[t>>2]=0,$t.HEAPU32[n>>2]=0,$t.HEAPU32[s>>2]=0,void($t.HEAPU32[i>>2]=0);$t.HEAPU32[t>>2]=o.shader,$t.HEAPU32[n>>2]=o.blendMode;const{ptr:r,count:a}=Jt(o.uniforms);$t.HEAPU32[s>>2]=r,$t.HEAPU32[i>>2]=a},Xt=!0}const Zt={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 en{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 tn{constructor(e,t=""){this.cache_=new en,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&&(jt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())jt.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:jt.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 nn(e){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function sn(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 on=new Map;function rn(e){on.set(e.name,e)}function an(e){on.delete(e)}function ln(e){return on.get(e)}function cn(){on.clear()}const un=K("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function dn(e,t){const n=e.getEntitiesWithComponents([un]);for(const s of n){const n=e.get(s,un);if(!n.enabled||!n.playing||!n.clip)continue;const i=on.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,fe)){const t=i.frames[n.currentFrame],o=e.get(s,fe);o.texture=t.texture,t.uvOffset&&(o.uvOffset=t.uvOffset,o.uvScale=t.uvScale),e.insert(s,fe,o)}a&&e.insert(s,un,n)}}class hn{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 async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const n=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,n)}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}}}}hn.mixer_=null,hn.bufferCache_=new Map,hn.bgmHandle_=null,hn.bgmVolume_=1,hn.fadeAnimId_=0,hn.disposed_=!1;const fn=new Map,pn=new Map;function mn(e,t,n){fn.set(e,{width:t,height:n})}function _n(e){return fn.get(e)}function gn(){fn.clear()}function yn(e,t){pn.set(e,t)}function wn(e){return pn.get(e)}function xn(){pn.clear()}let vn=null;function bn(e){vn=e}function Sn(){vn=null}const Mn={initLayer(e,t,n,s,i){vn?.tilemap_initLayer(e,t,n,s,i)},destroyLayer(e){vn?.tilemap_destroyLayer(e)},setTile(e,t,n,s){vn?.tilemap_setTile(e,t,n,s)},getTile:(e,t,n)=>vn?vn.tilemap_getTile(e,t,n):0,fillRect(e,t,n,s,i,o){vn?.tilemap_fillRect(e,t,n,s,i,o)},setTiles(e,t){if(!vn)return;const n=t.byteLength,s=vn._malloc(n);new Uint16Array(vn.HEAPU8.buffer,s,t.length).set(t),vn.tilemap_setTiles(e,s,t.length),vn._free(s)},hasLayer:e=>!!vn&&vn.tilemap_hasLayer(e),submitLayer(e,t,n,s,i,o,r,a,l,c,u,d,h){vn?.tilemap_submitLayer(e,t,n,s,i,o,r,a,l,c,u,d,h)}},Tn=K("Tilemap",{source:""}),Pn=K("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[]});function En(e,t){if(0===e)return 0;let n=0;2147483648&e&&(n|=8192),1073741824&e&&(n|=16384),536870912&e&&(n|=32768);return(536870911&e)-t+1|n}function Cn(e){const t=e.width,n=e.height,s=e.tilewidth??0,i=e.tileheight??0;if(!(t&&n&&s&&i))return null;const o=e.tilesets,r=[],a=[];if(o)for(const e of o){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??s,tileHeight:e.tileheight??i,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const s=e.width??t,i=e.height??n,o=!1!==e.visible,r=e.data,l=new Uint16Array(s*i);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=En(r[t],e)}c.push({name:e.name??"",width:s,height:i,visible:o,tiles:l})}return{width:t,height:n,tileWidth:s,tileHeight:i,layers:c,tilesets:r}}function An(e,t){const n=e.lastIndexOf("/"),s=((n>=0?e.substring(0,n+1):"")+t).split("/"),i=[];for(const e of s)".."===e?i.pop():"."!==e&&""!==e&&i.push(e);return i.join("/")}async function Rn(e,t){const n=vn;if(!n)return null;const s=new TextEncoder,i=s.encode(e),o=n._malloc(i.byteLength);n.HEAPU8.set(i,o);const r=n.tiled_loadMap(o,i.byteLength);if(n._free(o),0===r)return null;try{const e=n.tiled_getExternalTilesetCount(r);for(let i=0;i<e;i++){const e=n.tiled_getExternalTilesetSource(r,i);if(!t)return n.tiled_freeMap(r),null;const o=await t(e),a=s.encode(o),l=n._malloc(a.byteLength);n.HEAPU8.set(a,l);const c=n.tiled_loadExternalTileset(r,i,l,a.byteLength);if(n._free(l),!c)return n.tiled_freeMap(r),null}if(!n.tiled_finalize(r))return n.tiled_freeMap(r),null;const i={width:n.tiled_getMapWidth(r),height:n.tiled_getMapHeight(r),tileWidth:n.tiled_getMapTileWidth(r),tileHeight:n.tiled_getMapTileHeight(r),layers:[],tilesets:[]},o=n.tiled_getLayerCount(r);for(let e=0;e<o;e++){const t=n.tiled_getLayerWidth(r,e),s=n.tiled_getLayerHeight(r,e),o=t*s,a=2*o,l=n._malloc(a);n.tiled_getLayerTiles(r,e,l,o);const c=new Uint16Array(o);c.set(new Uint16Array(n.HEAPU8.buffer,l,o)),n._free(l),i.layers.push({name:n.tiled_getLayerName(r,e),width:t,height:s,visible:n.tiled_getLayerVisible(r,e),tiles:c})}const a=n.tiled_getTilesetCount(r);for(let e=0;e<a;e++)i.tilesets.push({name:n.tiled_getTilesetName(r,e),image:n.tiled_getTilesetImage(r,e),tileWidth:n.tiled_getTilesetTileWidth(r,e),tileHeight:n.tiled_getTilesetTileHeight(r,e),columns:n.tiled_getTilesetColumns(r,e),tileCount:n.tiled_getTilesetTileCount(r,e)});return n.tiled_freeMap(r),i}catch{return n.tiled_freeMap(r),null}}function In(e,t,n){const s=[],i=t.tilesets[0];let o=0;for(const r of t.layers){if(!r.visible)continue;const a=e.spawn();e.insert(a,ue,{});const l=i?n.get(i.image)??0:0,c=i?.columns??1;e.insert(a,Pn,{width:r.width,height:r.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:o,tiles:Array.from(r.tiles)}),s.push(a),o++}return s}const kn=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"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}]]);function Fn(e,t){kn.set(e,t)}function Bn(e){const t=kn.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 zn(e){return kn.get(e)?.fields??[]}function Un(e){return kn.get(e)?.spine??null}const Ln=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function $n(e,t){Ln.set(e,t)}function Dn(e){return Ln.get(e)}function On(e,t){const n=Ln.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 Hn(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,Te,{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)On(i,n),jn(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 Wn(e,t){return Hn(e,t)}async function Vn(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 Nn.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=kn.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=[...Nn.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=kn.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=Hn(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 Nn=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),mn(r.handle,r.width,r.height)}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=nn(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);rn(sn(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 hn.preloadAll(s).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=Cn(await t.loadJson(e));if(!i)return void console.warn(`Failed to parse tilemap: ${e}`);const o=[];for(const r of i.tilesets){const i=An(e,r.image);let a=0;try{const e=n?`${n}/${i}`:`/${i}`,o=await t.loadTexture(e);a=o.handle,s.set(i,e),mn(o.handle,o.width,o.height)}catch(e){console.warn(`Failed to load tileset texture: ${i}`,e)}o.push({textureHandle:a,columns:r.columns})}yn(e,{tileWidth:i.tileWidth,tileHeight:i.tileHeight,layers:i.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(i),new Map}}]]);function jn(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=oe(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 Xn(e,t){const n=e.getEntitiesWithComponents([pe]);for(const s of n){const n=e.get(s,pe);n&&(n.aspectRatio=t,e.insert(s,pe,n))}}function Yn(e,t){const n=e.getEntitiesWithComponents([Te]);for(const s of n){const n=e.get(s,Te);if(n&&n.value===t)return s}return null}const qn=[{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},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0}],Gn={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"},Kn=new Map,Jn=new Set;for(const e of qn)for(const t of e.extensions)Kn.set(t,e),Jn.add(t);function Qn(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function Zn(e){return Kn.get(Qn(e))}function es(e){return Zn(e)?.editorType??"unknown"}function ts(e){return Zn(e)?.addressableType??null}function ns(e){for(const t of qn)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function ss(e){return Jn.has(e.toLowerCase())}function is(){return Jn}function os(e){return"string"==typeof e&&(!!e.includes("/")&&ss(Qn(e)))}function rs(){const e=[];for(const t of qn)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function as(){return rs().map(e=>({type:"suffix",value:e}))}function ls(e){return Gn[e.toLowerCase()]}function cs(e){const t=Zn(e);return t?.wechatPackInclude??!1}function us(e){const t=Zn(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 ds(e,t){for(const n of qn)n.editorType===e&&(n.buildTransform=t)}function hs(e){return Zn(e)?.buildTransform}class fs{constructor(e){this.textureCache_=new en,this.shaderCache_=new en,this.jsonCache_=new en,this.textCache_=new en,this.binaryCache_=new en,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new en,this.prefabCache_=new en,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(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 tn(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(),jt.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"===Zn(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),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=Zn(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 Bn(e.type)){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}const n=Un(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 Vn(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 jt.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 jt.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(us(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 ps=ze(null,"Assets");class ms{build(e){const t=e.wasmModule;t?e.insertResource(ps,new fs(t)):console.warn("AssetPlugin: No WASM module available")}}const _s=new ms;class gs{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 ys(e,t){const n=e.getResource(ps);n&&n.registerEmbeddedAssets(t)}async function ws(e,t,n){const{entities:s,rootId:i}=await vs(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 Vn(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 xs=10;async function vs(e,t,n,s,i,o=0){if(o>xs)throw new Error(`Prefab nesting depth exceeded ${xs}. 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 vs(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,d={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};bs(d.components,r),Ss(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 bs(e,t){for(const n of e){const e=Dn(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 Ss(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 Ms{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 ws(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Ts=ze(null,"Prefabs");class Ps{constructor(){this.name="PrefabsPlugin",this.dependencies=[ps]}build(e){const t=e.getResource(ps);e.insertResource(Ts,new Ms(e.world,t))}}const Es=new Ps;let Cs=null,As=0,Rs=0,Is=0;const ks=new Float32Array(256);function Fs(e){Cs=e,As=Cs._malloc(64),Rs=Cs._malloc(64),Is=Cs._malloc(1024)}function Bs(){Cs&&(As&&(Cs._free(As),As=0),Rs&&(Cs._free(Rs),Rs=0),Is&&(Cs._free(Is),Is=0)),Cs=null}function zs(){if(!Cs)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Cs}const Us={r:1,g:1,b:1,a:1},Ls={begin(e){const t=zs();try{t.HEAPF32.set(e,As/4),t.draw_begin(As)}catch(e){Xe(e,"Draw.begin")}},end(){try{zs().draw_end()}catch(e){Xe(e,"Draw.end")}},line(e,t,n,s=1){try{zs().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Xe(e,"Draw.line")}},rect(e,t,n,s=!0){try{zs().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Xe(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{zs().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Xe(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{zs().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Xe(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{zs().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Xe(e,"Draw.circleOutline")}},texture(e,t,n,s=Us){try{zs().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){Xe(e,"Draw.texture")}},textureRotated(e,t,n,s,i=Us){try{zs().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){Xe(e,"Draw.textureRotated")}},setLayer(e){zs().draw_setLayer(e)},setDepth(e){zs().draw_setDepth(e)},getDrawCallCount:()=>Cs?Cs.draw_getDrawCallCount():0,getPrimitiveCount:()=>Cs?Cs.draw_getPrimitiveCount():0,setBlendMode(e){zs().draw_setBlendMode(e)},setDepthTest(e){zs().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=zs();s.HEAPF32.set(n,Rs/4),s.draw_mesh(e,t,Rs)}catch(n){Xe(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=zs(),i=jt.get(t);if(!i)return;if(Ls.setBlendMode(i.blendMode),Ls.setDepthTest(i.depthTest),0===i.uniforms.size)return void Ls.drawMesh(e,i.shader,n);let o;if(s.HEAPF32.set(n,Rs/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,n]of i.uniforms){const s=Os(t);if(!(s<0)){if(Lt(n))ks[o++]=10,ks[o++]=s,ks[o++]=n.slot??e++,ks[o++]=n.textureId;else if("number"==typeof n)ks[o++]=1,ks[o++]=s,ks[o++]=n;else if(Array.isArray(n)){ks[o++]=n.length,ks[o++]=s;for(let e=0;e<n.length;e++)ks[o++]=n[e]}else"w"in n?(ks[o++]=4,ks[o++]=s,ks[o++]=n.x,ks[o++]=n.y,ks[o++]=n.z,ks[o++]=n.w):"z"in n?(ks[o++]=3,ks[o++]=s,ks[o++]=n.x,ks[o++]=n.y,ks[o++]=n.z):(ks[o++]=2,ks[o++]=s,ks[o++]=n.x,ks[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(ks.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void s.draw_mesh(e,i.shader,Rs);s.HEAPF32.set(i.cachedBuffer_.subarray(0,o),Is/4),s.draw_meshWithUniforms(e,i.shader,Rs,Is,o)}catch(n){Xe(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},$s={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},Ds=new Set;function Os(e){const t=$s[e];return void 0!==t?t:(Ds.has(e)||(Ds.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys($s).join(", ")}`)),-1)}const Hs=new Map;function Ws(e,t,n){Hs.set(e,{fn:t,scene:n??""})}function Vs(e){Hs.delete(e)}function Ns(){Hs.clear()}var js;!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"}(js||(js={}));let Xs=null,Ys=0,qs=0,Gs=0;function Ks(e){Xs=e,Ys=Xs._malloc(262144),qs=Xs._malloc(65536),Gs=Xs._malloc(256)}function Js(){Xs&&(Ys&&Xs._free(Ys),qs&&Xs._free(qs),Gs&&Xs._free(Gs),Ys=0,qs=0,Gs=0),Xs=null}function Qs(){if(!Xs)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Xs}const Zs={create(e){const t=Qs(),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,Ys/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,Gs,i).set(o),t.geometry_init(n,Ys,s,Gs,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,qs,s).set(e.indices),t.geometry_setIndices16(n,qs,s)}else{new Uint32Array(t.HEAPU8.buffer,qs,s).set(e.indices),t.geometry_setIndices32(n,qs,s)}}return n},updateVertices(e,t,n=0){const s=Qs(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,Ys/4),s.geometry_updateVertices(e,Ys,i,n)},release(e){e>0&&Qs().geometry_release(e)},isValid:e=>!(!Xs||e<=0)&&Xs.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Zs.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:js.Float2},{name:"a_texCoord",type:js.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 Zs.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:js.Float2},{name:"a_texCoord",type:js.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 Zs.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:js.Float2},{name:"a_texCoord",type:js.Float2}],indices:new Uint16Array(r)})}};let ei=null,ti=1;const ni=new Map,si=new Map;function ii(e){ei=e}function oi(){for(const e of ni.values())e.destroy();ni.clear(),si.clear(),ei&&li.isInitialized()&&li.shutdown(),ei=null}class ri{constructor(){this.passes_=[],this.destroyed_=!1,this.id=ti++,ni.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}setEnabled(e,t){const n=this.passes_.find(t=>t.name===e);return n&&(n.enabled=t),this}setUniform(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.floatUniforms.set(t,n),this}setUniformVec4(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.vec4Uniforms.set(t,{...n}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of si)t===this&&si.delete(e);ni.delete(this.id)}}}function ai(){if(!ei)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return ei}const li={createStack:()=>new ri,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");si.set(e,t)},unbind(e){si.delete(e)},getStack:e=>si.get(e)??null,init(e,t){try{return ai().postprocess_init(e,t)}catch(n){return Xe(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{ai().postprocess_shutdown()}catch(e){Xe(e,"PostProcess.shutdown")}},resize(e,t){try{ai().postprocess_resize(e,t)}catch(n){Xe(n,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!ei)return!1;try{return ei.postprocess_isInitialized()}catch(e){return Xe(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{ai().postprocess_setBypass(e)}catch(e){Xe(e,"PostProcess.setBypass")}},setOutputViewport(e,t,n,s){try{ai().postprocess_setOutputViewport(e,t,n,s)}catch(e){Xe(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=si.get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(li.isInitialized()||li.init(1,1),li.setBypass(!1),function(e){const t=ai();try{t.postprocess_clearPasses()}catch(e){return void Xe(e,"PostProcess._applyForCamera:clearPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addPass(n.name,n.shader)}catch(e){Xe(e,`PostProcess._applyForCamera:addPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setUniformFloat(n.name,e,s)}catch(t){Xe(t,`PostProcess._applyForCamera:setUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){Xe(t,`PostProcess._applyForCamera:setUniformVec4("${n.name}", "${e}")`)}}}(t)):li.setBypass(!0)},_resetAfterCamera(){try{ai().postprocess_clearPasses(),ai().postprocess_setBypass(!0)}catch(e){Xe(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of si.keys())e(t)||si.delete(t)},createBlur:()=>jt.createShader(ci,"#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:()=>jt.createShader(ci,"#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:()=>jt.createShader(ci,"#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"),createBloom:()=>jt.createShader(ci,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_threshold;\nuniform float u_intensity;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 texelSize = 1.0 / u_resolution;\n\n vec3 bloom = vec3(0.0);\n float total = 0.0;\n for (float x = -3.0; x <= 3.0; x += 1.0) {\n for (float y = -3.0; y <= 3.0; y += 1.0) {\n vec2 offset = vec2(x, y) * texelSize * u_radius;\n vec4 s = texture(u_texture, v_texCoord + offset);\n float brightness = dot(s.rgb, vec3(0.2126, 0.7152, 0.0722));\n float w = max(brightness - u_threshold, 0.0);\n bloom += s.rgb * w;\n total += w;\n }\n }\n if (total > 0.0) bloom /= total;\n\n fragColor = vec4(color.rgb + bloom * u_intensity, color.a);\n}\n"),createChromaticAberration:()=>jt.createShader(ci,"#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")},ci="#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",ui=new Map;function di(e){ui.set(e.type,e)}function hi(e){return ui.get(e)}function fi(){return Array.from(ui.keys())}function pi(){return Array.from(ui.values())}di({type:"blur",label:"Blur",factory:()=>li.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),di({type:"bloom",label:"Bloom",factory:()=>li.createBloom(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:2,step:.01,defaultValue:.8},{name:"u_intensity",label:"Intensity",min:0,max:10,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:0,max:20,step:.1,defaultValue:4}]}),di({type:"vignette",label:"Vignette",factory:()=>li.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:3,step:.01,defaultValue:.8},{name:"u_softness",label:"Softness",min:0,max:2,step:.01,defaultValue:.3}]}),di({type:"grayscale",label:"Grayscale",factory:()=>li.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),di({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>li.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const mi=new Map,_i=new Map;function gi(e,t){let n=mi.get(e),s=_i.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(n||(n=li.createStack(),mi.set(e,n)),s||(s=new Map,_i.set(e,s));n.passCount>0;){const e=n.passes;n.removePass(e[e.length-1].name)}for(const e of i){const t=hi(e.type);if(!t)continue;let i=s.get(e.type);void 0===i&&(i=t.factory(),s.set(e.type,i)),n.addPass(e.type,i);for(const s of t.uniforms){const t=e.uniforms[s.name]??s.defaultValue;n.setUniform(e.type,s.name,t)}}li.bind(e,n)}else if(n&&(li.unbind(e),n.destroy(),mi.delete(e)),s){for(const e of s.values())jt.releaseShader(e);_i.delete(e)}}function yi(e){const t=mi.get(e);t&&(li.unbind(e),t.destroy(),mi.delete(e));const n=_i.get(e);if(n){for(const e of n.values())jt.releaseShader(e);_i.delete(e)}}function wi(){for(const e of mi.keys())yi(e)}var xi;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(xi||(xi={}));let vi=null,bi=0;function Si(e){vi=e,bi=vi._malloc(64)}function Mi(){vi&&bi&&(vi._free(bi),bi=0),vi=null}const Ti={init(e,t){vi?.renderer_init(e,t)},resize(e,t){vi?.renderer_resize(e,t)},begin(e,t){if(vi&&bi)try{vi.HEAPF32.set(e,bi/4),vi.renderer_begin(bi,t??0)}catch(e){Xe(e,"Renderer.begin")}},flush(){try{vi?.renderer_flush()}catch(e){Xe(e,"Renderer.flush")}},end(){try{vi?.renderer_end()}catch(e){Xe(e,"Renderer.end")}},submitSprites(e){if(vi)try{vi.renderer_submitSprites(e._cpp)}catch(e){Xe(e,"Renderer.submitSprites")}},submitBitmapText(e){if(vi)try{vi.renderer_submitBitmapText(e._cpp)}catch(e){Xe(e,"Renderer.submitBitmapText")}},submitSpine(e){if(vi)try{vi.renderer_submitSpine?.(e._cpp)}catch(e){Xe(e,"Renderer.submitSpine")}},submitParticles(e){if(vi)try{vi.renderer_submitParticles?.(e._cpp)}catch(e){Xe(e,"Renderer.submitParticles")}},setStage(e){vi?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>vi?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){vi?.renderer_releaseTarget(e)},getTargetTexture:e=>vi?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>vi?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){vi?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){vi?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){vi?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){vi?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>vi?vi.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>vi?{drawCalls:vi.renderer_getDrawCalls(),triangles:vi.renderer_getTriangles(),sprites:vi.renderer_getSprites(),text:vi.renderer_getText(),spine:vi.renderer_getSpine?.()??0,meshes:vi.renderer_getMeshes(),culled:vi.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Pi=null;function Ei(e){Pi=e}function Ci(){Pi=null}const Ai={enable(){Pi?.gl_enableErrorCheck(!0)},disable(){Pi?.gl_enableErrorCheck(!1)},check:e=>Pi?.gl_checkErrors(e)??0,diagnose(){Pi?.renderer_diagnose()}};class Ri{constructor(){this.spineRenderer_=null,this.tilemapRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}setTilemapRenderer(e){this.tilemapRenderer_=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),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),this.tilemapRenderer_&&this.tilemapRenderer_(),Ti.submitSprites(t),Ti.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ti.submitSpine(t),Ti.submitParticles(t),Ti.flush(),this.executeDrawCallbacks(n,o),Ti.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==li.getStack(r);a&&(li._applyForCamera(r),li.resize(s.w,s.h),li.setOutputViewport(s.x,s.y,s.w,s.h)),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),this.tilemapRenderer_&&this.tilemapRenderer_(),Ti.submitSprites(t),Ti.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ti.submitSpine(t),Ti.submitParticles(t),Ti.flush(),this.executeDrawCallbacks(n,o),Ti.end(),a&&li._resetAfterCamera()}executeDrawCallbacks(e,t){const n=Hs;if(n.size>0){Ls.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)}Ls.end();for(const e of s)Vs(e)}}}const Ii="__scene_transition_overlay__";class ki{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class Fi{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,Pe,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),Ws(e,t,this.instance_.config.name)}bindPostProcess(e,t){li.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){li.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,Pe)){const n=this.app_.world.get(e,Pe);n.persistent=t,this.app_.world.insert(e,Pe,n)}}}class Bi{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}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())Vs(t);for(const t of e.postProcessBindings.keys())li.unbind(t)}this.transition_&&(Vs(Ii),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}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??F.sceneTransitionDuration,i=t.color??{...F.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},Ws(Ii,()=>{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;Ls.setLayer(9999),Ls.setDepth(9999),Ls.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,Vs(Ii),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Vs(Ii),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 ki(t);this.scenes_.set(e,n);const s=new Fi(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(ps)?this.app_.getResource(ps):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 ki(t);this.scenes_.set(e,n);const s=new Fi(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(ps)?this.app_.getResource(ps):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,Pe)){if(this.app_.world.get(e,Pe).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())Vs(e);n.drawCallbacks.clear();for(const e of n.postProcessBindings.keys())li.unbind(e);n.postProcessBindings.clear(),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(ps)&&(i.assetServer=this.app_.getResource(ps));const o=await Vn(this.app_.world,s,i);e.loadedAssets=n;for(const n of o.values())e.entities.add(n),this.app_.world.insert(n,Pe,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=Ui(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(ps)?this.app_.getResource(ps):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)jt.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,fe)){const t=n.get(e,fe);s.sprite=t.color.a,t.color.a=0,n.insert(e,fe,t),i=!0}if(n.has(e,xe)){const t=n.get(e,xe);s.spine=t.color.a,t.color.a=0,n.insert(e,xe,t),i=!0}if(n.has(e,we)){const t=n.get(e,we);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,we,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,fe)){const t=n.get(e,fe);t.color.a=s.sprite,n.insert(e,fe,t)}if(void 0!==s.spine&&n.has(e,xe)){const t=n.get(e,xe);t.color.a=s.spine,n.insert(e,xe,t)}if(void 0!==s.bitmapText&&n.has(e,we)){const t=n.get(e,we);t.color.a=s.bitmapText,n.insert(e,we,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessBindings.values())n.setAllPassesEnabled(t)}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 zi=ze(null,"SceneManager");function Ui(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(zi).getSceneStatus(t)&&n._fn(...s)}}}const Li=Tt([Le(zi),Ue(Oe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),$i={name:"SceneManager",build(e){const t=new Bi(e);e.insertResource(zi,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(zi),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(bt.Startup,n),e.addSystemToSchedule(bt.Last,Li)}};class Di{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 gt,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 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(bt.Last);else{this.runSchedule(bt.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(bt.FixedPreUpdate),this.runSchedule(bt.FixedUpdate),this.runSchedule(bt.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(bt.PreUpdate),this.runSchedule(bt.Update),this.runSchedule(bt.PostUpdate),this.runSchedule(bt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new Ze,this.resources_=new De;for(const e of Object.values(bt))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Di}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(bt.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(bt.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 je(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(zi).register(e),this}setInitialScene(e){return this.getResource(zi).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new Rt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(Oe)||this.resources_.insert(Oe,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(bt.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(bt.Last);else{this.runSchedule(bt.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(bt.FixedPreUpdate),this.runSchedule(bt.FixedUpdate),this.runSchedule(bt.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(bt.PreUpdate),this.runSchedule(bt.Update),this.runSchedule(bt.PostUpdate),this.runSchedule(bt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new Rt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(Oe,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(bt.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1,Ns();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=[Ci,Mi,oi,Js,Vt,Bs];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(bt[e],performance.now()-s)}updateTime(e){const t=this.resources_.get(Oe);t.delta=e,t.elapsed+=e,t.frameCount++}}function Oi(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 Hi=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Wi(e,t,n,s,i){const o=e*t/n,r=e;switch(s){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 Vi=[];function Ni(e){if(e<Vi.length)return Vi[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 Vi.push(t),t}function ji(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,Pe);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,d=0;if(i.projectionType===ae.Orthographic){if(d=i.orthoSize,l){d=Wi(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=d*r,a=Yi(-u,u,-d,d,-i.farPlane,i.farPlane)}else a=Gi(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const h=Ji(o.position.x,o.position.y,o.position.z),f=Ni(c.length);f.entity=e,f.viewProjection.set(Zi(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 Yi(e,t,n,s,i,o){const r=Xi;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 qi=new Float32Array(16);function Gi(e,t,n,s){const i=qi;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 Ki=new Float32Array(16);function Ji(e,t,n){const s=Ki;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 Qi=new Float32Array(16);function Zi(e,t){const n=Qi;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 eo={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function to(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,d=o.bottom+e.y*l,h=o.bottom+t.y*l;let f,p,m,_;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=d+n.y-i.y*r.y,_=p+i.y):(p=d+n.y,_=h+s.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 no=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 so=null,io=null;function oo(e,t){e.has(t,fe)||e.insert(t,fe,{texture:$,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 ro(e,t){switch(e){case eo.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case eo.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case eo.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 ao(e,t){switch(e){case eo.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case eo.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case eo.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 lo(e,t,n,s){switch(e){case eo.BottomToTop:case eo.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function co(e,t,n,s){if(!e.has(t,no))return;const i=e.get(t,no),o=ro(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,no,i)}function uo(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function ho(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function fo(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(ho(r.charCodeAt(0))&&s.length>0&&ho(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!ho(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 po(e){let t=1;for(;t<e;)t*=2;return t}function mo(e,t){let n=0,s=t;for(;e.has(s,ge);){const t=e.get(s,ge).entity;if(!e.valid(t))break;n++,s=t}return n}function _o(e,t){if(so&&io){const e=so.getUIRectComputedWidth(io,t);if(e>0)return e}return e.size.x}function go(e,t){if(so&&io){const e=so.getUIRectComputedHeight(io,t);if(e>0)return e}return e.size.y}function yo(e,t,n,s,i,o){if(!e.has(t,fe))return;const r=e.get(t,fe);let a,l;switch(n){case eo.BottomToTop:case eo.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,fe,r))}function wo(e,t,n){let s=t;for(;e.has(s,ge);){const t=e.get(s,ge).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function xo(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function vo(e,t,n,s,i){if(!e.has(t,no))return;const o=e.get(t,no),r=to(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,fe)){const n=e.get(t,fe);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,fe,n))}if(e.has(t,ue)){const n=e.get(t,ue);n.position.x=r.originX-s,n.position.y=r.originY-i,e.insert(t,ue,n)}}function bo(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 So=.1,Mo=30,To={r:.3,g:.5,b:.8,a:1},Po={Left:0,Center:1,Right:2},Eo={Top:0,Middle:1,Bottom:2},Co={Visible:0,Clip:1,Ellipsis:2},Ao=K("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Po.Left,verticalAlign:Eo.Top,wordWrap:!0,overflow:Co.Visible,lineHeight:1.2});class Ro{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=d(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,po(this.frameMaxW_)),e.height=Math.max(e.height,po(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=po(this.frameMaxW_),e.height=po(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=fo(n,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===Co.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),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,po(f)),s.height=Math.max(s.height,po(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;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===Co.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 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 s;switch(e.align){case Po.Left:s=u;break;case Po.Center:s=f/2;break;case Po.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=c}i&&e.overflow===Co.Clip&&n.restore();const b=n.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),M=this.module.getResourceManager(),T=this.module._malloc(S.length);this.module.HEAPU8.set(S,T);const P=M.createTexture(f,p,T,S.length,1,!0);return this.module._free(T),{textureHandle:P,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 Po.Left:return"left";case Po.Center:return"center";case Po.Right:return"right"}}}const Io=bo({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?_o(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?go(e.uiRect,e.entity):0});class ko{build(e){ie("Text",Ao);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Ro(t),s=e.world,i=new Map;e.addSystemToSchedule(bt.PreUpdate,Tt([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Ao));for(const e of i.keys())if(!s.valid(e)||!s.has(e,Ao)){if(s.valid(e)&&s.has(e,fe)){const t=s.get(e,fe);s.insert(e,fe,{texture:$,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([Ao]);for(const t of e){const e=s.get(t,Ao),o=s.has(t,no)?s.get(t,no):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!Io.changed(a,r)){if(s.has(t,fe)&&s.get(t,fe).texture!==$)continue}oo(s,t);const l=o?{size:{x:_o(o,t),y:go(o,t)}}:null,c=n.renderForEntity(t,e,l),u=s.get(t,fe);s.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,Io.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Fo=new ko,Bo=0,zo=1,Uo=re("UIMask",{enabled:!0,mode:Bo});function Lo(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 $o(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],d=e[8],h=e[9],f=e[10],p=e[11],m=e[12],_=e[13],g=e[14],y=e[15],w=s*l-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,T=d*_-h*m,P=d*g-f*m,E=d*y-p*m,C=h*g-f*_,A=h*y-p*_,R=f*y-p*g;let I=w*R-x*A+v*C+b*E-S*P+M*T;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]=(_*M-g*S+y*b)*I,n[3]=(f*S-h*M-p*b)*I,n[4]=(c*E-a*R-u*P)*I,n[5]=(s*R-o*E+r*P)*I,n[6]=(g*v-m*M-y*x)*I,n[7]=(d*M-f*v+p*x)*I,n[8]=(a*A-l*E+u*T)*I,n[9]=(i*E-s*A-r*T)*I,n[10]=(m*S-_*v+y*w)*I,n[11]=(h*v-d*S-p*w)*I,n[12]=(l*P-a*C-c*T)*I,n[13]=(s*C-i*P+o*T)*I,n[14]=(_*x-m*b-g*w)*I,n[15]=(d*b-h*x+f*w)*I),n}function Do(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],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:u/d}}function Oo(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 Ho(e,t){return 2*Math.atan2(e,t)}function Wo(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 Vo(e,t,n,s,i,o,r,a,l,c){const u=Ho(l,c),d=Math.sin(-u),h=Math.cos(-u),f=e-n,p=t-s,m=f*h-p*d+n,_=f*d+p*h+s;return m>=n-i*r&&m<=n+i*(1-r)&&_>=s-o*a&&_<=s+o*(1-a)}function No(e,t,n,s,i,o,r){if(!e.has(t,no)||!e.has(t,ue))return null;const a=e.get(t,no),l=e.get(t,ue),c=_o(a,t)*l.worldScale.x,u=go(a,t)*l.worldScale.y,d=l.worldPosition.x,h=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=Ho(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[d+m*x-g*v,h+m*v+g*x],[d+_*x-g*v,h+_*v+g*x],[d+_*x-y*v,h+_*v+y*x],[d+m*x-y*v,h+m*v+y*x]];let S=1/0,M=1/0,T=-1/0,P=-1/0;for(const[e,t]of b){const[a,l]=Wo(e,t,n,s,i,o,r);S=Math.min(S,a),M=Math.min(M,l),T=Math.max(T,a),P=Math.max(P,l)}return{x:Math.round(S),y:Math.round(M),w:Math.round(T-S),h:Math.round(P-M)}}function jo(e,t){return(n,s,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Uo]);if(0===l.length)return;const c=[],u=[],d=new Set,h=new Set;for(const e of l){const n=t.get(e,Uo);n.enabled&&(d.add(e),n.mode===zo?(u.push(e),h.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;wo(t,e,e=>{if(i.has(e)){if(t.get(e,Uo).mode===Bo)return n=!1,!0}return!1}),n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(i.has(n)){if(t.get(n,Uo).mode===Bo){const e=No(t,n,o,r,a,l,c);e&&(s=Lo(u,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=No(t,e,o,r,a,l,c);n&&d(e,n)}}(e,t,n,c,d,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;wo(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,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class Xo{build(e){if(ie("UIMask",Uo),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(jo(e.wasmModule,e.world))}}const Yo=new Xo,qo=re("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),Go=re("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Ko={Normal:0,Hovered:1,Pressed:2,Disabled:3},Jo=K("Button",{state:Ko.Normal,transition:null});class Qo{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 Zo=ze(new Qo,"UIEvents");class er{build(e){ie("UIRect",no);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){so=e,io=t}(n,s);e.addSystemToSchedule(bt.PreUpdate,Tt([Ue(zt)],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(bt.PostUpdate,Tt([Ue(zt)],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(bt.PostUpdate,Tt([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const tr=new er;let nr=!1,sr=!1;function ir(e){nr=e}function or(){return nr}function rr(){return!nr}function ar(e){sr=e}function lr(){return sr}const cr=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&&($o(t,e),n=!1),e)}}();function ur(e,t,n,s){t.emit(n,s,n),wo(e,n,i=>{if(!e.has(i,qo))return!1;const o=e.get(i,qo);return o.enabled&&t.emit(i,s,n),o.blockRaycast})}class dr{build(e){ie("Interactable",qo),ie("Button",Jo);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new Qo;e.insertResource(Zo,i);let o=null,r=null;e.addSystemToSchedule(bt.PreUpdate,Tt([Ue(kt),Ue(zt)],(e,a)=>{if(i.drain(),or()&&!lr())return;const l=t.getEntitiesWithComponents([Go]);for(const e of l){const n=t.get(e,Go);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,Go,n))}if(!a.valid)return;const c=f(),u=e.mouseX*c,d=a.screenH-e.mouseY*c;cr.update(a.viewProjection);const h=Do(u,d,cr.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),_=e.isMouseButtonReleased(0);n.uiHitTest_update(s,h.x,h.y,p,m,_);const g=n.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,Go)){const e=t.get(o,Go);e.hovered=!1,t.insert(o,Go,e),i.emit(o,"hover_exit")}if(null!==y){xo(t,y,Go);const e=t.get(y,Go);e.hovered=!0,t.insert(y,Go,e),i.emit(y,"hover_enter")}o=y}if(m&&null!==y){const e=t.get(y,Go);e.pressed=!0,e.justPressed=!0,t.insert(y,Go,e),r=y,ur(t,i,y,"press")}if(_&&null!==r){if(t.valid(r)&&t.has(r,Go)){const e=t.get(r,Go);e.pressed=!1,e.justReleased=!0,t.insert(r,Go,e),ur(t,i,r,"release"),r===o&&ur(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(bt.Update,Tt([],()=>{const e=t.getEntitiesWithComponents([Jo]);for(const n of e){if(xo(t,n,qo,{enabled:!0}),!t.has(n,Go))continue;const e=t.get(n,Go),s=t.get(n,Jo),i=t.get(n,qo),o=!a.has(n),r=s.state;if(i.enabled?e.pressed?s.state=Ko.Pressed:e.hovered?s.state=Ko.Hovered:s.state=Ko.Normal:s.state=Ko.Disabled,o&&a.add(n),(o||r!==s.state)&&s.transition&&t.has(n,fe)){const o=t.get(n,fe);o.color=uo(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,fe,o)}}},{name:"ButtonSystem"}))}}const hr=new dr,fr=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}),pr=K("Focusable",{tabIndex:0,isFocused:!1});class mr{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 _r=ze(new mr,"FocusManager");class gr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(ie("TextInput",fr),or()&&!lr())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,i=d(F.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(_r);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,fr)?s:null}const _=()=>{l||null===m()||v()},g=()=>{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,fr);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(Zo).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,fr);s.focused=!1,s.dirty=!0;e.getResource(_r).blur()}};function v(){const t=m();if(null===t)return;const s=n.get(t,fr);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(Zo).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,fr);e.focused=!1,e.dirty=!0}e.getResource(_r).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 s.values())e.releaseTexture(t);s.clear(),0!==r&&(t._free(r),r=0,a=0)};let M=null;function T(e,l,u,d){(i.width<u||i.height<d)&&(i.width=po(Math.max(i.width,u)),i.height=po(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 _=Math.ceil(1.2*l.fontSize),g=l.padding;if(l.multiline){const e=fo(o,p,u-2*g);let t=g;for(const n of e)o.fillText(n,g,t),t+=_}else{const e=(d-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,n,s;if(l.multiline){const e=fo(o,l.value,u-2*g);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=g+o.measureText(c).width,n=g+r*_,s=_}else t=g+o.measureText(e).width,n=(d-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,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=s.get(e);void 0!==v&&x.releaseTexture(v);const b=x.createTexture(u,d,r,w.length,1,!0);s.set(e,b);const S=n.get(e,fe);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},n.insert(e,fe,S)}e.addSystemToSchedule(bt.Update,Tt([Ue(_r)],e=>{const t=n.getEntitiesWithComponents([fr]);for(const e of t)xo(n,e,pr,{tabIndex:0,isFocused:!1}),xo(n,e,qo,{enabled:!0,blockRaycast:!0});const s=m();if(s!==M){if(null!==M&&n.valid(M)&&n.has(M,fr)){const e=n.get(M,fr);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,fr);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(bt.PreUpdate,Tt([],()=>{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;n.get(o,fr).dirty=!0}const r=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,fr)||(r.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([fr,no]);for(const e of a){const t=n.get(e,fr);if(!t.dirty)continue;const s=n.get(e,no),i=Math.ceil(s.size.x),o=Math.ceil(s.size.y);i<=0||o<=0||(oo(n,e),T(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const yr=new gr,wr={Simple:0,Sliced:1,Tiled:2,Filled:3},xr={Horizontal:0,Vertical:1},vr={Left:0,Right:1,Bottom:2,Top:3},br=K("Image",{texture:$,color:{r:1,g:1,b:1,a:1},imageType:wr.Simple,fillMethod:xr.Horizontal,fillOrigin:vr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Sr=bo({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?_o(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?go(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class Mr{build(e){ie("Image",br);const t=e.world,n=new Map;e.addSystemToSchedule(bt.PreUpdate,Tt([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,br)||n.delete(e);const e=t.getEntitiesWithComponents([br]);for(const s of e){const e=t.get(s,br),i=t.has(s,no)?t.get(s,no):null,o={image:e,uiRect:i,entity:s},r=n.get(s);if(r&&!Sr.changed(r,o))continue;oo(t,s);const a=t.get(s,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=_o(i,s),a.size.y=go(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===wr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===xr.Horizontal?e.fillOrigin===vr.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===vr.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===wr.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,fe,a),n.set(s,Sr.take(o))}else a.color.a=0,t.insert(s,fe,a),n.set(s,Sr.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const Tr=new Mr,Pr=K("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Er=K("ToggleGroup",{allowSwitchOff:!1});class Cr{build(e){ie("Toggle",Pr),ie("ToggleGroup",Er);const t=e.world,n=new Set;e.addSystemToSchedule(bt.Update,Tt([Ue(Zo)],e=>{const s=t.getEntitiesWithComponents([Pr]);if(!or()||lr()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,Pr);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,Pr,s)):i.set(s.group,e))}const o=new Map;for(const e of s){const n=t.get(e,Pr);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(xo(t,n,qo,{enabled:!0}),!t.has(n,Go))continue;const s=t.get(n,Go),i=t.get(n,Pr),r=t.get(n,qo);if(s.justPressed&&r.enabled){const s=i.group,r=0!==s&&t.valid(s)&&t.has(s,Er);if(i.isOn&&r){if(!t.get(s,Er).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,Pr,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,Pr);i.isOn&&(i.isOn=!1,t.insert(s,Pr,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,fe)){const e=t.get(n,fe);e.color=uo(i.transition,r.enabled,s.pressed,s.hovered),t.insert(n,fe,e)}}}for(const e of s){const n=t.get(e,Pr);if(n.graphicEntity&&t.valid(n.graphicEntity)&&t.has(n.graphicEntity,fe)){const e=t.get(n.graphicEntity,fe);e.enabled=n.isOn,t.insert(n.graphicEntity,fe,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const Ar=new Cr,Rr=eo,Ir=K("ProgressBar",{value:0,fillEntity:0,direction:eo.LeftToRight});function kr(e,t,n,s){if(!e.has(t,no))return;const i=e.get(t,no),o=n/2,r=s/2,a={left:-o,bottom:-r,right:o,top:r},l=to(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,fe)){const n=e.get(t,fe);n.size.x===l.width&&n.size.y===l.height||(n.size.x=l.width,n.size.y=l.height,e.insert(t,fe,n))}if(e.has(t,ue)){const n=e.get(t,ue),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,ue,n))}}class Fr{build(e){ie("ProgressBar",Ir);const t=e.world;e.addSystemToSchedule(bt.PreUpdate,Tt([],()=>{const e=t.getEntitiesWithComponents([Ir,no]);for(const n of e){const e=t.get(n,Ir);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,no),i=Math.max(0,Math.min(1,e.value));co(t,e.fillEntity,e.direction,i);const o=_o(s,n),r=go(s,n);kr(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Br=new Fr,zr=K("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Ur=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 Lr{build(e){ie("Draggable",zr),ie("DragState",Ur);const t=e.world,n=e.getResource(Zo);let s=null,i={x:0,y:0},o=null;e.addSystemToSchedule(bt.PreUpdate,Tt([Ue(kt),Ue(zt)],(e,r)=>{if(or()&&!lr())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([zr,Go]);let n=null,o=-1/0,r=-1;for(const s of e){if(!t.get(s,zr).enabled)continue;if(t.get(s,Go).hovered){let e=0;t.has(s,fe)&&(e=t.get(s,fe).layer);const i=mo(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,Ur)||t.insert(n,Ur);const e=t.get(n,Ur),o=t.get(n,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!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,Ur)){t.get(s,Ur).isDragging=!1}s=null}if(null!==s&&null===o){if(!t.valid(s))return void(s=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),u=t.get(s,zr);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=s,s=null;t.get(o,Ur).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Ur))return void(o=null);const s=t.get(o,Ur),i=t.get(o,zr),r=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+r,u=s.startWorldPos.y+l;const d=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=d.x,u=d.y;const h=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-h,y:u-f},s.currentWorldPos={x:c,y:u},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:u-s.startWorldPos.y},t.has(o,ue)){const e=function(e,t,n,s){if(!e.has(t,ge))return{x:n,y:s};const i=e.get(t,ge).entity;if(!e.valid(i)||!e.has(i,ue))return{x:n,y:s};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=Ho(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,ue);n.position.x+=e.x,n.position.y+=e.y,t.insert(o,ue,n)}n.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}}const $r=new Lr,Dr=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 Or(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 Hr(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 Wr{build(e){ie("ScrollView",Dr);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(bt.PostUpdate,Tt([Ue(kt),Ue(zt),Ue(Oe)],(e,i,o)=>{const r=or()&&!lr(),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([Dr,no]);for(const o of l){xo(t,o,Uo,{enabled:!0,mode:Bo});const l=t.get(o,Dr),c=t.get(o,no);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 d=_o(c,o),h=go(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 n=0,s=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,no)){const e=t.get(r,no);a=_o(e,r)||e.size.x,l=go(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 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<n&&(n=d),h>s&&(s=h),f<i&&(i=f),p>o&&(o=p)}0===f&&(f=s-n),0===p&&(p=o-i)}const m=Math.max(0,f-d),_=Math.max(0,p-h);if(!r&&i.valid){xo(t,o,qo,{enabled:!0,blockRaycast:!0});const n=t.has(o,Go)?t.get(o,Go):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=Or(l.scrollX,0,m,d);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=Or(l.scrollY,0,_,h);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*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(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=Or(l.scrollY,0,_,h);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Or(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>_;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=Hr(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)<So&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>So?(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=Hr(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)<So&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>So?(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*d,t=.5*h;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),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,ue,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const Vr=new Wr,Nr=eo,jr=K("Slider",{value:0,minValue:0,maxValue:1,direction:eo.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function Xr(e,t,n,s,i,o){const r=_o(s,i)*n.worldScale.x,a=go(s,i)*n.worldScale.y,l=Ho(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),d=e-n.worldPosition.x,h=t-n.worldPosition.y,f=d*u-h*c,p=d*c+h*u,m=-s.pivot.x*r,_=-s.pivot.y*a;switch(o){case eo.LeftToRight:return r>0?(f-m)/r:0;case eo.RightToLeft:return r>0?1-(f-m)/r:0;case eo.BottomToTop:return a>0?(p-_)/a:0;case eo.TopToBottom:return a>0?1-(p-_)/a:0}}function Yr(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case eo.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case eo.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case eo.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case eo.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class qr{build(e){ie("Slider",jr);const t=e.world;let n=null;e.addSystemToSchedule(bt.PreUpdate,Tt([Ue(kt),Ue(zt),Ue(Zo)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const o=t.getEntitiesWithComponents([jr,no]);for(const r of o){const o=t.get(r,jr),a=t.get(r,no);if(!or()||lr()){if(t.has(r,ue)){xo(t,r,qo,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&xo(t,o.handleEntity,qo,{enabled:!0,blockRaycast:!1});const l=t.get(r,ue),c=t.has(r,Go)?t.get(r,Go):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Go)&&(u=t.get(o.handleEntity,Go).justPressed),u&&(n=r),n===r&&e.isMouseButtonDown(0)){let e=Xr(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,jr,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=_o(a,r),d=go(a,r),h={left:-u/2,bottom:-d/2,right:u/2,top:d/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(co(t,o.fillEntity,o.direction,c),vo(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,no)){const e=t.get(o.handleEntity,no);Yr(e,o.direction,c),t.insert(o.handleEntity,no,e),vo(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Gr=new qr;class Kr{build(e){ie("Focusable",pr);const t=e.world,n=new mr;e.insertResource(_r,n),e.addSystemToSchedule(bt.Update,Tt([Ue(kt),Ue(Zo)],(e,s)=>{if(or()&&!lr())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([pr]);for(const e of i){if(!t.has(e,Go))continue;t.get(e,Go).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,qo)){if(!t.get(n,qo).enabled)continue}const s=t.get(n,pr);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,pr)){t.get(i,pr).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,pr).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const Jr=new Kr,Qr=K("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function Zr(){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 ea{build(e){ie("SafeArea",Qr);const t=e.world;let n=Zr(),s=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=Zr(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=Zr(),s=!0});e.addSystemToSchedule(bt.PreUpdate,Tt([Ue(zt)],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([Qr,no]);for(const e of u){const s=t.get(e,Qr),i=t.get(e,no),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,no,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const ta=new ea,na=K("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let sa=null;function ia(e,t){if(!sa)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=sa.get(e);n?n.renderer=t:sa.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}class oa{build(e){ie("ListView",na);const t=e.world,n=new Map;sa=n,e.addSystemToSchedule(bt.PostUpdate,Tt([Ue(kt)],e=>{const s=or()&&!lr();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([na,no]);for(const o of i){xo(t,o,qo,{enabled:!0,blockRaycast:!0}),xo(t,o,Uo,{enabled:!0,mode:Bo});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,na),a=t.get(o,no),l=go(a,o),c=_o(a,o);if(!s){const n=t.has(o,Go)?t.get(o,Go):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 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,n]of i.itemEntities)(e<d||e>=h)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=d;e<h;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,Te,{value:`ListItem_${e}`}),t.insert(n,no,{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,ue)){const s=t.get(n,ue);s.position.y=-(e*r.itemHeight-r.scrollY),t.insert(n,ue,s)}}i.visibleStart=d,i.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const ra=new oa,aa=K("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class la{build(e){ie("Dropdown",aa);const t=e.world,n=new Map;function s(e){if(0===e||!t.valid(e))return;if(!t.has(e,ue))return;const n=t.get(e,ue);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,ue,{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,fe)){const n=t.get(e,fe);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&t.insert(e,fe,{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,fe),r=o.size.x,a=o.size.y;s.ddWidth=r;const l=n.options.length*Mo;t.insert(i,no,{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:$,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)*Mo;t.insert(o,Te,{value:`Option_${e}`}),t.insert(o,no,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Mo},offsetMax:{x:0,y:0},size:{x:r,y:Mo},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:$,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:Mo},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,qo,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),s.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,Ao,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Po.Left,verticalAlign:Eo.Middle,wordWrap:!1,overflow:Co.Clip,lineHeight:1.2}),t.insert(c,no,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:Mo},pivot:{x:.5,y:.5}}),t.setParent(c,o),s.textEntities.push(c)}d(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,Ao))return;const s=t.get(n,Ao);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,Ao,{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,qo)&&t.insert(e,qo,{enabled:n,blockRaycast:!0,raycastTarget:!0}),t.has(e,fe))){const s=t.get(e,fe);t.insert(e,fe,{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 d(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s)||!t.has(s,fe))continue;const i=n===e.highlightIndex?{...To}:{r:.95,g:.95,b:.95,a:1};t.insert(s,fe,{texture:$,color:i,size:{x:e.ddWidth,y:Mo},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 n of e.optionEntities){if(!t.valid(n)||!t.has(n,Go))continue;if(t.get(n,Go).hovered)return!0}return!1}e.addSystemToSchedule(bt.Update,Tt([Ue(kt),Ue(Zo)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=or()&&!lr(),p=t.getEntitiesWithComponents([aa]);for(const m of p){const p=t.get(m,aa);let _=n.get(m);if(_||(_={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(m,_)),s(p.listEntity),i(m),p.isOpen||u(p.listEntity,!1),l(p),f)continue;xo(t,m,qo,{enabled:!0,blockRaycast:!0});const g=t.has(m,Go)?t.get(m,Go):null;if(g?.justPressed&&(p.isOpen?r(m,p,_):o(m,p,_)),p.isOpen){for(let e=0;e<_.optionEntities.length;e++){const n=_.optionEntities[e];if(!t.valid(n)||!t.has(n,Go))continue;if(t.get(n,Go).justPressed){a(m,p,_,e,c);break}}let n=-1;for(let e=0;e<_.optionEntities.length;e++){const s=_.optionEntities[e];if(!t.valid(s)||!t.has(s,Go))continue;if(t.get(s,Go).hovered){n=e;break}}n>=0&&n!==_.highlightIndex&&(_.highlightIndex=n,d(_)),e.isKeyPressed("ArrowDown")?(_.highlightIndex>=p.options.length-1?_.highlightIndex=0:_.highlightIndex++,d(_)):e.isKeyPressed("ArrowUp")?(_.highlightIndex<=0?_.highlightIndex=p.options.length-1:_.highlightIndex--,d(_)):e.isKeyPressed("Enter")&&_.highlightIndex>=0?a(m,p,_,_.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,p,_),e.isMouseButtonPressed(0)&&(g?.hovered||h(_)||r(m,p,_))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}}const ca=new la,ua=0,da=0,ha=2,fa=K("LayoutGroup",{direction:ua,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:da,reverseOrder:!1});class pa{build(e){ie("LayoutGroup",fa);const t=e.world;e.addSystemToSchedule(bt.PreUpdate,Tt([],()=>{const e=t.getEntitiesWithComponents([fa,no,ye]);for(const n of e){const e=t.get(n,fa),s=t.get(n,no),i=t.get(n,ye);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,no)&&t.has(e,ue)&&o.push({entity:e,rect:t.get(e,no)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=_o(s,n),a=go(s,n),l=s.pivot.x,c=s.pivot.y,u=e.padding,d=e.direction===ua;let h=0;for(let n=0;n<o.length;n++){const s=o[n],i=_o(s.rect,s.entity),f=go(s.rect,s.entity),p=s.rect.pivot.x,m=s.rect.pivot.y;let _,g;d?(_=-l*r+u.left+h+p*i,g=e.childAlignment===da?(1-c)*a-u.top-(1-m)*f:e.childAlignment===ha?-c*a+u.bottom+m*f:(.5-c)*a+.5*(u.bottom-u.top)+(m-.5)*f,h+=i,n<o.length-1&&(h+=e.spacing)):(_=e.childAlignment===da?-l*r+u.left+p*i:e.childAlignment===ha?(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-h-(1-m)*f,h+=f,n<o.length-1&&(h+=e.spacing));const y=t.get(s.entity,ue);y.position.x=_,y.position.y=g,t.insert(s.entity,ue,y)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}}const ma=new pa;class _a{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(bt.PostUpdate,Tt([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const ga=new _a;async function ya(e,t,n){const s=e.getResource(zi);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function wa(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 xa=ze({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),va=ze(null,"PhysicsAPI");function ba(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Sa(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Ma{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(xa,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=wa(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([me]);for(const n of t){const t=e.world.get(n,me);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(bt.PostUpdate,Tt([Ue(Oe)],a=>{const l=r.getEntitiesWithComponents([Ae,ue]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,Ae),l=r.get(i,ue);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=ba(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===Fe.Kinematic){const e=ba(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,ue);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,ue)){const n=e.world.get(t.entity,ue),s=ba(n.worldRotation),i=a-n.worldPosition.x,o=l-n.worldPosition.y,r=Math.cos(-s),u=Math.sin(-s);d=(i*r-o*u)/(0!==n.worldScale.x?n.worldScale.x:1),h=(i*u+o*r)/(0!==n.worldScale.y?n.worldScale.y:1),f=c-s}}u.position.x=d,u.position.y=h;const p=Sa(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,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(xa,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(va,Pa._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,Re)){const e=s.get(n,Re);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,Ie)){const e=s.get(n,Ie);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,ke)){const e=s.get(n,ke);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 Pa{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(Pa.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 Ea={nearest:0,linear:1},Ca={repeat:0,clamp:1,mirror:2};function Aa(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=Ea[s.filterMode??"linear"]??1,a=Ca[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 Ia(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,d=a+a,h=l+l,f=c+c,p=a*d,m=a*h,_=a*f,g=l*h,y=l*f,w=c*f,x=u*d,v=u*h,b=u*f;return new Float32Array([(1-(g+w))*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 ka(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=zn(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]=Aa(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 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,n,s,i){const o={};for(const r of s.entities)for(const s of r.components){const r=Un(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"===Zn(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),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const f=n.loadSkeleton(d,h,s,s.length,r);if(t._free(d),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=Aa(e,o,!1),a=e.getResourceManager().getTextureGLId(r);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(n,o,h,s,i)),r){const e={gravity:a?.gravity??{...R},fixedTimestep:a?.fixedTimestep??I,subStepCount:a?.subStepCount??4};new Ma("",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=zn(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=Zn(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=Aa(e,c,!1),d=e.getResourceManager();s[o]=d.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=zn(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=jt.createShader(e.vertexSource,e.fragmentSource),s[i]=r),n[o]=jt.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=zn(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=nn(s),r=new Map;for(const t of o)try{const s=await n.loadPixels(t);r.set(t,Aa(e,s))}catch{r.set(t,0)}rn(sn(i,s,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(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=zn(t.type);for(const o of i){if("tilemap"!==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=Cn(JSON.parse(t));if(!s)continue;const o=[];for(const t of s.tilesets){const s=An(i,t.image);let r=0;try{const t=await n.loadPixels(s);r=Aa(e,t),mn(r,t.width,t.height)}catch{}o.push({textureHandle:r,columns:t.columns})}yn(i,{tileWidth:s.tileWidth,tileHeight:s.tileHeight,layers:s.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${i}`,e)}}}}}(n,s,i),await async function(e,t){const n=[],s=new Set;for(const t of e.entities)for(const e of t.components){const t=zn(e.type);for(const i of t){if("audio"!==i.type)continue;const t=e.data[i.field];"string"==typeof t&&t&&!s.has(t)&&(s.add(t),n.push(t))}}0!==n.length&&(t?await Promise.all(n.map(async e=>{try{const n=await t.readBinary(e);await hn.preloadFromData(e,n.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await hn.preloadAll(n).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(s,i),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=zn(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=Wn(t.world,s);if(c&&t.hasResource(zi))for(const e of m.values())t.world.insert(e,Pe,{scene:c,persistent:!1});if(o&&h){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=Un(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}(h,s,d,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=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,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(r,l*d);let h=0;if(c.has(o,ue)){const e=Ia(c.get(o,ue),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>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),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(r,e,c,u,d,f);const p=n.HEAPU32[d>>2],m=n.HEAPU32[f>>2],_=new Float32Array(n.HEAPF32.buffer,c,8*i),g=new Uint16Array(n.HEAPU8.buffer,u,o),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(_,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(g),t.renderer_submitTriangles(y,i,w,o,p,m,h),t._free(y),t._free(w),n._free(c),n._free(u),n._free(d),n._free(f)}h&&t._free(h)}})}(t,n,o,h,e)}if(l){const e=t.getResource(ps);e&&e.setAddressableManifest(l)}}function Fa(e,t,n){return{name:e,async setup(){await ka({...n,sceneData:t,sceneName:e})}}}async function Ba(e){const{app:t,firstScene:n,aspectRatio:s}=e;Oi(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(zi);for(const t of e.scenes)o.register(Fa(t.name,t.data,i));n&&(o.setInitial(n),await o.load(n)),void 0!==s&&Xn(t.world,s)}class za{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=Un(e.type);if(i){const s=e.data[i.skeletonField],o=e.data[i.atlasField];s&&("binary"===Zn(s)?.contentType?n.add(s):t.add(s)),o&&t.add(o)}const o=zn(e.type);for(const i of o){const o=e.data[i.field];"string"==typeof o&&o&&("font"===i.type?(s.add(o),t.add(o)):"material"===i.type||"anim-clip"===i.type||"tilemap"===i.type?t.add(o):"audio"===i.type&&n.add(o))}}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=Zn(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 Ua="__preview__";class La{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(zi);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(),n=new za(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await ka({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:n,spineModule:s,sceneName:Ua})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([pe]);for(const s of n){if(e.get(s,pe).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([me]);for(const i of s){const s=e.get(i,me);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(zi).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,ue,r);const a={isActive:!0,projectionType:ae.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,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(zi);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 $a={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),$a.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 Da;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Da||(Da={}));class Oa{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Da[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Da.Debug:console.debug(t,n);break;case Da.Info:console.log(t,n);break;case Da.Warn:console.warn(t,n);break;case Da.Error:console.error(t,n)}}}class Ha{constructor(){this.handlers_=[],this.minLevel_=Da.Info,this.addHandler(new Oa)}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(Da.Debug,e,t,n)}info(e,t,n){this.log(Da.Info,e,t,n)}warn(e,t,n){this.log(Da.Warn,e,t,n)}error(e,t,n){this.log(Da.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 Wa=new Ha;function Va(){return Wa}function Na(e){Wa.setMinLevel(e)}function ja(e,t,n){Wa.debug(e,t,n)}function Xa(e,t,n){Wa.info(e,t,n)}function Ya(e,t,n){Wa.warn(e,t,n)}function qa(e,t,n){Wa.error(e,t,n)}const Ga={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},Ka={Running:0,Paused:1,Completed:2,Cancelled:3},Ja={None:0,Restart:1,PingPong:2};const Qa=1.70158,Za=2.70158,el=2.5949095;const tl=2*Math.PI/3,nl=2*Math.PI/4.5;const sl=7.5625,il=2.75;const ol=1e-6;function rl(e,t,n){switch(e){case Ga.Linear:return t;case Ga.EaseInQuad:return function(e){return e*e}(t);case Ga.EaseOutQuad:return function(e){return e*(2-e)}(t);case Ga.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case Ga.EaseInCubic:return function(e){return e*e*e}(t);case Ga.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case Ga.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case Ga.EaseInBack:return function(e){return Za*e*e*e-Qa*e*e}(t);case Ga.EaseOutBack:return function(e){const t=e-1;return 1+Za*t*t*t+Qa*t*t}(t);case Ga.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-el)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+el)+2)/2}(t);case Ga.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*tl)}(t);case Ga.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*tl)+1}(t);case Ga.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*nl)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*nl)/2+1}(t);case Ga.EaseOutBounce:return function(e){return e<1/il?sl*e*e:e<2/il?sl*(e-=1.5/il)*e+.75:e<2.5/il?sl*(e-=2.25/il)*e+.9375:sl*(e-=2.625/il)*e+.984375}(t);case Ga.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)<ol)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)<ol)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 Ga.Step:return function(e){return e<1?0:1}(t);default:return t}}const al=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??Ga.Linear,bezierPoints:null,state:Ka.Running,loop:i?.loop??Ja.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)===Ka.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==Ka.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=rl(t.easing,n,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*s),n>=1){if(t.loop!==Ja.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===Ja.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=Ka.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===Ka.Running&&(t.state=Ka.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===Ka.Paused&&(t.state=Ka.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=Ka.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:Ka.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 ll{constructor(e){this.id=e}get state(){return al.getState(this.id)}bezier(e,t,n,s){return al.setBezier(this.id,e,t,n,s),this}then(e){return e instanceof ll?al.setSequenceNext(this.id,e.id):al.setSequenceNextExternal(this.id,e),this}pause(){al.pause(this.id)}resume(){al.resume(this.id)}cancel(){al.cancel(this.id)}}const cl={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 ul{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 ll?(al.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 dl=null,hl=null;function fl(e,t){dl=e,hl=t,al.init(e,t)}function pl(){al.shutdown(),dl=null,hl=null}function ml(){if(!dl)throw new Error("Tween API not initialized");return dl}function _l(){if(!hl)throw new Error("Tween API not initialized");return hl}const gl={to(e,t,n,s,i,o){const r=ml(),a=_l(),l=o?.easing??Ga.Linear,c=o?.delay??0,u=o?.loop??Ja.None,d=o?.loopCount??0,h=r._anim_createTween(a,e,t,n,s,i,l,c,u,d);return new ul(r,a,h)},value(e,t,n,s,i){const o=al.create(e,t,n,s,i);return new ll(o)},cancel(e){ml()._anim_cancelTween(_l(),e.entity)},cancelAll(e){ml()._anim_cancelAllTweens(_l(),e)},update(e){ml()._anim_updateTweens(_l(),e),al.update(e)}};class yl{constructor(){this.name="AnimationPlugin"}build(e){fl(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(bt.Update,Tt([Ue(Oe)],e=>{gl.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(bt.Update,Tt([Ue(Oe)],e=>{dn(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){pl()}}const wl=new yl;var xl;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(xl||(xl={}));const vl={model:xl.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function bl(e,t=vl){const{model:n,refDistance:s,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(n){case xl.Linear:{const e=i-s;if(e<=0)return 1;a=1-(Math.min(Math.max(r,s),i)-s)/e;break}case xl.Inverse:a=s/Math.max(r,s);break;case xl.Exponential:a=Math.pow(Math.max(r,s)/s,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function Sl(e,t,n,s,i){const o=e-n;return Math.max(-1,Math.min(1,o/i))}const Ml=K("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:xl.Inverse,rolloff:1,priority:0,enabled:!0}),Tl=K("AudioListener",{enabled:!0});class Pl{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;hn.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(bt.PreUpdate,Tt([Ue(Oe)],t=>{if(!(!or()||lr()))return void(c&&(l=!1,c=!1));c=!0;const s=e.world;let i=0,u=0,d=!1;const h=s.getEntitiesWithComponents([Tl,he]);for(const e of h){if(s.get(e,Tl).enabled){const t=s.get(e,he);i=t.position.x,u=t.position.y,d=!0;break}}const f=s.getEntitiesWithComponents([Ml]);a.clear();for(const e of f){const t=s.get(e,Ml);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=hn.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}d||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=s.tryGet?.(e,he),a=r?.position.x??0,h=r?.position.y??0,f=a-i,p=h-u,m=bl(Math.sqrt(f*f+p*p),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),_=Sl(a,0,i,0,t.maxDistance);n.setVolume(t.volume*m),n.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(),hn.dispose()}}const El=new Pl;let Cl=null,Al=null;function Rl(e,t){Cl=e,Al=t}function Il(){Cl=null,Al=null}const kl={update(e){Cl&&Al&&Cl.particle_update?.(Al,e)},play(e){Cl&&Al&&Cl.particle_play?.(Al,e)},stop(e){Cl&&Al&&Cl.particle_stop?.(Al,e)},reset(e){Cl&&Al&&Cl.particle_reset?.(Al,e)},getAliveCount:e=>Cl?Cl.particle_getAliveCount?.(e)??0:0};class Fl{constructor(){this.name="ParticlePlugin"}build(e){Rl(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(bt.Update,Tt([Ue(Oe)],e=>{kl.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){Il()}}const Bl=new Fl,zl=1e6;class Ul{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.sourceEntityKeys_=new Map}build(e){bn(e.wasmModule);const t=e.world,n=this.initializedLayers_,s=this.sourceEntityKeys_;e.pipeline?.setTilemapRenderer(()=>{const i=e.getResource(zt),o=i?.valid?i.worldLeft:-1e6,r=i?.valid?i.worldBottom:-1e6,a=i?.valid?i.worldRight:zl,l=i?.valid?i.worldTop:zl,c=t.getEntitiesWithComponents([Pn,ue]);for(const e of c){const s=t.tryGet(e,Pn),i=t.tryGet(e,ue);if(!s||!i)continue;const c=s.texture;if(!c)continue;const u=_n(c);if(!u)continue;if(!n.has(e)){if(Mn.initLayer(e,s.width,s.height,s.tileWidth,s.tileHeight),s.tiles.length>0){const t=new Uint16Array(s.tiles.length);for(let e=0;e<s.tiles.length;e++)t[e]=s.tiles[e];Mn.setTiles(e,t)}n.add(e)}const d=s.tileWidth/u.width,h=s.tileHeight/u.height;Mn.submitLayer(e,c,s.layer,0,s.tilesetColumns,d,h,i.worldPosition.x,i.worldPosition.y,o,r,a,l)}const u=t.getEntitiesWithComponents([Tn,ue]);for(const e of u){if(t.tryGet(e,Pn))continue;const i=t.tryGet(e,Tn),c=t.tryGet(e,ue);if(!i?.source||!c)continue;const u=wn(i.source);if(!u)continue;if(!s.has(e)){const t=[];for(let s=0;s<u.layers.length;s++){const i=1073741824+256*e+s,o=u.layers[s];Mn.initLayer(i,o.width,o.height,u.tileWidth,u.tileHeight),o.tiles.length>0&&Mn.setTiles(i,o.tiles),t.push(i),n.add(i)}s.set(e,t)}const d=s.get(e);for(let e=0;e<u.layers.length&&e<d.length;e++){const t=d[e],n=u.tilesets[0];if(!n)continue;const s=_n(n.textureHandle);if(!s)continue;const i=u.tileWidth/s.width,h=u.tileHeight/s.height;Mn.submitLayer(t,n.textureHandle,e,0,n.columns,i,h,c.worldPosition.x,c.worldPosition.y,o,r,a,l)}}})}cleanup(){for(const e of this.initializedLayers_)Mn.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),gn(),Sn()}}const Ll=new Ul;function $l(e,t){return e.toFixed(t)}function Dl(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}class Ol{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">${$l(e.fps,1)}</span> Frame: <span style="color:#d19a66">${$l(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>${Dl(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${$l(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 Hl(){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 Wl=ze(Hl(),"Stats");class Vl{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 Nl="StatsCollect";class jl{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 Xl{constructor(e){this.name="Stats",this.collector_=new jl,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(Wl,Hl());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new Ol(e,this.options_.position)}const t=this.collector_,n=this.overlay_,s=Tt([Ue(Oe),{_type:"get_world"}],(s,i)=>{t.pushFrame(s.delta);const o=e.getResource(Wl);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(Nl),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:Nl});e.addSystemToSchedule(bt.Last,s)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const Yl=new Xl;class ql{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 Gl(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 Kl(e){const{app:t,module:n,assets:s,scenes:i,firstScene:o}=e,r=t.getResource(ps);r&&(r.registerEmbeddedAssets(s),r.setEmbeddedOnly(!0));const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await Gl(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 Gl(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new ql(s);await Ba({app:t,module:n,provider:c,scenes:i,firstScene:o,spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()}const Jl=[Fo,Yo,tr,Tr,Br,hr,$r,Vr,Gr,Ar,yr,Jr,ta,ra,ca,ma,ga],Ql=[...Jl,wl,El,Bl,Ll];function Zl(e,t){return function(e,t){const n=Di.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Fs(e),Wt(e),Ks(e),ii(e),Si(e),Ei(e);const i=new Ri;n.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=ji(e,s,t,i));const r=n.getResource(zt);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(zt,{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=(h()-o)/1e3;let d;if(Ti.resize(t,l),n.hasResource(zi)){const e=n.getResource(zi).getActiveScenes();e.length>0&&(d=new Set(e))}i.setActiveScenes(d??null);const f=ji(e,s,t,l,n.world,d);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:Hi,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,cameraEntity:e.entity})}Ti.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(bt.First,l),n.addSystemToSchedule(bt.Last,c),n.addPlugin(_s),n.addPlugin(Es),n.addPlugin(Bt),n.addPlugin($i),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Ql,...t})}e=w;export{nt as Added,yl as AnimationPlugin,Di as App,ms as AssetPlugin,gs as AssetRefCounter,fs as AssetServer,ps as Assets,en as AsyncCache,xl as AttenuationModel,hn as Audio,p as AudioBus,Tl as AudioListener,m as AudioMixer,Pl as AudioPlugin,_ as AudioPool,Ml as AudioSource,we as BitmapText,Ut as BlendMode,Fe as BodyType,Re as BoxCollider,Jo as Button,Ko as ButtonState,pe as Camera,me as Canvas,ke as CapsuleCollider,st as Changed,ye as Children,Ie as CircleCollider,le as ClearFlags,ht as Commands,pt as CommandsInstance,v as DEFAULT_DESIGN_HEIGHT,x as DEFAULT_DESIGN_WIDTH,A as DEFAULT_FALLBACK_DT,I as DEFAULT_FIXED_TIMESTEP,T as DEFAULT_FONT_FAMILY,P 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,js as DataType,Lr as DragPlugin,Ur as DragState,zr as Draggable,Ls as Draw,aa as Dropdown,la as DropdownPlugin,Ga as EasingType,ve as EmitterShape,ft as EntityCommands,wt as EventReader,vt as EventReaderInstance,gt as EventRegistry,yt as EventWriter,xt as EventWriterInstance,eo as FillDirection,xr as FillMethod,vr as FillOrigin,_r as FocusManager,mr as FocusManagerState,Kr as FocusPlugin,pr as Focusable,Vl as FrameHistory,Ai as GLDebug,Zs as Geometry,St as GetWorld,L as INVALID_ENTITY,D as INVALID_FONT,O as INVALID_MATERIAL,$ as INVALID_TEXTURE,br as Image,Mr as ImagePlugin,wr as ImageType,kt as Input,Ft as InputPlugin,It as InputState,qo as Interactable,pa as LayoutGroupPlugin,na as ListView,oa as ListViewPlugin,de as LocalTransform,Da as LogLevel,Ha as Logger,Ja as LoopMode,jt as Material,tn as MaterialLoader,et as Mut,Te as Name,ge as Parent,kl as Particle,Se as ParticleEasing,Me as ParticleEmitter,Fl as ParticlePlugin,Pa as Physics,xa as PhysicsEvents,Ma as PhysicsPlugin,li as PostProcess,ri as PostProcessStack,Ee as PostProcessVolume,Ms as PrefabServer,Ts as Prefabs,Ps as PrefabsPlugin,La as PreviewPlugin,Ir as ProgressBar,Rr as ProgressBarDirection,Fr as ProgressBarPlugin,ae as ProjectionType,lt as Query,ct as QueryInstance,ut as Removed,dt as RemovedQueryInstance,Ri as RenderPipeline,xi as RenderStage,$a as RenderTexture,Ti as Renderer,Ue as Res,Le as ResMut,Ae as RigidBody,F as RuntimeConfig,Qr as SafeArea,ea as SafeAreaPlugin,ce as ScaleMode,zi as SceneManager,Bi as SceneManagerState,Pe as SceneOwner,bt as Schedule,Dr as ScrollView,Wr as ScrollViewPlugin,Zt as ShaderSources,be as SimulationSpace,jr as Slider,Nr as SliderDirection,qr as SliderPlugin,xe as SpineAnimation,fe as Sprite,un as SpriteAnimator,Wl as Stats,jl as StatsCollector,Ol as StatsOverlay,Xl as StatsPlugin,Rt as SystemRunner,Ao as Text,Po as TextAlign,fr as TextInput,gr as TextInputPlugin,Co as TextOverflow,ko as TextPlugin,Ro as TextRenderer,Eo as TextVerticalAlign,Tn as Tilemap,Mn as TilemapAPI,Pn as TilemapLayer,Ul as TilemapPlugin,Oe as Time,Pr as Toggle,Cr as TogglePlugin,ue as Transform,gl as Tween,ul as TweenHandle,Ka as TweenState,cl as TweenTarget,zt as UICameraInfo,Qo as UIEventQueue,Zo as UIEvents,Go as UIInteraction,dr as UIInteractionPlugin,er as UILayoutPlugin,Uo as UIMask,Xo as UIMaskPlugin,no as UIRect,_a as UIRenderOrderPlugin,_e as Velocity,za as WebAssetProvider,Ze as World,he as WorldTransform,Ct as addStartupSystem,Et as addSystem,At as addSystemToSchedule,wl as animationPlugin,U as applyBuildRuntimeConfig,co as applyDirectionalFill,B as applyRuntimeConfig,_s as assetPlugin,El as audioPlugin,bl as calculateAttenuation,Sl as calculatePanning,wi as cleanupAllPostProcessVolumes,yi as cleanupPostProcessVolume,cn as clearAnimClips,Ns as clearDrawCallbacks,gn as clearTextureDimensionsCache,xn as clearTilemapSourceCache,Z as clearUserComponents,N as color,ro as computeFillAnchors,lo as computeFillSize,ao as computeHandleAnchors,to as computeUIRectLayout,jo as createMaskProcessor,Fa as createRuntimeSceneConfig,Zl as createWebApp,ja as debug,Hl as defaultFrameStats,K as defineComponent,mt as defineEvent,ze as defineResource,Tt as defineSystem,J as defineTag,$r as dragPlugin,ca as dropdownPlugin,qa as error,nn as extractAnimClipTexturePaths,Yn as findEntityByName,Oi as flushPendingSystems,Jr as focusPlugin,ts as getAddressableType,ns as getAddressableTypeByEditorType,is as getAllAssetExtensions,pi as getAllEffectDefs,ln as getAnimClip,hs as getAssetBuildTransform,ls as getAssetMimeType,Zn as getAssetTypeEntry,oe as getComponent,zn as getComponentAssetFieldDescriptors,Bn as getComponentAssetFields,Ce as getComponentDefaults,Dn as getComponentEntityFields,Un as getComponentSpineFieldDescriptor,rs as getCustomExtensions,es as getEditorType,hi as getEffectDef,fi as getEffectTypes,Va as getLogger,t as getPlatform,s as getPlatformType,_n as getTextureDimensions,wn as getTilemapSource,Q as getUserComponent,as as getWeChatPackOptions,Tr as imagePlugin,Xa as info,Fs as initDrawAPI,Ei as initGLDebugAPI,Ks as initGeometryAPI,Wt as initMaterialAPI,Rl as initParticleAPI,Kl as initPlayableRuntime,ii as initPostProcessAPI,Si as initRendererAPI,Ba as initRuntime,bn as initTilemapAPI,fl as initTweenAPI,Bt as inputPlugin,ws as instantiatePrefab,Lo as intersectRects,$o as invertMatrix4,ne as isBuiltinComponent,cs as isCustomExtension,or as isEditor,ss as isKnownAssetExtension,n as isPlatformInitialized,lr as isPlayMode,rr as isRuntime,Lt as isTextureRef,i as isWeChat,o as isWeb,ma as layoutGroupPlugin,ra as listViewPlugin,jn as loadComponent,wa as loadPhysicsModule,ka as loadRuntimeScene,Wn as loadSceneData,Vn as loadSceneWithAssets,In as loadTiledMap,os as looksLikeAssetPath,sn as parseAnimClipData,Rn as parseTiledMap,Cn as parseTmjJson,Bl as particlePlugin,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Vo as pointInOBB,Oo as pointInWorldRect,Es as prefabsPlugin,Br as progressBarPlugin,j as quat,rn as registerAnimClip,ds as registerAssetBuildTransform,ie as registerComponent,Fn as registerComponentAssetFields,$n as registerComponentEntityFields,Ws as registerDrawCallback,ys as registerEmbeddedAssets,Qt as registerMaterialCallback,mn as registerTextureDimensions,yn as registerTilemapSource,On as remapEntityFields,An as resolveRelativePath,ta as safeAreaPlugin,$i as sceneManagerPlugin,Do as screenToWorld,Vr as scrollViewPlugin,ir as setEditorMode,ia as setListViewRenderer,Na as setLogLevel,ar as setPlayMode,je as setWasmErrorHandler,Bs as shutdownDrawAPI,Ci as shutdownGLDebugAPI,Js as shutdownGeometryAPI,Vt as shutdownMaterialAPI,Il as shutdownParticleAPI,oi as shutdownPostProcessAPI,Mi as shutdownRendererAPI,Sn as shutdownTilemapAPI,pl as shutdownTweenAPI,Gr as sliderPlugin,dn as spriteAnimatorSystemUpdate,Yl as statsPlugin,yo as syncFillSpriteSize,gi as syncPostProcessVolume,yr as textInputPlugin,Fo as textPlugin,Ll as tilemapPlugin,us as toBuildPath,Ar as togglePlugin,ya as transitionTo,hr as uiInteractionPlugin,tr as uiLayoutPlugin,Yo as uiMaskPlugin,Jl as uiPlugins,ga as uiRenderOrderPlugin,an as unregisterAnimClip,ee as unregisterComponent,Vs as unregisterDrawCallback,Xn as updateCameraAspectRatio,H as vec2,W as vec3,V as vec4,Ya as warn,Ui 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 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,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 g(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 loadBufferFromData(e,t){if(!this.context_)throw new Error("AudioContext not initialized");const s=this.urlToId_.get(e);if(void 0!==s&&this.buffers_.has(s)){return{id:s,duration:this.buffers_.get(s).duration}}let n;try{n=await this.context_.decodeAudioData(t)}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}}async doLoadBuffer_(e){const s=await t().readFile(e);return this.loadBufferFromData(e,s)}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 _(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 L=0,$=4294967295,D=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}),V=(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}),X=(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 Y=0;function q(e,t){const s=++Y,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},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:$,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}}),ge=re("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),_e=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:D,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={Point:0,Circle:1,Rectangle:2,Cone:3},be={World:0,Local:1},Se={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},Me=re("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:ve.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:Se.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:Se.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:$,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:be.World,enabled:!0}),Pe=K("Name",{value:""}),Te=K("SceneOwner",{scene:"",persistent:!1}),Ee=K("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});function Ce(e){const t=oe(e);return t?N(t._default):null}const Re=re("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Ae=re("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ie=re("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ke=re("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Fe={Static:0,Kinematic:1,Dynamic:2};let Be=0;function ze(e,t){const s=++Be;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function Ue(e){return{_type:"res",_resource:e}}function Le(e){return{_type:"res_mut",_resource:e}}class $e{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class De{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new $e(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Oe=ze({delta:0,elapsed:0,frameCount:0},"Time");function We(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=He(t[e]),o=He(i);"null"!==s&&"undefined"!==s&&(s!==o&&null!=i&&n.push({field:e,expected:s,actual:o,value:i}))}return n}function He(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Ve(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 je=null;function Xe(e){je=e}function Ne(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),je&&je(e,t)}function Ye(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 qe=1;const Ge=new WeakMap;function Ke(e){let t=Ge.get(e);return void 0===t&&(t=qe++,Ge.set(e,t)),t}const Je=[];function Qe(e,t=[],s=[]){Je.length=0;for(const t of e)Je.push(Ke(t));Je.sort((e,t)=>e-t);let n=Je.join(",");if(t.length>0){Je.length=0;for(const e of t)Je.push(Ke(e));Je.sort((e,t)=>e-t),n+="|+"+Je.join(",")}if(s.length>0){Je.length=0;for(const e of s)Je.push(Ke(e));Je.sort((e,t)=>e-t),n+="|-"+Je.join(",")}return n}class Ze{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 Ne(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){Ne(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){Ne(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Ne(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{const n=t._default,i=s;let o=i;for(const e of Object.keys(i))e in n||(o===i&&(o={...i}),delete o[e]);this.getBuiltinMethods(t._cppName).add(e,Ye(o))}catch(s){Ne(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 Ne(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=t._default,i={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&e in n&&(i[e]=t);const e=We(t._name,n,i);if(e.length>0)throw new Error(Ve(t._name,e))}const o={...t._default,...i};let r=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(t._cppName);r=!s.has(e),s.add(e,Ye(o))}catch(s){Ne(s,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),o}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 Ne(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 Ne(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Ne(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=We(t._name,t._default,e);if(i.length>0)throw new Error(Ve(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??Qe(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 et(e){return{_type:"mut",_component:e}}function tt(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function st(e){return{_filterType:"added",_component:e}}function nt(e){return{_filterType:"changed",_component:e}}function it(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function ot(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function rt(e){return tt(e)||it(e)||ot(e)?e._component:e}function at(e,t=[],s=[]){const n=[],i=[],o=[];return e.forEach((e,t)=>{tt(e)&&n.push(t),it(e)?i.push({index:t,component:e._component}):ot(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s,_addedFilters:i,_changedFilters:o,with:(...n)=>at(e,[...t,...n],s),without:(...n)=>at(e,t,[...s,...n])}}function lt(...e){return at(e)}class ct{constructor(e,t,s=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=s,this.actualComponents_=t._components.map(rt),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_=Qe(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 ut(e){return{_type:"removed",_component:e}}class ht{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 dt(){return{_type:"commands"}}class ft{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 pt{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ft(this,null);return this.spawned_.push(e),e}entity(e){return new ft(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 mt(e){return{_id:Symbol(`Event_${e}`),_name:e}}class gt{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 _t{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new gt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new gt,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 wt(e){return{_type:"event_reader",_event:e}}class xt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class vt{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var bt;function St(){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"}(bt||(bt={}));let Mt=0;function Pt(e,t,s){const n=++Mt;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Tt(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function Et(e){Tt().push({schedule:bt.Update,system:e})}function Ct(e){Tt().push({schedule:bt.Startup,system:e})}function Rt(e,t){Tt().push({schedule:e,system:t})}class At{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 pt&&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 ct(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 pt(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 xt(s)}case"event_reader":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new vt(s)}case"removed":{const t=e;return new ht(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class It{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const kt=ze(new It,"Input");class Ft{constructor(e){this.target_=e??null}build(e){const s=new It;e.insertResource(kt,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(bt.Last,Pt([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Bt=new Ft,zt=ze({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var Ut;function Lt(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"}(Ut||(Ut={}));let $t=null,Dt=null,Ot=1;const Wt=new Map;function Ht(e){$t=e,Dt=e.getResourceManager(),Qt()}function Vt(){0!==Yt&&$t&&($t._free(Yt),Yt=0),Wt.clear(),Ot=1,Nt=!1,Gt.clear(),Kt=null,Dt=null,$t=null}function jt(){if(!Dt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Dt}const Xt={createShader:(e,t)=>jt().createShader(e,t),releaseShader(e){e>0&&jt().releaseShader(e)},create(e){const t=Ot++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Ut.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 Wt.set(t,s),t},get:e=>Wt.get(e),setUniform(e,t,s){const n=Wt.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0,$t?.invalidateMaterialCache(e))},getUniform(e,t){const s=Wt.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Wt.get(e);s&&(s.blendMode=t,$t?.invalidateMaterialCache(e))},getBlendMode(e){const t=Wt.get(e);return t?.blendMode??Ut.Normal},setDepthTest(e,t){const s=Wt.get(e);s&&(s.depthTest=t,$t?.invalidateMaterialCache(e))},getShader(e){const t=Wt.get(e);return t?.shader??0},release(e){Wt.delete(e),$t?.invalidateMaterialCache(e)},isValid:e=>Wt.has(e),releaseAll(){Wt.clear(),$t?.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??Ut.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Wt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Ot++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Wt.set(s,n),s},toAssetData(e,t){const s=Wt.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=Wt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Nt=!1,Yt=0;const qt=16384,Gt=new Map;let Kt=null;function Jt(e){const t=(0===Yt&&$t&&(Yt=$t._malloc(qt)),Yt);if(0===t||!$t)return{ptr:0,count:0};let s=0,n=0;const i=$t.HEAPU8,o=$t.HEAPU32,r=$t.HEAPF32;for(const[a,l]of e){if(Lt(l))continue;let e=Gt.get(a);e||(Kt||(Kt=new TextEncoder),e=Kt.encode(a),Gt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(s+(4+u+4+16)>qt){console.warn(`[ESEngine] Material uniform buffer full (${s}/${qt} 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 Qt(){if(!$t||Nt)return;$t.materialDataProvider=(e,t,s,n,i)=>{const o=Wt.get(e);if(!o)return $t.HEAPU32[t>>2]=0,$t.HEAPU32[s>>2]=0,$t.HEAPU32[n>>2]=0,void($t.HEAPU32[i>>2]=0);$t.HEAPU32[t>>2]=o.shader,$t.HEAPU32[s>>2]=o.blendMode;const{ptr:r,count:a}=Jt(o.uniforms);$t.HEAPU32[n>>2]=r,$t.HEAPU32[i>>2]=a},Nt=!0}const Zt={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 es{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 ts{constructor(e,t=""){this.cache_=new es,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&&(Xt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Xt.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:Xt.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 ss(e){const t=new Set;for(const s of e.frames)s.texture&&t.add(s.texture);return Array.from(t)}function ns(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 is=new Map;function os(e){is.set(e.name,e)}function rs(e){is.delete(e)}function as(e){return is.get(e)}function ls(){is.clear()}const cs=K("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function us(e,t){const s=e.getEntitiesWithComponents([cs]);for(const n of s){const s=e.get(n,cs);if(!s.enabled||!s.playing||!s.clip)continue;const i=is.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,cs,s)}}class hs{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 async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const s=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,s)}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}}}}hs.mixer_=null,hs.bufferCache_=new Map,hs.bgmHandle_=null,hs.bgmVolume_=1,hs.fadeAnimId_=0,hs.disposed_=!1;const ds=new Map,fs=new Map;function ps(e,t,s){ds.set(e,{width:t,height:s})}function ms(e){return ds.get(e)}function gs(){ds.clear()}function _s(e,t){fs.set(e,t)}function ys(e){return fs.get(e)}function ws(){fs.clear()}let xs=null;function vs(e){xs=e}function bs(){xs=null}const Ss={initLayer(e,t,s,n,i){xs?.tilemap_initLayer(e,t,s,n,i)},destroyLayer(e){xs?.tilemap_destroyLayer(e)},setTile(e,t,s,n){xs?.tilemap_setTile(e,t,s,n)},getTile:(e,t,s)=>xs?xs.tilemap_getTile(e,t,s):0,fillRect(e,t,s,n,i,o){xs?.tilemap_fillRect(e,t,s,n,i,o)},setTiles(e,t){if(!xs)return;const s=t.byteLength,n=xs._malloc(s);new Uint16Array(xs.HEAPU8.buffer,n,t.length).set(t),xs.tilemap_setTiles(e,n,t.length),xs._free(n)},hasLayer:e=>!!xs&&xs.tilemap_hasLayer(e),submitLayer(e,t,s,n,i,o,r,a,l,c,u,h,d,f,p,m,g,_,y,w){xs?.tilemap_submitLayer(e,t,s,n,i,o,r,a,l,c,u,h,d,f,p,m,g,_,y,w)}},Ms=K("Tilemap",{source:""}),Ps=K("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[],tint:{r:1,g:1,b:1,a:1},opacity:1,visible:!0,parallaxFactor:{x:1,y:1}});function Ts(e){if(0===e)return{r:1,g:1,b:1,a:1};const t=(e>>>24&255)/255;return{r:(e>>>16&255)/255,g:(e>>>8&255)/255,b:(255&e)/255,a:0===t?1:t}}function Es(e){if(!e)return{r:1,g:1,b:1,a:1};const t=e.startsWith("#")?e.slice(1):e;if(8===t.length){const e=parseInt(t.slice(0,2),16)/255;return{r:parseInt(t.slice(2,4),16)/255,g:parseInt(t.slice(4,6),16)/255,b:parseInt(t.slice(6,8),16)/255,a:e}}if(6===t.length){return{r:parseInt(t.slice(0,2),16)/255,g:parseInt(t.slice(2,4),16)/255,b:parseInt(t.slice(4,6),16)/255,a:1}}return{r:1,g:1,b:1,a:1}}function Cs(e,t){if(0===e)return 0;let s=0;2147483648&e&&(s|=8192),1073741824&e&&(s|=16384),536870912&e&&(s|=32768);return(536870911&e)-t+1|s}function Rs(e){const t=e.width,s=e.height,n=e.tilewidth??0,i=e.tileheight??0;if(!(t&&s&&n&&i))return null;const o=e.tilesets,r=[],a=[];if(o)for(const e of o){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??n,tileHeight:e.tileheight??i,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const n=e.width??t,i=e.height??s,o=!1!==e.visible,r=e.data,l=new Uint16Array(n*i);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=Cs(r[t],e)}const u="number"==typeof e.opacity?e.opacity:1,h=Es(e.tintcolor),d="number"==typeof e.parallaxx?e.parallaxx:1,f="number"==typeof e.parallaxy?e.parallaxy:1;c.push({name:e.name??"",width:n,height:i,visible:o,tiles:l,opacity:u,tintColor:h,parallaxX:d,parallaxY:f})}const u=[],h=[];if(l)for(const e of l){if("objectgroup"!==e.type)continue;const t=e.objects;if(!t)continue;const s=[];for(const e of t){const t=new Map,n=e.properties;if(n)for(const e of n)t.set(e.name,e.value);let i="rect",o=null;if(e.ellipse)i="ellipse";else if(e.point)i="point";else if(e.polygon){i="polygon";const t=e.polygon;o=[];for(const e of t)o.push(e.x,e.y)}else if(e.polyline){i="polygon";const t=e.polyline;o=[];for(const e of t)o.push(e.x,e.y)}s.push({shape:i,x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0,rotation:e.rotation??0,vertices:o,properties:t})}u.push({name:e.name??"",objects:s})}if(o)for(const e of o){const t=e.firstgid??1,s=e.tiles;if(s)for(const e of s){const s=e.properties;if(s)for(const n of s)"collision"===n.name&&!0===n.value&&h.push(e.id+t)}}return{width:t,height:s,tileWidth:n,tileHeight:i,layers:c,tilesets:r,objectGroups:u,collisionTileIds:h}}function As(e,t){const s=e.lastIndexOf("/"),n=((s>=0?e.substring(0,s+1):"")+t).split("/"),i=[];for(const e of n)".."===e?i.pop():"."!==e&&""!==e&&i.push(e);return i.join("/")}async function Is(e,t){const s=xs;if(!s)return null;const n=new TextEncoder,i=n.encode(e),o=s._malloc(i.byteLength);s.HEAPU8.set(i,o);const r=s.tiled_loadMap(o,i.byteLength);if(s._free(o),0===r)return null;try{const e=s.tiled_getExternalTilesetCount(r);for(let i=0;i<e;i++){const e=s.tiled_getExternalTilesetSource(r,i);if(!t)return s.tiled_freeMap(r),null;const o=await t(e),a=n.encode(o),l=s._malloc(a.byteLength);s.HEAPU8.set(a,l);const c=s.tiled_loadExternalTileset(r,i,l,a.byteLength);if(s._free(l),!c)return s.tiled_freeMap(r),null}if(!s.tiled_finalize(r))return s.tiled_freeMap(r),null;const i={width:s.tiled_getMapWidth(r),height:s.tiled_getMapHeight(r),tileWidth:s.tiled_getMapTileWidth(r),tileHeight:s.tiled_getMapTileHeight(r),layers:[],tilesets:[],objectGroups:[],collisionTileIds:[]},o=s.tiled_getLayerCount(r);for(let e=0;e<o;e++){const t=s.tiled_getLayerWidth(r,e),n=s.tiled_getLayerHeight(r,e),o=t*n,a=2*o,l=s._malloc(a);s.tiled_getLayerTiles(r,e,l,o);const c=new Uint16Array(o);c.set(new Uint16Array(s.HEAPU8.buffer,l,o)),s._free(l),i.layers.push({name:s.tiled_getLayerName(r,e),width:t,height:n,visible:s.tiled_getLayerVisible(r,e),tiles:c,opacity:s.tiled_getLayerOpacity(r,e),tintColor:s.tiled_getLayerTintColor?Ts(s.tiled_getLayerTintColor(r,e)):{r:1,g:1,b:1,a:1},parallaxX:s.tiled_getLayerParallaxX(r,e),parallaxY:s.tiled_getLayerParallaxY(r,e)})}const a=s.tiled_getTilesetCount(r);for(let e=0;e<a;e++)i.tilesets.push({name:s.tiled_getTilesetName(r,e),image:s.tiled_getTilesetImage(r,e),tileWidth:s.tiled_getTilesetTileWidth(r,e),tileHeight:s.tiled_getTilesetTileHeight(r,e),columns:s.tiled_getTilesetColumns(r,e),tileCount:s.tiled_getTilesetTileCount(r,e)});return s.tiled_freeMap(r),i}catch{return s.tiled_freeMap(r),null}}const ks=Math.PI/180;function Fs(e,t,s,n,i,o){const r=function(e,t,s,n){const i=new Uint8Array(t*s),o=[],r=(o,r)=>{if(o>=t||r>=s)return!1;const a=r*t+o;if(i[a])return!1;const l=8191&e[a];return 0!==l&&n.has(l)};for(let e=0;e<s;e++)for(let n=0;n<t;n++){if(!r(n,e))continue;let a=1;for(;r(n+a,e);)a++;let l=1,c=!0;for(;c;){const t=e+l;if(t>=s)break;for(let e=0;e<a;e++)if(!r(n+e,t)){c=!1;break}c&&l++}for(let s=0;s<l;s++)for(let o=0;o<a;o++)i[(e+s)*t+(n+o)]=1;o.push({col:n,row:e,width:a,height:l})}return o}(t.tiles,t.width,t.height,n),a=[],l=s.tileWidth,c=s.tileHeight,u=s.height*c;for(const t of r){const s=t.width*l,n=t.height*c,r=i+t.col*l+.5*s,h=o+(u-t.row*c)-.5*n,d=e.spawn();e.insert(d,ue,{position:{x:r,y:h,z:0}}),e.insert(d,Re,{bodyType:Fe.Static}),e.insert(d,Ae,{halfExtents:{x:.5*s,y:.5*n}}),a.push(d)}return a}function Bs(e,t,s,n={}){const i=[],o=t.tilesets[0];let r=0;for(const n of t.layers){if(!n.visible)continue;const a=e.spawn();e.insert(a,ue,{});const l=o?s.get(o.image)??0:0,c=o?.columns??1;e.insert(a,Ps,{width:n.width,height:n.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:r,tiles:Array.from(n.tiles),tint:{...n.tintColor},opacity:n.opacity,visible:n.visible,parallaxFactor:{x:n.parallaxX,y:n.parallaxY}}),i.push(a),r++}if(!1!==n.generateObjectCollision&&t.objectGroups.length>0){const s=function(e,t,s,n){const i=[],o=t.height*t.tileHeight;for(const r of t.objectGroups)for(const t of r.objects){if("point"===t.shape)continue;const r=e.spawn(),a=t.x,l=t.y,c=s+a+.5*t.width,u=n+(o-l)-.5*t.height,h=-t.rotation*ks;if(e.insert(r,ue,{position:{x:c,y:u,z:0}}),e.insert(r,Re,{bodyType:Fe.Static}),"ellipse"===t.shape){const s=.5*Math.max(t.width,t.height);e.insert(r,Ie,{radius:s})}else if("polygon"===t.shape&&t.vertices){let s=1/0,n=1/0,i=-1/0,o=-1/0;for(let e=0;e<t.vertices.length;e+=2){const r=t.vertices[e],a=t.vertices[e+1];r<s&&(s=r),r>i&&(i=r),a<n&&(n=a),a>o&&(o=a)}const a=i-s,l=o-n,c=.5*(s+i),u=.5*(n+o);e.insert(r,Ae,{halfExtents:{x:.5*a,y:.5*l},offset:{x:c,y:-u}})}else e.insert(r,Ae,{halfExtents:{x:.5*t.width,y:.5*t.height}});if(0!==h){const t=.5*h;e.insert(r,ue,{position:{x:c,y:u,z:0},rotation:{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}})}i.push(r)}return i}(e,t,0,0);i.push(...s)}const a=new Set(n.collisionTileIds??t.collisionTileIds);if(a.size>0)for(const s of t.layers){if(!s.visible)continue;const n=Fs(e,s,t,a,0,0);i.push(...n)}return i}const zs=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"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}]]);function Us(e,t){zs.set(e,t)}function Ls(e){const t=zs.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 $s(e){return zs.get(e)?.fields??[]}function Ds(e){return zs.get(e)?.spine??null}const Os=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Ws(e,t){Os.set(e,t)}function Hs(e){return Os.get(e)}function Vs(e,t){const s=Os.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 js(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,Pe,{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),qs(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 Xs(e,t){return js(e,t)}async function Ns(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 Ys.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=zs.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=[...Ys.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=zs.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=js(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 Ys=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),ps(r.handle,r.width,r.height)}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=ss(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);os(ns(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 hs.preloadAll(n).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,s,n){const i=[...e].map(async e=>{try{const i=Rs(await t.loadJson(e));if(!i)return void console.warn(`Failed to parse tilemap: ${e}`);const o=[];for(const r of i.tilesets){const i=As(e,r.image);let a=0;try{const e=s?`${s}/${i}`:`/${i}`,o=await t.loadTexture(e);a=o.handle,n.set(i,e),ps(o.handle,o.width,o.height)}catch(e){console.warn(`Failed to load tileset texture: ${i}`,e)}o.push({textureHandle:a,columns:r.columns})}_s(e,{tileWidth:i.tileWidth,tileHeight:i.tileHeight,layers:i.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(i),new Map}}]]);function qs(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 Gs(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 Ks(e,t){const s=e.getEntitiesWithComponents([Pe]);for(const n of s){const s=e.get(n,Pe);if(s&&s.value===t)return n}return null}const Js=[{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},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0}],Qs={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"},Zs=new Map,en=new Set;for(const e of Js)for(const t of e.extensions)Zs.set(t,e),en.add(t);function tn(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function sn(e){return Zs.get(tn(e))}function nn(e){return sn(e)?.editorType??"unknown"}function on(e){return sn(e)?.addressableType??null}function rn(e){for(const t of Js)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function an(e){return en.has(e.toLowerCase())}function ln(){return en}function cn(e){return"string"==typeof e&&(!!e.includes("/")&&an(tn(e)))}function un(){const e=[];for(const t of Js)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function hn(){return un().map(e=>({type:"suffix",value:e}))}function dn(e){return Qs[e.toLowerCase()]}function fn(e){const t=sn(e);return t?.wechatPackInclude??!1}function pn(e){const t=sn(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 mn(e,t){for(const s of Js)s.editorType===e&&(s.buildTransform=t)}function gn(e){return sn(e)?.buildTransform}class _n{constructor(e){this.textureCache_=new es,this.shaderCache_=new es,this.jsonCache_=new es,this.textCache_=new es,this.binaryCache_=new es,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new es,this.prefabCache_=new es,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 ts(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(),Xt.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"===sn(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=sn(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 Ls(e.type)){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}const s=Ds(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 Ns(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 Xt.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 Xt.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(pn(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 yn=ze(null,"Assets");class wn{build(e){const t=e.wasmModule;t?e.insertResource(yn,new _n(t)):console.warn("AssetPlugin: No WASM module available")}}const xn=new wn;class vn{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 bn(e,t){const s=e.getResource(yn);s&&s.registerEmbeddedAssets(t)}async function Sn(e,t,s){const{entities:n,rootId:i}=await Pn(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 Ns(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 Mn=10;async function Pn(e,t,s,n,i,o=0){if(o>Mn)throw new Error(`Prefab nesting depth exceeded ${Mn}. 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 Pn(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};Tn(h.components,r),En(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 Tn(e,t){for(const s of e){const e=Hs(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 En(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 Cn{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 Sn(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Rn=ze(null,"Prefabs");class An{constructor(){this.name="PrefabsPlugin",this.dependencies=[yn]}build(e){const t=e.getResource(yn);e.insertResource(Rn,new Cn(e.world,t))}}const In=new An;let kn=null,Fn=0,Bn=0,zn=0;const Un=new Float32Array(256);function Ln(e){kn=e,Fn=kn._malloc(64),Bn=kn._malloc(64),zn=kn._malloc(1024)}function $n(){kn&&(Fn&&(kn._free(Fn),Fn=0),Bn&&(kn._free(Bn),Bn=0),zn&&(kn._free(zn),zn=0)),kn=null}function Dn(){if(!kn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return kn}const On={r:1,g:1,b:1,a:1},Wn={begin(e){const t=Dn();try{t.HEAPF32.set(e,Fn/4),t.draw_begin(Fn)}catch(e){Ne(e,"Draw.begin")}},end(){try{Dn().draw_end()}catch(e){Ne(e,"Draw.end")}},line(e,t,s,n=1){try{Dn().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ne(e,"Draw.line")}},rect(e,t,s,n=!0){try{Dn().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ne(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{Dn().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ne(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,i=32){try{Dn().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){Ne(e,"Draw.circle")}},circleOutline(e,t,s,n=1,i=32){try{Dn().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){Ne(e,"Draw.circleOutline")}},texture(e,t,s,n=On){try{Dn().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Ne(e,"Draw.texture")}},textureRotated(e,t,s,n,i=On){try{Dn().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,i.r,i.g,i.b,i.a)}catch(e){Ne(e,"Draw.textureRotated")}},setLayer(e){Dn().draw_setLayer(e)},setDepth(e){Dn().draw_setDepth(e)},getDrawCallCount:()=>kn?kn.draw_getDrawCallCount():0,getPrimitiveCount:()=>kn?kn.draw_getPrimitiveCount():0,setBlendMode(e){Dn().draw_setBlendMode(e)},setDepthTest(e){Dn().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=Dn();n.HEAPF32.set(s,Bn/4),n.draw_mesh(e,t,Bn)}catch(s){Ne(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=Dn(),i=Xt.get(t);if(!i)return;if(Wn.setBlendMode(i.blendMode),Wn.setDepthTest(i.depthTest),0===i.uniforms.size)return void Wn.drawMesh(e,i.shader,s);let o;if(n.HEAPF32.set(s,Bn/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,s]of i.uniforms){const n=jn(t);if(!(n<0)){if(Lt(s))Un[o++]=10,Un[o++]=n,Un[o++]=s.slot??e++,Un[o++]=s.textureId;else if("number"==typeof s)Un[o++]=1,Un[o++]=n,Un[o++]=s;else if(Array.isArray(s)){Un[o++]=s.length,Un[o++]=n;for(let e=0;e<s.length;e++)Un[o++]=s[e]}else"w"in s?(Un[o++]=4,Un[o++]=n,Un[o++]=s.x,Un[o++]=s.y,Un[o++]=s.z,Un[o++]=s.w):"z"in s?(Un[o++]=3,Un[o++]=n,Un[o++]=s.x,Un[o++]=s.y,Un[o++]=s.z):(Un[o++]=2,Un[o++]=n,Un[o++]=s.x,Un[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(Un.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void n.draw_mesh(e,i.shader,Bn);n.HEAPF32.set(i.cachedBuffer_.subarray(0,o),zn/4),n.draw_meshWithUniforms(e,i.shader,Bn,zn,o)}catch(s){Ne(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Hn={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17},Vn=new Set;function jn(e){const t=Hn[e];return void 0!==t?t:(Vn.has(e)||(Vn.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Hn).join(", ")}`)),-1)}const Xn=new Map;function Nn(e,t,s){Xn.set(e,{fn:t,scene:s??""})}function Yn(e){Xn.delete(e)}function qn(){Xn.clear()}var Gn;!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"}(Gn||(Gn={}));let Kn=null,Jn=0,Qn=0,Zn=0;function ei(e){Kn=e,Jn=Kn._malloc(262144),Qn=Kn._malloc(65536),Zn=Kn._malloc(256)}function ti(){Kn&&(Jn&&Kn._free(Jn),Qn&&Kn._free(Qn),Zn&&Kn._free(Zn),Jn=0,Qn=0,Zn=0),Kn=null}function si(){if(!Kn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Kn}const ni={create(e){const t=si(),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,Jn/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,Zn,i).set(o),t.geometry_init(s,Jn,n,Zn,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,Qn,n).set(e.indices),t.geometry_setIndices16(s,Qn,n)}else{new Uint32Array(t.HEAPU8.buffer,Qn,n).set(e.indices),t.geometry_setIndices32(s,Qn,n)}}return s},updateVertices(e,t,s=0){const n=si(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);n.HEAPF32.set(t,Jn/4),n.geometry_updateVertices(e,Jn,i,s)},release(e){e>0&&si().geometry_release(e)},isValid:e=>!(!Kn||e<=0)&&Kn.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return ni.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:Gn.Float2},{name:"a_texCoord",type:Gn.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 ni.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:Gn.Float2},{name:"a_texCoord",type:Gn.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 ni.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Gn.Float2},{name:"a_texCoord",type:Gn.Float2}],indices:new Uint16Array(r)})}};let ii=1;const oi=new Map,ri=new Map;function ai(){return oi}function li(){return ri}class ci{constructor(){this.passes_=[],this.destroyed_=!1,this.id=ii++,oi.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}setEnabled(e,t){const s=this.passes_.find(t=>t.name===e);return s&&(s.enabled=t),this}setUniform(e,t,s){const n=this.passes_.find(t=>t.name===e);return n&&n.floatUniforms.set(t,s),this}setUniformVec4(e,t,s){const n=this.passes_.find(t=>t.name===e);return n&&n.vec4Uniforms.set(t,{...s}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of ri)t===this&&ri.delete(e);oi.delete(this.id)}}}const ui="#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";let hi=null;function di(e){hi=e}function fi(){for(const e of ai().values())e.destroy();ai().clear(),li().clear(),hi&&mi.isInitialized()&&mi.shutdown(),hi=null}function pi(){if(!hi)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return hi}const mi={createStack:()=>new ci,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");li().set(e,t)},unbind(e){li().delete(e)},getStack:e=>li().get(e)??null,init(e,t){try{return pi().postprocess_init(e,t)}catch(s){return Ne(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{pi().postprocess_shutdown()}catch(e){Ne(e,"PostProcess.shutdown")}},resize(e,t){try{pi().postprocess_resize(e,t)}catch(s){Ne(s,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!hi)return!1;try{return hi.postprocess_isInitialized()}catch(e){return Ne(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{pi().postprocess_setBypass(e)}catch(e){Ne(e,"PostProcess.setBypass")}},setOutputViewport(e,t,s,n){try{pi().postprocess_setOutputViewport(e,t,s,n)}catch(e){Ne(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=li().get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(mi.isInitialized()||mi.init(1,1),mi.setBypass(!1),function(e){const t=pi();try{t.postprocess_clearPasses()}catch(e){return void Ne(e,"PostProcess._applyForCamera:clearPasses")}for(const s of e.passes)if(s.enabled){try{t.postprocess_addPass(s.name,s.shader)}catch(e){Ne(e,`PostProcess._applyForCamera:addPass("${s.name}")`);continue}for(const[e,n]of s.floatUniforms)try{t.postprocess_setUniformFloat(s.name,e,n)}catch(t){Ne(t,`PostProcess._applyForCamera:setUniform("${s.name}", "${e}")`)}for(const[e,n]of s.vec4Uniforms)try{t.postprocess_setUniformVec4(s.name,e,n.x,n.y,n.z,n.w)}catch(t){Ne(t,`PostProcess._applyForCamera:setUniformVec4("${s.name}", "${e}")`)}}}(t)):mi.setBypass(!0)},_resetAfterCamera(){try{pi().postprocess_clearPasses(),pi().postprocess_setBypass(!0)}catch(e){Ne(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of li().keys())e(t)||li().delete(t)},screenStack:null,setScreenStack(e){mi.screenStack=e},_beginScreenCapture(){try{pi().postprocess_beginScreenCapture()}catch(e){Ne(e,"PostProcess._beginScreenCapture")}},_endScreenCapture(){try{pi().postprocess_endScreenCapture()}catch(e){Ne(e,"PostProcess._endScreenCapture")}},_applyScreenStack(){const e=mi.screenStack;if(!e||e.isDestroyed||0===e.enabledPassCount)return;const t=pi();try{t.postprocess_clearScreenPasses()}catch(e){return void Ne(e,"PostProcess._applyScreenStack:clearScreenPasses")}for(const s of e.passes)if(s.enabled){try{t.postprocess_addScreenPass(s.name,s.shader)}catch(e){Ne(e,`PostProcess._applyScreenStack:addScreenPass("${s.name}")`);continue}for(const[e,n]of s.floatUniforms)try{t.postprocess_setScreenUniformFloat(s.name,e,n)}catch(t){Ne(t,`PostProcess._applyScreenStack:setScreenUniform("${s.name}", "${e}")`)}for(const[e,n]of s.vec4Uniforms)try{t.postprocess_setScreenUniformVec4(s.name,e,n.x,n.y,n.z,n.w)}catch(t){Ne(t,`PostProcess._applyScreenStack:setScreenUniformVec4("${s.name}", "${e}")`)}}},_executeScreenPasses(){try{pi().postprocess_executeScreenPasses()}catch(e){Ne(e,"PostProcess._executeScreenPasses")}},createBlur:()=>Xt.createShader(ui,"#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:()=>Xt.createShader(ui,"#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:()=>Xt.createShader(ui,"#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"),createBloom:()=>Xt.createShader(ui,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_threshold;\nuniform float u_intensity;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 texelSize = 1.0 / u_resolution;\n\n vec3 bloom = vec3(0.0);\n float total = 0.0;\n for (float x = -3.0; x <= 3.0; x += 1.0) {\n for (float y = -3.0; y <= 3.0; y += 1.0) {\n vec2 offset = vec2(x, y) * texelSize * u_radius;\n vec4 s = texture(u_texture, v_texCoord + offset);\n float brightness = dot(s.rgb, vec3(0.2126, 0.7152, 0.0722));\n float w = max(brightness - u_threshold, 0.0);\n bloom += s.rgb * w;\n total += w;\n }\n }\n if (total > 0.0) bloom /= total;\n\n fragColor = vec4(color.rgb + bloom * u_intensity, color.a);\n}\n"),createChromaticAberration:()=>Xt.createShader(ui,"#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")},gi=new Map;function _i(e){gi.set(e.type,e)}function yi(e){return gi.get(e)}function wi(){return Array.from(gi.keys())}function xi(){return Array.from(gi.values())}_i({type:"blur",label:"Blur",factory:()=>mi.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),_i({type:"bloom",label:"Bloom",factory:()=>mi.createBloom(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:2,step:.01,defaultValue:.8},{name:"u_intensity",label:"Intensity",min:0,max:10,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:0,max:20,step:.1,defaultValue:4}]}),_i({type:"vignette",label:"Vignette",factory:()=>mi.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:3,step:.01,defaultValue:.8},{name:"u_softness",label:"Softness",min:0,max:2,step:.01,defaultValue:.3}]}),_i({type:"grayscale",label:"Grayscale",factory:()=>mi.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),_i({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>mi.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const vi=new Map,bi=new Map;function Si(e,t){let s=vi.get(e),n=bi.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(s||(s=mi.createStack(),vi.set(e,s)),n||(n=new Map,bi.set(e,n));s.passCount>0;){const e=s.passes;s.removePass(e[e.length-1].name)}for(const e of i){const t=yi(e.type);if(!t)continue;let i=n.get(e.type);void 0===i&&(i=t.factory(),n.set(e.type,i)),s.addPass(e.type,i);for(const n of t.uniforms){const t=e.uniforms[n.name]??n.defaultValue;s.setUniform(e.type,n.name,t)}}mi.bind(e,s)}else if(s&&(mi.unbind(e),s.destroy(),vi.delete(e)),n){for(const e of n.values())Xt.releaseShader(e);bi.delete(e)}}function Mi(e){const t=vi.get(e);t&&(mi.unbind(e),t.destroy(),vi.delete(e));const s=bi.get(e);if(s){for(const e of s.values())Xt.releaseShader(e);bi.delete(e)}}function Pi(){for(const e of vi.keys())Mi(e)}const Ti=ze({enabled:!0},"PostProcessVolumeConfig"),Ei=new Map,Ci=new Map;function Ri(e){const t=Ci.get(e);if(void 0!==t)return t;const s=yi(e);if(!s)return null;const n=s.factory();return Ci.set(e,n),n}function Ai(e,t){if(0===t.size){const t=Ei.get(e);return void(t&&(mi.unbind(e),t.destroy(),Ei.delete(e)))}let s=Ei.get(e);for(s||(s=mi.createStack(),Ei.set(e,s));s.passCount>0;){const e=s.passes;s.removePass(e[e.length-1].name)}for(const[e,n]of t){if(!n.enabled)continue;const t=Ri(e);if(null!==t){s.addPass(e,t);for(const[t,i]of n.uniforms)s.setUniform(e,t,i)}}s.enabledPassCount>0?mi.bind(e,s):mi.unbind(e)}const Ii=Pt([lt(Ee,ue)],e=>{const t=[];for(const[s,n,i]of e)t.push({data:n,tx:{x:i.position.x,y:i.position.y}});if(0===t.length)return;const s=[];for(const{data:e,tx:n}of t)e.isGlobal&&s.push({data:e,factor:1});if(s.length>0){const e=function(e){const t=new Map,s=[...e].sort((e,t)=>e.data.priority-t.data.priority);for(const{data:e,factor:n}of s)if(!(n<=0))for(const s of e.effects){if(!s.enabled)continue;const e=t.get(s.type);if(e)for(const[t,i]of Object.entries(s.uniforms)){const s=e.uniforms.get(t)??0;e.uniforms.set(t,s+(i-s)*n)}else{const e=new Map;for(const[t,i]of Object.entries(s.uniforms))e.set(t,i*n);t.set(s.type,{enabled:!0,uniforms:e})}}return t}(s);for(const[t]of Ei)Ai(t,e)}},{name:"PostProcessVolumeSystem"});class ki{constructor(){this.name="PostProcessPlugin"}build(e){e.insertResource(Ti,{enabled:!0}),e.addSystemToSchedule(bt.PostUpdate,Ii)}cleanup(){Pi(),function(){for(const[e,t]of Ei)mi.unbind(e),t.destroy();Ei.clear();for(const e of Ci.values())Xt.releaseShader(e);Ci.clear()}(),mi.setScreenStack(null)}}const Fi=new ki;var Bi;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Bi||(Bi={}));let zi=null,Ui=0;function Li(e){zi=e,Ui=zi._malloc(64)}function $i(){zi&&Ui&&(zi._free(Ui),Ui=0),zi=null}const Di={init(e,t){zi?.renderer_init(e,t)},resize(e,t){zi?.renderer_resize(e,t)},begin(e,t){if(zi&&Ui)try{zi.HEAPF32.set(e,Ui/4),zi.renderer_begin(Ui,t??0)}catch(e){Ne(e,"Renderer.begin")}},flush(){try{zi?.renderer_flush()}catch(e){Ne(e,"Renderer.flush")}},end(){try{zi?.renderer_end()}catch(e){Ne(e,"Renderer.end")}},submitSprites(e){if(zi)try{zi.renderer_submitSprites(e._cpp)}catch(e){Ne(e,"Renderer.submitSprites")}},submitBitmapText(e){if(zi)try{zi.renderer_submitBitmapText(e._cpp)}catch(e){Ne(e,"Renderer.submitBitmapText")}},submitSpine(e){if(zi)try{zi.renderer_submitSpine?.(e._cpp)}catch(e){Ne(e,"Renderer.submitSpine")}},submitParticles(e){if(zi)try{zi.renderer_submitParticles?.(e._cpp)}catch(e){Ne(e,"Renderer.submitParticles")}},setStage(e){zi?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>zi?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){zi?.renderer_releaseTarget(e)},getTargetTexture:e=>zi?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>zi?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){zi?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){zi?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,i){zi?.renderer_setScissor(e,t,s,n,i)},clearBuffers(e){zi?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>zi?zi.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>zi?{drawCalls:zi.renderer_getDrawCalls(),triangles:zi.renderer_getTriangles(),sprites:zi.renderer_getSprites(),text:zi.renderer_getText(),spine:zi.renderer_getSpine?.()??0,meshes:zi.renderer_getMeshes(),culled:zi.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Oi=null;function Wi(e){Oi=e}function Hi(){Oi=null}const Vi={enable(){Oi?.gl_enableErrorCheck(!0)},disable(){Oi?.gl_enableErrorCheck(!1)},check:e=>Oi?.gl_checkErrors(e)??0,diagnose(){Oi?.renderer_diagnose()}};class ji{constructor(){this.spineRenderer_=null,this.tilemapRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}setTilemapRenderer(e){this.tilemapRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}beginScreenCapture(){mi.screenStack&&mi.screenStack.enabledPassCount>0&&(mi.isInitialized()||mi.init(1,1),mi._applyScreenStack(),mi._beginScreenCapture())}endScreenCapture(){mi.screenStack&&mi.screenStack.enabledPassCount>0&&(mi._endScreenCapture(),mi._executeScreenPasses())}render(e){const{registry:t,viewProjection:s,width:n,height:i,elapsed:o}=e;n===this.lastWidth_&&i===this.lastHeight_||(Di.resize(n,i),this.lastWidth_=n,this.lastHeight_=i),Di.setViewport(0,0,n,i),Di.clearBuffers(3),Di.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,i),this.tilemapRenderer_&&this.tilemapRenderer_(),Di.submitSprites(t),Di.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Di.submitSpine(t),Di.submitParticles(t),Di.flush(),this.executeDrawCallbacks(s,o),Di.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==mi.getStack(r);a&&(mi._applyForCamera(r),mi.resize(n.w,n.h),mi.setOutputViewport(n.x,n.y,n.w,n.h)),Di.setViewport(n.x,n.y,n.w,n.h),Di.setScissor(n.x,n.y,n.w,n.h,!0),Di.clearBuffers(i),Di.setScissor(0,0,0,0,!1),Di.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),this.tilemapRenderer_&&this.tilemapRenderer_(),Di.submitSprites(t),Di.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Di.submitSpine(t),Di.submitParticles(t),Di.flush(),this.executeDrawCallbacks(s,o),Di.end(),a&&mi._resetAfterCamera()}executeDrawCallbacks(e,t){const s=Xn;if(s.size>0){Wn.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)}Wn.end();for(const e of n)Yn(e)}}}const Xi="__scene_transition_overlay__";class Ni{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class Yi{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,Te,{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),Nn(e,t,this.instance_.config.name)}bindPostProcess(e,t){mi.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){mi.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,Te)){const s=this.app_.world.get(e,Te);s.persistent=t,this.app_.world.insert(e,Te,s)}}}class qi{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}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())Yn(t);for(const t of e.postProcessBindings.keys())mi.unbind(t)}this.transition_&&(Yn(Xi),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}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},Nn(Xi,()=>{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;Wn.setLayer(9999),Wn.setDepth(9999),Wn.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,Yn(Xi),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Yn(Xi),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 Ni(t);this.scenes_.set(e,s);const n=new Yi(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(yn)?this.app_.getResource(yn):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 Ni(t);this.scenes_.set(e,s);const n=new Yi(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(yn)?this.app_.getResource(yn):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,Te)){if(this.app_.world.get(e,Te).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())Yn(e);s.drawCallbacks.clear();for(const e of s.postProcessBindings.keys())mi.unbind(e);s.postProcessBindings.clear(),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(yn)&&(i.assetServer=this.app_.getResource(yn));const o=await Ns(this.app_.world,n,i);e.loadedAssets=s;for(const s of o.values())e.entities.add(s),this.app_.world.insert(s,Te,{scene:t,persistent:!1})}if(s.systems)for(const{schedule:e,system:n}of s.systems){const s=Ki(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(yn)?this.app_.getResource(yn):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)Xt.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.postProcessBindings.values())s.setAllPassesEnabled(t)}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 Gi=ze(null,"SceneManager");function Ki(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Gi).getSceneStatus(t)&&s._fn(...n)}}}const Ji=Pt([Le(Gi),Ue(Oe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Qi={name:"SceneManager",build(e){const t=new qi(e);e.insertResource(Gi,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Gi),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(bt.Startup,s),e.addSystemToSchedule(bt.Last,Ji)}};class Zi{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 _t,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(bt.Last);else{this.runSchedule(bt.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(bt.FixedPreUpdate),this.runSchedule(bt.FixedUpdate),this.runSchedule(bt.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(bt.PreUpdate),this.runSchedule(bt.Update),this.runSchedule(bt.PostUpdate),this.runSchedule(bt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new Ze,this.resources_=new De;for(const e of Object.values(bt))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Zi}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(bt.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(bt.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 Xe(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(Gi).register(e),this}setInitialScene(e){return this.getResource(Gi).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new At(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(Oe)||this.resources_.insert(Oe,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(bt.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(bt.Last);else{this.runSchedule(bt.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(bt.FixedPreUpdate),this.runSchedule(bt.FixedUpdate),this.runSchedule(bt.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(bt.PreUpdate),this.runSchedule(bt.Update),this.runSchedule(bt.PostUpdate),this.runSchedule(bt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new At(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(Oe,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(bt.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,qn();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=[Hi,$i,fi,ti,Vt,$n];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(bt[e],performance.now()-n)}updateTime(e){const t=this.resources_.get(Oe);t.delta=e,t.elapsed+=e,t.frameCount++}}function eo(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 to=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function so(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 no=[];function io(e){if(e<no.length)return no[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 no.push(t),t}function oo(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,Te);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=so(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=h*r,a=ao(-u,u,-h,h,-i.farPlane,i.farPlane)}else a=co(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const d=ho(o.position.x,o.position.y,o.position.z),f=io(c.length);f.entity=e,f.viewProjection.set(po(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 ro=new Float32Array(16);function ao(e,t,s,n,i,o){const r=ro;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 lo=new Float32Array(16);function co(e,t,s,n){const i=lo;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 uo=new Float32Array(16);function ho(e,t,s){const n=uo;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 fo=new Float32Array(16);function po(e,t){const s=fo;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 mo={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function go(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,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=h+s.y-i.y*r.y,g=p+i.y):(p=h+s.y,g=d+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 _o=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 yo=null,wo=null;function xo(e,t){e.has(t,fe)||e.insert(t,fe,{texture:$,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 vo(e,t){switch(e){case mo.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case mo.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case mo.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 bo(e,t){switch(e){case mo.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case mo.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case mo.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 So(e,t,s,n){switch(e){case mo.BottomToTop:case mo.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}}function Mo(e,t,s,n){if(!e.has(t,_o))return;const i=e.get(t,_o),o=vo(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,_o,i)}function Po(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function To(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Eo(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(To(r.charCodeAt(0))&&n.length>0&&To(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!To(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 Co(e){let t=1;for(;t<e;)t*=2;return t}function Ro(e,t){let s=0,n=t;for(;e.has(n,_e);){const t=e.get(n,_e).entity;if(!e.valid(t))break;s++,n=t}return s}function Ao(e,t){if(yo&&wo){const e=yo.getUIRectComputedWidth(wo,t);if(e>0)return e}return e.size.x}function Io(e,t){if(yo&&wo){const e=yo.getUIRectComputedHeight(wo,t);if(e>0)return e}return e.size.y}function ko(e,t,s,n,i,o){if(!e.has(t,fe))return;const r=e.get(t,fe);let a,l;switch(s){case mo.BottomToTop:case mo.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 Fo(e,t,s){let n=t;for(;e.has(n,_e);){const t=e.get(n,_e).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function Bo(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function zo(e,t,s,n,i){if(!e.has(t,_o))return;const o=e.get(t,_o),r=go(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 Uo(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 Lo=.1,$o=30,Do={r:.3,g:.5,b:.8,a:1},Oo={Left:0,Center:1,Right:2},Wo={Top:0,Middle:1,Bottom:2},Ho={Visible:0,Clip:1,Ellipsis:2},Vo=K("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Oo.Left,verticalAlign:Wo.Top,wordWrap:!0,overflow:Ho.Visible,lineHeight:1.2});class jo{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,Co(this.frameMaxW_)),e.height=Math.max(e.height,Co(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Co(this.frameMaxW_),e.height=Co(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=Eo(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===Ho.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,Co(f)),n.height=Math.max(n.height,Co(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===Ho.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 Wo.Top:x=u;break;case Wo.Middle:x=u+(p-2*u-w)/2;break;case Wo.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 Oo.Left:n=u;break;case Oo.Center:n=f/2;break;case Oo.Right:n=f-u;break;default:n=u}s.fillText(t,n,v),v+=c}i&&e.overflow===Ho.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 Oo.Left:return"left";case Oo.Center:return"center";case Oo.Right:return"right"}}}const Xo=Uo({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?Ao(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Io(e.uiRect,e.entity):0});class No{build(e){ie("Text",Vo);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new jo(t),n=e.world,i=new Map;e.addSystemToSchedule(bt.PreUpdate,Pt([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Vo));for(const e of i.keys())if(!n.valid(e)||!n.has(e,Vo)){if(n.valid(e)&&n.has(e,fe)){const t=n.get(e,fe);n.insert(e,fe,{texture:$,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([Vo]);for(const t of e){const e=n.get(t,Vo),o=n.has(t,_o)?n.get(t,_o):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!Xo.changed(a,r)){if(n.has(t,fe)&&n.get(t,fe).texture!==$)continue}xo(n,t);const l=o?{size:{x:Ao(o,t),y:Io(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,Xo.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Yo=new No,qo=0,Go=1,Ko=re("UIMask",{enabled:!0,mode:qo});function Jo(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 Qo(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],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=h*g-d*m,T=h*_-f*m,E=h*y-p*m,C=d*_-f*g,R=d*y-p*g,A=f*y-p*_;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]=(g*M-_*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]=(_*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-g*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]=(g*x-m*b-_*w)*I,s[15]=(h*b-d*x+f*w)*I),s}function Zo(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 er(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 tr(e,t){return 2*Math.atan2(e,t)}function sr(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 nr(e,t,s,n,i,o,r,a,l,c){const u=tr(l,c),h=Math.sin(-u),d=Math.cos(-u),f=e-s,p=t-n,m=f*d-p*h+s,g=f*h+p*d+n;return m>=s-i*r&&m<=s+i*(1-r)&&g>=n-o*a&&g<=n+o*(1-a)}function ir(e,t,s,n,i,o,r){if(!e.has(t,_o)||!e.has(t,ue))return null;const a=e.get(t,_o),l=e.get(t,ue),c=Ao(a,t)*l.worldScale.x,u=Io(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=tr(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]=sr(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 or(e,t){return(s,n,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Ko]);if(0===l.length)return;const c=[],u=[],h=new Set,d=new Set;for(const e of l){const s=t.get(e,Ko);s.enabled&&(h.add(e),s.mode===Go?(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;Fo(t,e,e=>{if(i.has(e)){if(t.get(e,Ko).mode===qo)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,Ko).mode===qo){const e=ir(t,s,o,r,a,l,c);e&&(n=Jo(u,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),h(s,n)}}for(const e of u){const s=ir(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;Fo(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 rr{build(e){if(ie("UIMask",Ko),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(or(e.wasmModule,e.world))}}const ar=new rr,lr=re("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),cr=re("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),ur={Normal:0,Hovered:1,Pressed:2,Disabled:3},hr=K("Button",{state:ur.Normal,transition:null});class dr{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 fr=ze(new dr,"UIEvents");class pr{build(e){ie("UIRect",_o);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){yo=e,wo=t}(s,n);e.addSystemToSchedule(bt.PreUpdate,Pt([Ue(zt)],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(bt.PostUpdate,Pt([Ue(zt)],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(bt.PostUpdate,Pt([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const mr=new pr;let gr=!1,_r=!1;function yr(e){gr=e}function wr(){return gr}function xr(){return!gr}function vr(e){_r=e}function br(){return _r}const Sr=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&&(Qo(t,e),s=!1),e)}}();function Mr(e,t,s,n){t.emit(s,n,s),Fo(e,s,i=>{if(!e.has(i,lr))return!1;const o=e.get(i,lr);return o.enabled&&t.emit(i,n,s),o.blockRaycast})}class Pr{build(e){ie("Interactable",lr),ie("Button",hr);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),i=new dr;e.insertResource(fr,i);let o=null,r=null;e.addSystemToSchedule(bt.PreUpdate,Pt([Ue(kt),Ue(zt)],(e,a)=>{if(i.drain(),wr()&&!br())return;const l=t.getEntitiesWithComponents([cr]);for(const e of l){const s=t.get(e,cr);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,cr,s))}if(!a.valid)return;const c=f(),u=e.mouseX*c,h=a.screenH-e.mouseY*c;Sr.update(a.viewProjection);const d=Zo(u,h,Sr.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);s.uiHitTest_update(n,d.x,d.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,cr)){const e=t.get(o,cr);e.hovered=!1,t.insert(o,cr,e),i.emit(o,"hover_exit")}if(null!==y){Bo(t,y,cr);const e=t.get(y,cr);e.hovered=!0,t.insert(y,cr,e),i.emit(y,"hover_enter")}o=y}if(m&&null!==y){const e=t.get(y,cr);e.pressed=!0,e.justPressed=!0,t.insert(y,cr,e),r=y,Mr(t,i,y,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,cr)){const e=t.get(r,cr);e.pressed=!1,e.justReleased=!0,t.insert(r,cr,e),Mr(t,i,r,"release"),r===o&&Mr(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(bt.Update,Pt([],()=>{const e=t.getEntitiesWithComponents([hr]);for(const s of e){if(Bo(t,s,lr,{enabled:!0}),!t.has(s,cr))continue;const e=t.get(s,cr),n=t.get(s,hr),i=t.get(s,lr),o=!a.has(s),r=n.state;if(i.enabled?e.pressed?n.state=ur.Pressed:e.hovered?n.state=ur.Hovered:n.state=ur.Normal:n.state=ur.Disabled,o&&a.add(s),(o||r!==n.state)&&n.transition&&t.has(s,fe)){const o=t.get(s,fe);o.color=Po(n.transition,i.enabled,e.pressed,e.hovered),t.insert(s,fe,o)}}},{name:"ButtonSystem"}))}}const Tr=new Pr,Er=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}),Cr=K("Focusable",{tabIndex:0,isFocused:!1});class Rr{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Ar=ze(new Rr,"FocusManager");class Ir{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(ie("TextInput",Er),wr()&&!br())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(Ar);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,Er)?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,Er);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(fr).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,Er);n.focused=!1,n.dirty=!0;e.getResource(Ar).blur()}};function v(){const t=m();if(null===t)return;const n=s.get(t,Er);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(fr).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,Er);e.focused=!1,e.dirty=!0}e.getResource(Ar).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,h){(i.width<u||i.height<h)&&(i.width=Co(Math.max(i.width,u)),i.height=Co(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=Eo(o,p,u-2*_);let t=_;for(const s of e)o.fillText(s,_,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,s,n;if(l.multiline){const e=Eo(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=(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(bt.Update,Pt([Ue(Ar)],e=>{const t=s.getEntitiesWithComponents([Er]);for(const e of t)Bo(s,e,Cr,{tabIndex:0,isFocused:!1}),Bo(s,e,lr,{enabled:!0,blockRaycast:!0});const n=m();if(n!==M){if(null!==M&&s.valid(M)&&s.has(M,Er)){const e=s.get(M,Er);e.focused=!1,e.dirty=!0,p.blur()}null!==n&&function(e){const t=s.get(e,Er);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(bt.PreUpdate,Pt([],()=>{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,Er).dirty=!0}const r=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Er)||(r.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Er,_o]);for(const e of a){const t=s.get(e,Er);if(!t.dirty)continue;const n=s.get(e,_o),i=Math.ceil(n.size.x),o=Math.ceil(n.size.y);i<=0||o<=0||(xo(s,e),P(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const kr=new Ir,Fr={Simple:0,Sliced:1,Tiled:2,Filled:3},Br={Horizontal:0,Vertical:1},zr={Left:0,Right:1,Bottom:2,Top:3},Ur=K("Image",{texture:$,color:{r:1,g:1,b:1,a:1},imageType:Fr.Simple,fillMethod:Br.Horizontal,fillOrigin:zr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Lr=Uo({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?Ao(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Io(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class $r{build(e){ie("Image",Ur);const t=e.world,s=new Map;e.addSystemToSchedule(bt.PreUpdate,Pt([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,Ur)||s.delete(e);const e=t.getEntitiesWithComponents([Ur]);for(const n of e){const e=t.get(n,Ur),i=t.has(n,_o)?t.get(n,_o):null,o={image:e,uiRect:i,entity:n},r=s.get(n);if(r&&!Lr.changed(r,o))continue;xo(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=Ao(i,n),a.size.y=Io(i,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Fr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===Br.Horizontal?e.fillOrigin===zr.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===zr.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===Fr.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,Lr.take(o))}else a.color.a=0,t.insert(n,fe,a),s.set(n,Lr.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const Dr=new $r,Or=K("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Wr=K("ToggleGroup",{allowSwitchOff:!1});class Hr{build(e){ie("Toggle",Or),ie("ToggleGroup",Wr);const t=e.world,s=new Set;e.addSystemToSchedule(bt.Update,Pt([Ue(fr)],e=>{const n=t.getEntitiesWithComponents([Or]);if(!wr()||br()){const i=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,Or);n.isOn&&0!==n.group&&t.valid(n.group)&&(i.has(n.group)?(n.isOn=!1,t.insert(e,Or,n)):i.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,Or);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(Bo(t,s,lr,{enabled:!0}),!t.has(s,cr))continue;const n=t.get(s,cr),i=t.get(s,Or),r=t.get(s,lr);if(n.justPressed&&r.enabled){const n=i.group,r=0!==n&&t.valid(n)&&t.has(n,Wr);if(i.isOn&&r){if(!t.get(n,Wr).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(s,Or,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,Or);i.isOn&&(i.isOn=!1,t.insert(n,Or,i),e.emit(n,"change"))}}e.emit(s,"change")}if(i.transition&&t.has(s,fe)){const e=t.get(s,fe);e.color=Po(i.transition,r.enabled,n.pressed,n.hovered),t.insert(s,fe,e)}}}for(const e of n){const s=t.get(e,Or);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 Vr=new Hr,jr=mo,Xr=K("ProgressBar",{value:0,fillEntity:0,direction:mo.LeftToRight});function Nr(e,t,s,n){if(!e.has(t,_o))return;const i=e.get(t,_o),o=s/2,r=n/2,a={left:-o,bottom:-r,right:o,top:r},l=go(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 Yr{build(e){ie("ProgressBar",Xr);const t=e.world;e.addSystemToSchedule(bt.PreUpdate,Pt([],()=>{const e=t.getEntitiesWithComponents([Xr,_o]);for(const s of e){const e=t.get(s,Xr);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,_o),i=Math.max(0,Math.min(1,e.value));Mo(t,e.fillEntity,e.direction,i);const o=Ao(n,s),r=Io(n,s);Nr(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const qr=new Yr,Gr=K("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Kr=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 Jr{build(e){ie("Draggable",Gr),ie("DragState",Kr);const t=e.world,s=e.getResource(fr);let n=null,i={x:0,y:0},o=null;e.addSystemToSchedule(bt.PreUpdate,Pt([Ue(kt),Ue(zt)],(e,r)=>{if(wr()&&!br())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Gr,cr]);let s=null,o=-1/0,r=-1;for(const n of e){if(!t.get(n,Gr).enabled)continue;if(t.get(n,cr).hovered){let e=0;t.has(n,fe)&&(e=t.get(n,fe).layer);const i=Ro(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,Kr)||t.insert(s,Kr);const e=t.get(s,Kr),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,Kr)){t.get(n,Kr).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,Gr);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=n,n=null;t.get(o,Kr).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Kr))return void(o=null);const n=t.get(o,Kr),i=t.get(o,Gr),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,_e))return{x:s,y:n};const i=e.get(t,_e).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=tr(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 Qr=new Jr,Zr=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 ea(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 ta(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 sa{build(e){ie("ScrollView",Zr);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(bt.PostUpdate,Pt([Ue(kt),Ue(zt),Ue(Oe)],(e,i,o)=>{const r=wr()&&!br(),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([Zr,_o]);for(const o of l){Bo(t,o,Ko,{enabled:!0,mode:qo});const l=t.get(o,Zr),c=t.get(o,_o);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=Ao(c,o),d=Io(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,_o)){const e=t.get(r,_o);a=Ao(e,r)||e.size.x,l=Io(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),g=Math.max(0,p-d);if(!r&&i.valid){Bo(t,o,lr,{enabled:!0,blockRaycast:!0});const s=t.has(o,cr)?t.get(o,cr):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=ea(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=ea(l.scrollY,0,g,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=ea(l.scrollY,0,g,d);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=ea(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=ta(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)<Lo&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Lo?(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=ta(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)<Lo&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Lo?(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,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 na=new sa,ia=mo,oa=K("Slider",{value:0,minValue:0,maxValue:1,direction:mo.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function ra(e,t,s,n,i,o){const r=Ao(n,i)*s.worldScale.x,a=Io(n,i)*s.worldScale.y,l=tr(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,g=-n.pivot.y*a;switch(o){case mo.LeftToRight:return r>0?(f-m)/r:0;case mo.RightToLeft:return r>0?1-(f-m)/r:0;case mo.BottomToTop:return a>0?(p-g)/a:0;case mo.TopToBottom:return a>0?1-(p-g)/a:0}}function aa(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case mo.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case mo.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case mo.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case mo.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class la{build(e){ie("Slider",oa);const t=e.world;let s=null;e.addSystemToSchedule(bt.PreUpdate,Pt([Ue(kt),Ue(zt),Ue(fr)],(e,n,i)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([oa,_o]);for(const r of o){const o=t.get(r,oa),a=t.get(r,_o);if(!wr()||br()){if(t.has(r,ue)){Bo(t,r,lr,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Bo(t,o.handleEntity,lr,{enabled:!0,blockRaycast:!1});const l=t.get(r,ue),c=t.has(r,cr)?t.get(r,cr):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,cr)&&(u=t.get(o.handleEntity,cr).justPressed),u&&(s=r),s===r&&e.isMouseButtonDown(0)){let e=ra(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,oa,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=Ao(a,r),h=Io(a,r),d={left:-u/2,bottom:-h/2,right:u/2,top:h/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(Mo(t,o.fillEntity,o.direction,c),zo(t,o.fillEntity,d,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,_o)){const e=t.get(o.handleEntity,_o);aa(e,o.direction,c),t.insert(o.handleEntity,_o,e),zo(t,o.handleEntity,d,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const ca=new la;class ua{build(e){ie("Focusable",Cr);const t=e.world,s=new Rr;e.insertResource(Ar,s),e.addSystemToSchedule(bt.Update,Pt([Ue(kt),Ue(fr)],(e,n)=>{if(wr()&&!br())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const i=t.getEntitiesWithComponents([Cr]);for(const e of i){if(!t.has(e,cr))continue;t.get(e,cr).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,lr)){if(!t.get(s,lr).enabled)continue}const n=t.get(s,Cr);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,Cr)){t.get(i,Cr).isFocused=!1,n.emit(i,"blur",i)}s.focus(e);t.get(e,Cr).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const ha=new ua,da=K("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function fa(){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 pa{build(e){ie("SafeArea",da);const t=e.world;let s=fa(),n=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{s=fa(),n=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{s=fa(),n=!0});e.addSystemToSchedule(bt.PreUpdate,Pt([Ue(zt)],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([da,_o]);for(const e of u){const n=t.get(e,da),i=t.get(e,_o),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,_o,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const ma=new pa,ga=K("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let _a=null;function ya(e,t){if(!_a)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=_a.get(e);s?s.renderer=t:_a.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}class wa{build(e){ie("ListView",ga);const t=e.world,s=new Map;_a=s,e.addSystemToSchedule(bt.PostUpdate,Pt([Ue(kt)],e=>{const n=wr()&&!br();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([ga,_o]);for(const o of i){Bo(t,o,lr,{enabled:!0,blockRaycast:!0}),Bo(t,o,Ko,{enabled:!0,mode:qo});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,ga),a=t.get(o,_o),l=Io(a,o),c=Ao(a,o);if(!n){const s=t.has(o,cr)?t.get(o,cr):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,Pe,{value:`ListItem_${e}`}),t.insert(s,_o,{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 xa=new wa,va=K("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class ba{build(e){ie("Dropdown",va);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*$o;t.insert(i,_o,{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:$,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)*$o;t.insert(o,Pe,{value:`Option_${e}`}),t.insert(o,_o,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*$o},offsetMax:{x:0,y:0},size:{x:r,y:$o},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:$,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:$o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,lr,{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,Vo,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Oo.Left,verticalAlign:Wo.Middle,wordWrap:!1,overflow:Ho.Clip,lineHeight:1.2}),t.insert(c,_o,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:$o},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,Vo))return;const n=t.get(s,Vo);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,Vo,{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,lr)&&t.insert(e,lr,{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?{...Do}:{r:.95,g:.95,b:.95,a:1};t.insert(n,fe,{texture:$,color:i,size:{x:e.ddWidth,y:$o},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,cr))continue;if(t.get(s,cr).hovered)return!0}return!1}e.addSystemToSchedule(bt.Update,Pt([Ue(kt),Ue(fr)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const f=wr()&&!br(),p=t.getEntitiesWithComponents([va]);for(const m of p){const p=t.get(m,va);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;Bo(t,m,lr,{enabled:!0,blockRaycast:!0});const _=t.has(m,cr)?t.get(m,cr):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,cr))continue;if(t.get(s,cr).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,cr))continue;if(t.get(n,cr).hovered){s=e;break}}s>=0&&s!==g.highlightIndex&&(g.highlightIndex=s,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 Sa=new ba,Ma=0,Pa=0,Ta=2,Ea=K("LayoutGroup",{direction:Ma,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Pa,reverseOrder:!1});class Ca{build(e){ie("LayoutGroup",Ea);const t=e.world;e.addSystemToSchedule(bt.PreUpdate,Pt([],()=>{const e=t.getEntitiesWithComponents([Ea,_o,ye]);for(const s of e){const e=t.get(s,Ea),n=t.get(s,_o),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,_o)&&t.has(e,ue)&&o.push({entity:e,rect:t.get(e,_o)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=Ao(n,s),a=Io(n,s),l=n.pivot.x,c=n.pivot.y,u=e.padding,h=e.direction===Ma;let d=0;for(let s=0;s<o.length;s++){const n=o[s],i=Ao(n.rect,n.entity),f=Io(n.rect,n.entity),p=n.rect.pivot.x,m=n.rect.pivot.y;let g,_;h?(g=-l*r+u.left+d+p*i,_=e.childAlignment===Pa?(1-c)*a-u.top-(1-m)*f:e.childAlignment===Ta?-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)):(g=e.childAlignment===Pa?-l*r+u.left+p*i:e.childAlignment===Ta?(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,s<o.length-1&&(d+=e.spacing));const y=t.get(n.entity,ue);y.position.x=g,y.position.y=_,t.insert(n.entity,ue,y)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}}const Ra=new Ca;class Aa{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(bt.PostUpdate,Pt([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const Ia=new Aa;async function ka(e,t,s){const n=e.getResource(Gi);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function Fa(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 Ba=ze({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),za={r:.2,g:.4,b:1,a:.7},Ua={r:.2,g:1,b:.2,a:.7},La={r:.2,g:1,b:1,a:.7},$a={r:1,g:1,b:.2,a:.5},Da={r:1,g:.2,b:.2,a:.8},Oa={r:1,g:.2,b:.2,a:1},Wa=1.5,Ha=16;function Va(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function ja(e){switch(e){case Fe.Static:return za;case Fe.Kinematic:return La;default:return Ua}}function Xa(e,t,s,n,i,o){const r=Math.cos(i),a=Math.sin(i),l=[{x:-s,y:-n},{x:s,y:-n},{x:s,y:n},{x:-s,y:n}].map(s=>({x:e+s.x*r-s.y*a,y:t+s.x*a+s.y*r}));for(let e=0;e<4;e++)Wn.line(l[e],l[(e+1)%4],o,Wa)}function Na(e,t,s,n,i,o){const r=Math.cos(i),a=Math.sin(i),l=(s,n)=>({x:e+s*r-n*a,y:t+s*a+n*r}),c=l(-s,n),u=l(s,n),h=l(-s,-n),d=l(s,-n);Wn.line(c,h,o,Wa),Wn.line(u,d,o,Wa);for(let e=0;e<Ha;e++){const t=e/Ha*Math.PI,i=(e+1)/Ha*Math.PI,r=l(-s*Math.cos(t),n+s*Math.sin(t)),a=l(-s*Math.cos(i),n+s*Math.sin(i));Wn.line(r,a,o,Wa)}for(let e=0;e<Ha;e++){const t=Math.PI+e/Ha*Math.PI,i=Math.PI+(e+1)/Ha*Math.PI,r=l(-s*Math.cos(t),-n+s*Math.sin(t)),a=l(-s*Math.cos(i),-n+s*Math.sin(i));Wn.line(r,a,o,Wa)}}function Ya(e,t,s,n){const i=e+.5*s,o=t+.5*n;Wn.line({x:e,y:t},{x:i,y:o},Da,Wa);const r=Math.sqrt(s*s+n*n);if(r<1)return;const a=Math.PI/6,l=s/r,c=n/r,u=i-6*(l*Math.cos(a)-c*Math.sin(a)),h=o-6*(l*Math.sin(a)+c*Math.cos(a)),d=i-6*(l*Math.cos(a)+c*Math.sin(a)),f=o-6*(-l*Math.sin(a)+c*Math.cos(a));Wn.line({x:i,y:o},{x:u,y:h},Da,Wa),Wn.line({x:i,y:o},{x:d,y:f},Da,Wa)}function qa(e,t,s){const n=e.getResource(Ba);if(!n||!n.enabled)return;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=e.world.getEntitiesWithComponents([Re,ue]);let r=null;n.showVelocity&&e.hasResource(t)&&(r=e.getResource(t));for(const t of o){const s=e.world.get(t,Re);if(!s.enabled)continue;const o=e.world.get(t,ue),a=o.worldPosition.x,l=o.worldPosition.y,c=Va(o.worldRotation);if(n.showColliders){if(e.world.has(t,Ae)){const n=e.world.get(t,Ae),o=n.isSensor?$a:ja(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,h=Math.cos(c),d=Math.sin(c);Xa(a+r*h-u*d,l+r*d+u*h,n.halfExtents.x*i,n.halfExtents.y*i,c,o)}if(e.world.has(t,Ie)){const n=e.world.get(t,Ie),o=n.isSensor?$a:ja(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,h=Math.cos(c),d=Math.sin(c),f=a+r*h-u*d,p=l+r*d+u*h;Wn.circleOutline({x:f,y:p},n.radius*i,o,Wa,32)}if(e.world.has(t,ke)){const n=e.world.get(t,ke),o=n.isSensor?$a:ja(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,h=Math.cos(c),d=Math.sin(c);Na(a+r*h-u*d,l+r*d+u*h,n.radius*i,n.halfHeight*i,c,o)}}if(n.showVelocity&&r&&s.bodyType===Fe.Dynamic){const e=r.getLinearVelocity(t);Ya(a,l,e.x*i,e.y*i)}}if(n.showContacts&&e.hasResource(s)){const t=e.getResource(s);for(const e of t.collisionEnters)Wn.circle({x:e.contactX,y:e.contactY},3,Oa,!0,32)}}const Ga=ze({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Ka=ze(null,"PhysicsAPI");function Ja(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Qa(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Za{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(Ga,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Fa(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(bt.PostUpdate,Pt([Ue(Oe)],a=>{const l=r.getEntitiesWithComponents([Re,ue]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,Re),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=Ja(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),el(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===Fe.Kinematic){const e=Ja(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,_e)){const t=e.world.get(r,_e);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ue)){const s=e.world.get(t.entity,ue),n=Ja(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=Qa(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(Ga,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,i)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Ka,tl._fromModule(n)),function(e,t,s){e.insertResource(Ba,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),Nn("physics-debug-draw",()=>{qa(e,t,s)})}(e,Ka,Ga),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function el(e,t,s){const n=e.world;if(n.has(s,Ae)){const e=n.get(s,Ae);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,Ie)){const e=n.get(s,Ie);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,ke)){const e=n.get(s,ke);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 tl{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(tl.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)}static setDebugDraw(e,t){const s=e.getResource(Ba);s&&(s.enabled=t,e.insertResource(Ba,s))}static setDebugDrawConfig(e,t){const s=e.getResource(Ba);s&&e.insertResource(Ba,{...s,...t})}}const sl={nearest:0,linear:1},nl={repeat:0,clamp:1,mirror:2};function il(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=sl[n.filterMode??"linear"]??1,a=nl[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 ol(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 rl(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,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 al(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=$s(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]=il(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=Ds(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"===sn(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=ol(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=il(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 Za("",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=$s(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=sn(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=il(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=$s(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=Xt.createShader(e.vertexSource,e.fragmentSource),n[i]=r),s[o]=Xt.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=$s(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=ss(n),r=new Map;for(const t of o)try{const n=await s.loadPixels(t);r.set(t,il(e,n))}catch{r.set(t,0)}os(ns(i,n,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(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=$s(t.type);for(const o of i){if("tilemap"!==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=Rs(JSON.parse(t));if(!n)continue;const o=[];for(const t of n.tilesets){const n=As(i,t.image);let r=0;try{const t=await s.loadPixels(n);r=il(e,t),ps(r,t.width,t.height)}catch{}o.push({textureHandle:r,columns:t.columns})}_s(i,{tileWidth:n.tileWidth,tileHeight:n.tileHeight,layers:n.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${i}`,e)}}}}}(s,n,i),await async function(e,t){const s=[],n=new Set;for(const t of e.entities)for(const e of t.components){const t=$s(e.type);for(const i of t){if("audio"!==i.type)continue;const t=e.data[i.field];"string"==typeof t&&t&&!n.has(t)&&(n.add(t),s.push(t))}}0!==s.length&&(t?await Promise.all(s.map(async e=>{try{const s=await t.readBinary(e);await hs.preloadFromData(e,s.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await hs.preloadAll(s).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(n,i),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=$s(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=Xs(t.world,n);if(c&&t.hasResource(Gi))for(const e of m.values())t.world.insert(e,Te,{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=Ds(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=rl(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],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,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(yn);e&&e.setAddressableManifest(l)}}function ll(e,t,s){return{name:e,async setup(){await al({...s,sceneData:t,sceneName:e})}}}async function cl(e){const{app:t,firstScene:s,aspectRatio:n}=e;eo(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(Gi);for(const t of e.scenes)o.register(ll(t.name,t.data,i));s&&(o.setInitial(s),await o.load(s)),void 0!==n&&Gs(t.world,n)}class ul{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=Ds(e.type);if(i){const n=e.data[i.skeletonField],o=e.data[i.atlasField];n&&("binary"===sn(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=$s(e.type);for(const i of o){const o=e.data[i.field];"string"==typeof o&&o&&("font"===i.type?(n.add(o),t.add(o)):"material"===i.type||"anim-clip"===i.type||"tilemap"===i.type?t.add(o):"audio"===i.type&&s.add(o))}}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=sn(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 hl="__preview__";class dl{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(Gi);t.register({name:hl,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(hl),this.loadPromise_=t.load(hl).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 ul(this.baseUrl_);await s.prefetch(t);let n=null;const i=this.app_.spineInitPromise;if(i){n=(await i).controller.raw}await al({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:s,spineModule:n,sceneName:hl})}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(Gi).getScene(hl),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(Gi);await e.switchTo(hl),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 fl={create(e){const t=e.depth??!0,s="linear"===e.filter,n=(t?1:0)|(s?2:0),i=Di.createRenderTarget(e.width,e.height,n);return{_handle:i,textureId:Di.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:s?"linear":"nearest"}},release(e){Di.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Di.releaseRenderTarget(e._handle),fl.create({width:t,height:s,depth:e._depth,filter:e._filter})),begin(e,t){Di.begin(t,e._handle)},end(){Di.end()},getDepthTexture:e=>Di.getTargetDepthTexture(e._handle)};var pl;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(pl||(pl={}));class ml{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${pl[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case pl.Debug:console.debug(t,s);break;case pl.Info:console.log(t,s);break;case pl.Warn:console.warn(t,s);break;case pl.Error:console.error(t,s)}}}class gl{constructor(){this.handlers_=[],this.minLevel_=pl.Info,this.addHandler(new ml)}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(pl.Debug,e,t,s)}info(e,t,s){this.log(pl.Info,e,t,s)}warn(e,t,s){this.log(pl.Warn,e,t,s)}error(e,t,s){this.log(pl.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 _l=new gl;function yl(){return _l}function wl(e){_l.setMinLevel(e)}function xl(e,t,s){_l.debug(e,t,s)}function vl(e,t,s){_l.info(e,t,s)}function bl(e,t,s){_l.warn(e,t,s)}function Sl(e,t,s){_l.error(e,t,s)}const Ml={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},Pl={Running:0,Paused:1,Completed:2,Cancelled:3},Tl={None:0,Restart:1,PingPong:2};const El=1.70158,Cl=2.70158,Rl=2.5949095;const Al=2*Math.PI/3,Il=2*Math.PI/4.5;const kl=7.5625,Fl=2.75;const Bl=1e-6;function zl(e,t,s){switch(e){case Ml.Linear:return t;case Ml.EaseInQuad:return function(e){return e*e}(t);case Ml.EaseOutQuad:return function(e){return e*(2-e)}(t);case Ml.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case Ml.EaseInCubic:return function(e){return e*e*e}(t);case Ml.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case Ml.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case Ml.EaseInBack:return function(e){return Cl*e*e*e-El*e*e}(t);case Ml.EaseOutBack:return function(e){const t=e-1;return 1+Cl*t*t*t+El*t*t}(t);case Ml.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-Rl)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+Rl)+2)/2}(t);case Ml.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*Al)}(t);case Ml.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*Al)+1}(t);case Ml.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*Il)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*Il)/2+1}(t);case Ml.EaseOutBounce:return function(e){return e<1/Fl?kl*e*e:e<2/Fl?kl*(e-=1.5/Fl)*e+.75:e<2.5/Fl?kl*(e-=2.25/Fl)*e+.9375:kl*(e-=2.625/Fl)*e+.984375}(t);case Ml.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)<Bl)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)<Bl)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 Ml.Step:return function(e){return e<1?0:1}(t);default:return t}}const Ul=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??Ml.Linear,bezierPoints:null,state:Pl.Running,loop:i?.loop??Tl.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)===Pl.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==Pl.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=zl(t.easing,s,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*n),s>=1){if(t.loop!==Tl.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===Tl.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=Pl.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===Pl.Running&&(t.state=Pl.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===Pl.Paused&&(t.state=Pl.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=Pl.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:Pl.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 Ll{constructor(e){this.id=e}get state(){return Ul.getState(this.id)}bezier(e,t,s,n){return Ul.setBezier(this.id,e,t,s,n),this}then(e){return e instanceof Ll?Ul.setSequenceNext(this.id,e.id):Ul.setSequenceNextExternal(this.id,e),this}pause(){Ul.pause(this.id)}resume(){Ul.resume(this.id)}cancel(){Ul.cancel(this.id)}}const $l={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 Dl{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 Ll?(Ul.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 Ol=null,Wl=null;function Hl(e,t){Ol=e,Wl=t,Ul.init(e,t)}function Vl(){Ul.shutdown(),Ol=null,Wl=null}function jl(){if(!Ol)throw new Error("Tween API not initialized");return Ol}function Xl(){if(!Wl)throw new Error("Tween API not initialized");return Wl}const Nl={to(e,t,s,n,i,o){const r=jl(),a=Xl(),l=o?.easing??Ml.Linear,c=o?.delay??0,u=o?.loop??Tl.None,h=o?.loopCount??0,d=r._anim_createTween(a,e,t,s,n,i,l,c,u,h);return new Dl(r,a,d)},value(e,t,s,n,i){const o=Ul.create(e,t,s,n,i);return new Ll(o)},cancel(e){jl()._anim_cancelTween(Xl(),e.entity)},cancelAll(e){jl()._anim_cancelAllTweens(Xl(),e)},update(e){jl()._anim_updateTweens(Xl(),e),Ul.update(e)}};class Yl{constructor(){this.name="AnimationPlugin"}build(e){Hl(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(bt.Update,Pt([Ue(Oe)],e=>{Nl.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(bt.Update,Pt([Ue(Oe)],e=>{us(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){Vl()}}const ql=new Yl;var Gl;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(Gl||(Gl={}));const Kl={model:Gl.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function Jl(e,t=Kl){const{model:s,refDistance:n,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(s){case Gl.Linear:{const e=i-n;if(e<=0)return 1;a=1-(Math.min(Math.max(r,n),i)-n)/e;break}case Gl.Inverse:a=n/Math.max(r,n);break;case Gl.Exponential:a=Math.pow(Math.max(r,n)/n,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function Ql(e,t,s,n,i){const o=e-s;return Math.max(-1,Math.min(1,o/i))}const Zl=K("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:Gl.Inverse,rolloff:1,priority:0,enabled:!0}),ec=K("AudioListener",{enabled:!0});class tc{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;hs.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(bt.PreUpdate,Pt([Ue(Oe)],t=>{if(!(!wr()||br()))return void(c&&(l=!1,c=!1));c=!0;const n=e.world;let i=0,u=0,h=!1;const d=n.getEntitiesWithComponents([ec,de]);for(const e of d){if(n.get(e,ec).enabled){const t=n.get(e,de);i=t.position.x,u=t.position.y,h=!0;break}}const f=n.getEntitiesWithComponents([Zl]);a.clear();for(const e of f){const t=n.get(e,Zl);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=hs.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=Jl(Math.sqrt(f*f+p*p),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=Ql(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(),hs.dispose()}}const sc=new tc;let nc=null,ic=null;function oc(e,t){nc=e,ic=t}function rc(){nc=null,ic=null}const ac={update(e){nc&&ic&&nc.particle_update?.(ic,e)},play(e){nc&&ic&&nc.particle_play?.(ic,e)},stop(e){nc&&ic&&nc.particle_stop?.(ic,e)},reset(e){nc&&ic&&nc.particle_reset?.(ic,e)},getAliveCount:e=>nc?nc.particle_getAliveCount?.(e)??0:0};class lc{constructor(){this.name="ParticlePlugin"}build(e){oc(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(bt.Update,Pt([Ue(Oe)],e=>{ac.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){rc()}}const cc=new lc,uc=1e6;class hc{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.sourceEntityKeys_=new Map}build(e){vs(e.wasmModule);const t=e.world,s=this.initializedLayers_,n=this.sourceEntityKeys_;e.pipeline?.setTilemapRenderer(()=>{const i=e.getResource(zt),o=i?.valid?i.worldLeft:-1e6,r=i?.valid?i.worldBottom:-1e6,a=i?.valid?i.worldRight:uc,l=i?.valid?i.worldTop:uc,c=t.getEntitiesWithComponents([Ps,ue]);for(const e of c){const n=t.tryGet(e,Ps),i=t.tryGet(e,ue);if(!n||!i)continue;if(!n.visible)continue;const c=n.texture;if(!c)continue;const u=ms(c);if(!u)continue;if(!s.has(e)){if(Ss.initLayer(e,n.width,n.height,n.tileWidth,n.tileHeight),n.tiles.length>0){const t=new Uint16Array(n.tiles.length);for(let e=0;e<n.tiles.length;e++)t[e]=n.tiles[e];Ss.setTiles(e,t)}s.add(e)}const h=n.tileWidth/u.width,d=n.tileHeight/u.height,f=n.tint,p=n.parallaxFactor;Ss.submitLayer(e,c,n.layer,0,n.tilesetColumns,h,d,i.worldPosition.x,i.worldPosition.y,o,r,a,l,f.r,f.g,f.b,f.a,n.opacity,p.x,p.y)}const u=t.getEntitiesWithComponents([Ms,ue]);for(const e of u){if(t.tryGet(e,Ps))continue;const i=t.tryGet(e,Ms),c=t.tryGet(e,ue);if(!i?.source||!c)continue;const u=ys(i.source);if(!u)continue;if(!n.has(e)){const t=[];for(let n=0;n<u.layers.length;n++){const i=1073741824+256*e+n,o=u.layers[n];Ss.initLayer(i,o.width,o.height,u.tileWidth,u.tileHeight),o.tiles.length>0&&Ss.setTiles(i,o.tiles),t.push(i),s.add(i)}n.set(e,t)}const h=n.get(e);for(let e=0;e<u.layers.length&&e<h.length;e++){const t=h[e],s=u.tilesets[0];if(!s)continue;const n=ms(s.textureHandle);if(!n)continue;const i=u.tileWidth/n.width,d=u.tileHeight/n.height;Ss.submitLayer(t,s.textureHandle,e,0,s.columns,i,d,c.worldPosition.x,c.worldPosition.y,o,r,a,l,1,1,1,1,1,1,1)}}})}cleanup(){for(const e of this.initializedLayers_)Ss.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),gs(),bs()}}const dc=new hc;function fc(e,t){return e.toFixed(t)}function pc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}class mc{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">${fc(e.fps,1)}</span> Frame: <span style="color:#d19a66">${fc(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>${pc(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${fc(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 gc(){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 _c=ze(gc(),"Stats");class yc{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 wc="StatsCollect";class xc{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 vc{constructor(e){this.name="Stats",this.collector_=new xc,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(_c,gc());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new mc(e,this.options_.position)}const t=this.collector_,s=this.overlay_,n=Pt([Ue(Oe),{_type:"get_world"}],(n,i)=>{t.pushFrame(n.delta);const o=e.getResource(_c);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(wc),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=Di.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:wc});e.addSystemToSchedule(bt.Last,n)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const bc=new vc;class Sc{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 Mc(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 Pc(e){const{app:t,module:s,assets:n,scenes:i,firstScene:o}=e,r=t.getResource(yn);r&&(r.registerEmbeddedAssets(n),r.setEmbeddedOnly(!0));const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await Mc(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 Mc(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new Sc(n);await cl({app:t,module:s,provider:c,scenes:i,firstScene:o,spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()}const Tc=[Yo,ar,mr,Dr,qr,Tr,Qr,na,ca,Vr,kr,ha,ma,xa,Sa,Ra,Ia],Ec=[...Tc,ql,sc,cc,dc,Fi];function Cc(e,t){return function(e,t){const s=Zi.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ln(e),Ht(e),ei(e),di(e),Li(e),Wi(e);const i=new ji;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=oo(e,n,t,i));const r=s.getResource(zt);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(zt,{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;Di.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-o)/1e3;let h;if(Di.resize(t,l),s.hasResource(Gi)){const e=s.getResource(Gi).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=oo(e,n,t,l,s.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:n},viewProjection:to,width:t,height:l,elapsed:u});else{i.beginScreenCapture();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,cameraEntity:e.entity})}i.endScreenCapture(),Di.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(bt.First,l),s.addSystemToSchedule(bt.Last,c),s.addPlugin(xn),s.addPlugin(In),s.addPlugin(Bt),s.addPlugin(Qi),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Ec,...t})}e=w;export{st as Added,Yl as AnimationPlugin,Zi as App,wn as AssetPlugin,vn as AssetRefCounter,_n as AssetServer,yn as Assets,es as AsyncCache,Gl as AttenuationModel,hs as Audio,p as AudioBus,ec as AudioListener,m as AudioMixer,tc as AudioPlugin,g as AudioPool,Zl as AudioSource,we as BitmapText,Ut as BlendMode,Fe as BodyType,Ae as BoxCollider,hr as Button,ur as ButtonState,pe as Camera,me as Canvas,ke as CapsuleCollider,nt as Changed,ye as Children,Ie as CircleCollider,le as ClearFlags,dt as Commands,pt 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,Gn as DataType,Jr as DragPlugin,Kr as DragState,Gr as Draggable,Wn as Draw,va as Dropdown,ba as DropdownPlugin,Ml as EasingType,ve as EmitterShape,ft as EntityCommands,wt as EventReader,vt as EventReaderInstance,_t as EventRegistry,yt as EventWriter,xt as EventWriterInstance,mo as FillDirection,Br as FillMethod,zr as FillOrigin,Ar as FocusManager,Rr as FocusManagerState,ua as FocusPlugin,Cr as Focusable,yc as FrameHistory,Vi as GLDebug,ni as Geometry,St as GetWorld,L as INVALID_ENTITY,D as INVALID_FONT,O as INVALID_MATERIAL,$ as INVALID_TEXTURE,Ur as Image,$r as ImagePlugin,Fr as ImageType,kt as Input,Ft as InputPlugin,It as InputState,lr as Interactable,Ca as LayoutGroupPlugin,ga as ListView,wa as ListViewPlugin,he as LocalTransform,pl as LogLevel,gl as Logger,Tl as LoopMode,Xt as Material,ts as MaterialLoader,et as Mut,Pe as Name,_e as Parent,ac as Particle,Se as ParticleEasing,Me as ParticleEmitter,lc as ParticlePlugin,tl as Physics,Ga as PhysicsEvents,Za as PhysicsPlugin,mi as PostProcess,ki as PostProcessPlugin,ci as PostProcessStack,Ee as PostProcessVolume,Cn as PrefabServer,Rn as Prefabs,An as PrefabsPlugin,dl as PreviewPlugin,Xr as ProgressBar,jr as ProgressBarDirection,Yr as ProgressBarPlugin,ae as ProjectionType,lt as Query,ct as QueryInstance,ut as Removed,ht as RemovedQueryInstance,ji as RenderPipeline,Bi as RenderStage,fl as RenderTexture,Di as Renderer,Ue as Res,Le as ResMut,Re as RigidBody,F as RuntimeConfig,da as SafeArea,pa as SafeAreaPlugin,ce as ScaleMode,Gi as SceneManager,qi as SceneManagerState,Te as SceneOwner,bt as Schedule,Zr as ScrollView,sa as ScrollViewPlugin,Zt as ShaderSources,be as SimulationSpace,oa as Slider,ia as SliderDirection,la as SliderPlugin,xe as SpineAnimation,fe as Sprite,cs as SpriteAnimator,_c as Stats,xc as StatsCollector,mc as StatsOverlay,vc as StatsPlugin,At as SystemRunner,Vo as Text,Oo as TextAlign,Er as TextInput,Ir as TextInputPlugin,Ho as TextOverflow,No as TextPlugin,jo as TextRenderer,Wo as TextVerticalAlign,Ms as Tilemap,Ss as TilemapAPI,Ps as TilemapLayer,hc as TilemapPlugin,Oe as Time,Or as Toggle,Hr as TogglePlugin,ue as Transform,Nl as Tween,Dl as TweenHandle,Pl as TweenState,$l as TweenTarget,zt as UICameraInfo,dr as UIEventQueue,fr as UIEvents,cr as UIInteraction,Pr as UIInteractionPlugin,pr as UILayoutPlugin,Ko as UIMask,rr as UIMaskPlugin,_o as UIRect,Aa as UIRenderOrderPlugin,ge as Velocity,ul as WebAssetProvider,Ze as World,de as WorldTransform,Ct as addStartupSystem,Et as addSystem,Rt as addSystemToSchedule,ql as animationPlugin,U as applyBuildRuntimeConfig,Mo as applyDirectionalFill,B as applyRuntimeConfig,xn as assetPlugin,sc as audioPlugin,Jl as calculateAttenuation,Ql as calculatePanning,Pi as cleanupAllPostProcessVolumes,Mi as cleanupPostProcessVolume,ls as clearAnimClips,qn as clearDrawCallbacks,gs as clearTextureDimensionsCache,ws as clearTilemapSourceCache,Z as clearUserComponents,j as color,vo as computeFillAnchors,So as computeFillSize,bo as computeHandleAnchors,go as computeUIRectLayout,or as createMaskProcessor,ll as createRuntimeSceneConfig,Cc as createWebApp,xl as debug,gc as defaultFrameStats,K as defineComponent,mt as defineEvent,ze as defineResource,Pt as defineSystem,J as defineTag,Qr as dragPlugin,Sa as dropdownPlugin,Sl as error,ss as extractAnimClipTexturePaths,Ks as findEntityByName,eo as flushPendingSystems,ha as focusPlugin,on as getAddressableType,rn as getAddressableTypeByEditorType,ln as getAllAssetExtensions,xi as getAllEffectDefs,as as getAnimClip,gn as getAssetBuildTransform,dn as getAssetMimeType,sn as getAssetTypeEntry,oe as getComponent,$s as getComponentAssetFieldDescriptors,Ls as getComponentAssetFields,Ce as getComponentDefaults,Hs as getComponentEntityFields,Ds as getComponentSpineFieldDescriptor,un as getCustomExtensions,nn as getEditorType,yi as getEffectDef,wi as getEffectTypes,yl as getLogger,t as getPlatform,n as getPlatformType,ms as getTextureDimensions,ys as getTilemapSource,Q as getUserComponent,hn as getWeChatPackOptions,Dr as imagePlugin,vl as info,Ln as initDrawAPI,Wi as initGLDebugAPI,ei as initGeometryAPI,Ht as initMaterialAPI,oc as initParticleAPI,Pc as initPlayableRuntime,di as initPostProcessAPI,Li as initRendererAPI,cl as initRuntime,vs as initTilemapAPI,Hl as initTweenAPI,Bt as inputPlugin,Sn as instantiatePrefab,Jo as intersectRects,Qo as invertMatrix4,se as isBuiltinComponent,fn as isCustomExtension,wr as isEditor,an as isKnownAssetExtension,s as isPlatformInitialized,br as isPlayMode,xr as isRuntime,Lt as isTextureRef,i as isWeChat,o as isWeb,Ra as layoutGroupPlugin,xa as listViewPlugin,qs as loadComponent,Fa as loadPhysicsModule,al as loadRuntimeScene,Xs as loadSceneData,Ns as loadSceneWithAssets,Bs as loadTiledMap,cn as looksLikeAssetPath,ns as parseAnimClipData,Is as parseTiledMap,Rs as parseTmjJson,cc as particlePlugin,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,nr as pointInOBB,er as pointInWorldRect,Fi as postProcessPlugin,In as prefabsPlugin,qr as progressBarPlugin,X as quat,os as registerAnimClip,mn as registerAssetBuildTransform,ie as registerComponent,Us as registerComponentAssetFields,Ws as registerComponentEntityFields,Nn as registerDrawCallback,bn as registerEmbeddedAssets,Qt as registerMaterialCallback,ps as registerTextureDimensions,_s as registerTilemapSource,Vs as remapEntityFields,As as resolveRelativePath,ma as safeAreaPlugin,Qi as sceneManagerPlugin,Zo as screenToWorld,na as scrollViewPlugin,yr as setEditorMode,ya as setListViewRenderer,wl as setLogLevel,vr as setPlayMode,Xe as setWasmErrorHandler,$n as shutdownDrawAPI,Hi as shutdownGLDebugAPI,ti as shutdownGeometryAPI,Vt as shutdownMaterialAPI,rc as shutdownParticleAPI,fi as shutdownPostProcessAPI,$i as shutdownRendererAPI,bs as shutdownTilemapAPI,Vl as shutdownTweenAPI,ca as sliderPlugin,us as spriteAnimatorSystemUpdate,bc as statsPlugin,ko as syncFillSpriteSize,Si as syncPostProcessVolume,kr as textInputPlugin,Yo as textPlugin,dc as tilemapPlugin,pn as toBuildPath,Vr as togglePlugin,ka as transitionTo,Tr as uiInteractionPlugin,mr as uiLayoutPlugin,ar as uiMaskPlugin,Tc as uiPlugins,Ia as uiRenderOrderPlugin,rs as unregisterAnimClip,ee as unregisterComponent,Yn as unregisterDrawCallback,Gs as updateCameraAspectRatio,W as vec2,H as vec3,V as vec4,bl as warn,Ki as wrapSceneSystem};
//# sourceMappingURL=index.js.map
diff --git a/desktop/public/sdk/esm/physics/index.d.ts b/desktop/public/sdk/esm/physics/index.d.ts
index 3817e5785..8b792f83a 100644
--- a/desktop/public/sdk/esm/physics/index.d.ts
+++ b/desktop/public/sdk/esm/physics/index.d.ts
@@ -539,6 +539,13 @@ interface ESEngineModule {
postprocess_clearPasses(): void;
postprocess_setOutputTarget(fboId: number): void;
postprocess_setOutputViewport(x: number, y: number, w: number, h: number): void;
+ postprocess_beginScreenCapture(): void;
+ postprocess_endScreenCapture(): void;
+ postprocess_executeScreenPasses(): void;
+ postprocess_addScreenPass(name: string, shaderHandle: number): number;
+ postprocess_clearScreenPasses(): void;
+ postprocess_setScreenUniformFloat(passName: string, uniform: string, value: number): void;
+ postprocess_setScreenUniformVec4(passName: string, uniform: string, x: number, y: number, z: number, w: number): void;
renderer_init(width: number, height: number): void;
renderer_resize(width: number, height: number): void;
renderer_begin(matrixPtr: number, targetHandle: number): void;
@@ -829,6 +836,8 @@ declare class RenderPipeline {
get maskProcessor(): MaskProcessorFn | null;
setMaskProcessor(fn: MaskProcessorFn | null): void;
setActiveScenes(scenes: Set<string> | null): void;
+ beginScreenCapture(): void;
+ endScreenCapture(): void;
render(params: RenderParams): void;
renderCamera(params: CameraRenderParams): void;
private executeDrawCallbacks;
@@ -883,11 +892,6 @@ interface SceneData {
*/
type DrawCallback = (elapsed: number) => void;
-/**
- * @file postprocess.ts
- * @brief Per-camera post-processing effects API
- */
-
interface PassConfig {
name: string;
shader: ShaderHandle;
@@ -1090,6 +1094,22 @@ interface ESEngineMainModule {
}
declare function loadPhysicsSideModule(wasmBinary: ArrayBuffer, mainModule: ESEngineMainModule): Promise<PhysicsWasmModule>;
+interface PhysicsDebugDrawConfig {
+ enabled: boolean;
+ showColliders: boolean;
+ showVelocity: boolean;
+ showContacts: boolean;
+}
+declare const PhysicsDebugDraw: ResourceDef<PhysicsDebugDrawConfig>;
+interface VelocityProvider {
+ getLinearVelocity(entity: number): {
+ x: number;
+ y: number;
+ };
+}
+declare function drawPhysicsDebug(app: App, physicsApiRes: ResourceDef<VelocityProvider>, physicsEventsRes: ResourceDef<PhysicsEventsData>): void;
+declare function setupPhysicsDebugDraw(app: App, physicsApiRes: ResourceDef<VelocityProvider>, physicsEventsRes: ResourceDef<PhysicsEventsData>): void;
+
interface PhysicsPluginConfig {
gravity?: Vec2;
fixedTimestep?: number;
@@ -1140,7 +1160,9 @@ declare class Physics {
getAngularVelocity(entity: Entity): number;
applyTorque(entity: Entity, torque: number): void;
applyAngularImpulse(entity: Entity, impulse: number): void;
+ static setDebugDraw(app: App, enabled: boolean): void;
+ static setDebugDrawConfig(app: App, config: Partial<PhysicsDebugDrawConfig>): void;
}
-export { BodyType, BoxCollider$1 as BoxCollider, CapsuleCollider$1 as CapsuleCollider, CircleCollider$1 as CircleCollider, Physics, PhysicsAPI, PhysicsEvents, PhysicsPlugin, RigidBody$1 as RigidBody, loadPhysicsModule, loadPhysicsSideModule };
-export type { BoxColliderData, CapsuleColliderData, CircleColliderData, CollisionEnterEvent, ESEngineMainModule, PhysicsEventsData, PhysicsModuleFactory, PhysicsPluginConfig, PhysicsWasmModule, RigidBodyData, SensorEvent };
+export { BodyType, BoxCollider$1 as BoxCollider, CapsuleCollider$1 as CapsuleCollider, CircleCollider$1 as CircleCollider, Physics, PhysicsAPI, PhysicsDebugDraw, PhysicsEvents, PhysicsPlugin, RigidBody$1 as RigidBody, drawPhysicsDebug, loadPhysicsModule, loadPhysicsSideModule, setupPhysicsDebugDraw };
+export type { BoxColliderData, CapsuleColliderData, CircleColliderData, CollisionEnterEvent, ESEngineMainModule, PhysicsDebugDrawConfig, PhysicsEventsData, PhysicsModuleFactory, PhysicsPluginConfig, PhysicsWasmModule, RigidBodyData, SensorEvent };
diff --git a/desktop/public/sdk/esm/physics/index.js b/desktop/public/sdk/esm/physics/index.js
index 84ae382b6..5ee76e021 100644
--- a/desktop/public/sdk/esm/physics/index.js
+++ b/desktop/public/sdk/esm/physics/index.js
@@ -1,2 +1,2 @@
-const e=4294967295;function t(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(t);const n={};for(const i in e)n[i]=t(e[i]);return n}let n=0;function i(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function s(e,s){const r=o.get(e)??i().get(e);if(r)return r;const a=function(e,i){const s=++n,o=function(e){for(const t in e){const n=e[t];if(null!==n&&"object"==typeof n)return!0}return!1}(i);return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:i,_builtin:!1,create:e=>o?e?{...t(i),...e}:t(i):e?{...i,...e}:{...i}}}(e,s);return i().set(e,a),o.set(e,a),function(e,t,n){const i=globalThis;i.__esengine_registerComponent&&i.__esengine_registerComponent(e,t,n)}(e,s,!1),a}const o=new Map;function r(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return o.set(e,n),n}const a=r("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}});r("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}),r("Camera",{projectionType:1,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3});const l=r("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}});r("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}});const c=r("Parent",{entity:0});r("Children",{entities:[]}),r("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:4294967295,enabled:!0}),r("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});const u=0;r("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:3,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:u,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:u,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:e,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:0,enabled:!0}),s("Name",{value:""}),s("SceneOwner",{scene:"",persistent:!1}),s("PostProcessVolume",{effects:[]});let y=0;function p(e,t){const n=++y;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}const _=p({delta:0,elapsed:0,frameCount:0},"Time");var d;!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"}(d||(d={}));let m=0;async function h(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}async function f(e,t){await t.loadDynamicLibrary(new Uint8Array(e),{loadAsync:!0,allowUndefined:!0});const n=t.cwrap.bind(t);return{_physics_init:n("physics_init",null,["number","number","number","number"]),_physics_shutdown:n("physics_shutdown",null,[]),_physics_createBody:n("physics_createBody",null,["number","number","number","number","number","number","number","number","number","number"]),_physics_destroyBody:n("physics_destroyBody",null,["number"]),_physics_hasBody:n("physics_hasBody","number",["number"]),_physics_addBoxShape:n("physics_addBoxShape",null,["number","number","number","number","number","number","number","number","number"]),_physics_addCircleShape:n("physics_addCircleShape",null,["number","number","number","number","number","number","number","number"]),_physics_addCapsuleShape:n("physics_addCapsuleShape",null,["number","number","number","number","number","number","number","number","number"]),_physics_step:n("physics_step",null,["number"]),_physics_setBodyTransform:n("physics_setBodyTransform",null,["number","number","number","number"]),_physics_getDynamicBodyCount:n("physics_getDynamicBodyCount","number",[]),_physics_getDynamicBodyTransforms:n("physics_getDynamicBodyTransforms","number",[]),_physics_collectEvents:n("physics_collectEvents",null,[]),_physics_getCollisionEnterCount:n("physics_getCollisionEnterCount","number",[]),_physics_getCollisionEnterBuffer:n("physics_getCollisionEnterBuffer","number",[]),_physics_getCollisionExitCount:n("physics_getCollisionExitCount","number",[]),_physics_getCollisionExitBuffer:n("physics_getCollisionExitBuffer","number",[]),_physics_getSensorEnterCount:n("physics_getSensorEnterCount","number",[]),_physics_getSensorEnterBuffer:n("physics_getSensorEnterBuffer","number",[]),_physics_getSensorExitCount:n("physics_getSensorExitCount","number",[]),_physics_getSensorExitBuffer:n("physics_getSensorExitBuffer","number",[]),_physics_applyForce:n("physics_applyForce",null,["number","number","number"]),_physics_applyImpulse:n("physics_applyImpulse",null,["number","number","number"]),_physics_setLinearVelocity:n("physics_setLinearVelocity",null,["number","number","number"]),_physics_getLinearVelocity:n("physics_getLinearVelocity","number",["number"]),_physics_setGravity:n("physics_setGravity",null,["number","number"]),_physics_getGravity:n("physics_getGravity","number",[]),_physics_setAngularVelocity:n("physics_setAngularVelocity",null,["number","number"]),_physics_getAngularVelocity:n("physics_getAngularVelocity","number",["number"]),_physics_applyTorque:n("physics_applyTorque",null,["number","number"]),_physics_applyAngularImpulse:n("physics_applyAngularImpulse",null,["number","number"]),_physics_updateBodyProperties:n("physics_updateBodyProperties",null,["number","number","number","number","number","number","number"]),get HEAPF32(){return t.HEAPF32},get HEAPU8(){return t.HEAPU8},get HEAPU32(){return t.HEAPU32},_malloc:t._malloc.bind(t),_free:t._free.bind(t)}}const g=r("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),b=r("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),x=r("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),E=r("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),S={Static:0,Kinematic:1,Dynamic:2},P=p({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),w=p(null,"PhysicsAPI");function C(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function A(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class v{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(P,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,i=h(this.wasmUrl_,this.factory_).then(i=>{i._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const s=function(e){const t=e.world.getEntitiesWithComponents([l]);for(const n of t){const t=e.world.get(n,l);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/s,r=e.world;var u;r.onDespawn(e=>{t.has(e)&&(i._physics_destroyBody(e),t.delete(e),n.delete(e))}),e.addSystemToSchedule(d.PostUpdate,function(e,t,n){const i=++m;return{_id:Symbol(`System_${i}_${n?.name}`),_params:e,_fn:t,_name:n?.name??`System_${i}`}}([(u=_,{_type:"res",_resource:u})],l=>{const u=r.getEntitiesWithComponents([g,a]),y=new Set;for(const s of u){y.add(s);const l=r.get(s,g),c=r.get(s,a);if(t.has(s)){const e=n.get(s);!e||e.bodyType===l.bodyType&&e.gravityScale===l.gravityScale&&e.linearDamping===l.linearDamping&&e.angularDamping===l.angularDamping&&e.fixedRotation===l.fixedRotation&&e.bullet===l.bullet||(i._physics_updateBodyProperties(s,l.bodyType,l.gravityScale,l.linearDamping,l.angularDamping,l.fixedRotation?1:0,l.bullet?1:0),e.bodyType=l.bodyType,e.gravityScale=l.gravityScale,e.linearDamping=l.linearDamping,e.angularDamping=l.angularDamping,e.fixedRotation=l.fixedRotation,e.bullet=l.bullet)}else{if(!l.enabled)continue;const r=C(c.worldRotation);i._physics_createBody(s,l.bodyType,c.worldPosition.x*o,c.worldPosition.y*o,r,l.gravityScale,l.linearDamping,l.angularDamping,l.fixedRotation?1:0,l.bullet?1:0),B(e,i,s),t.add(s),n.set(s,{bodyType:l.bodyType,gravityScale:l.gravityScale,linearDamping:l.linearDamping,angularDamping:l.angularDamping,fixedRotation:l.fixedRotation,bullet:l.bullet})}if(l.bodyType===S.Kinematic){const e=C(c.worldRotation);i._physics_setBodyTransform(s,c.worldPosition.x*o,c.worldPosition.y*o,e)}}for(const e of t)y.has(e)||(i._physics_destroyBody(e),t.delete(e),n.delete(e));i._physics_step(l.delta),function(e,t,n){const i=t._physics_getDynamicBodyCount();if(0===i)return;const s=t._physics_getDynamicBodyTransforms(),o=s>>2;for(let s=0;s<i;s++){const i=o+4*s,r=t.HEAPU32[i],l=t.HEAPF32[i+1]*n,u=t.HEAPF32[i+2]*n,y=t.HEAPF32[i+3];if(!e.world.valid(r))continue;const p=e.world.get(r,a);if(!p)continue;let _=l,d=u,m=y;if(e.world.has(r,c)){const t=e.world.get(r,c);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,a)){const n=e.world.get(t.entity,a),i=C(n.worldRotation),s=l-n.worldPosition.x,o=u-n.worldPosition.y,r=Math.cos(-i),c=Math.sin(-i);_=(s*r-o*c)/(0!==n.worldScale.x?n.worldScale.x:1),d=(s*c+o*r)/(0!==n.worldScale.y?n.worldScale.y:1),m=y-i}}p.position.x=_,p.position.y=d;const h=A(m);p.rotation.w=h.w,p.rotation.x=h.x,p.rotation.y=h.y,p.rotation.z=h.z,e.world.insert(r,a,p)}}(e,i,s),function(e,t,n){t._physics_collectEvents();const i=[],s=t._physics_getCollisionEnterCount();if(s>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<s;o++){const s=e+6*o;i.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1],normalX:t.HEAPF32[s+2],normalY:t.HEAPF32[s+3],contactX:t.HEAPF32[s+4]*n,contactY:t.HEAPF32[s+5]*n})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<r;n++){const i=e+2*n;o.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const i=e+2*n;a.push({sensorEntity:t.HEAPU32[i],visitorEntity:t.HEAPU32[i+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const i=e+2*n;c.push({sensorEntity:t.HEAPU32[i],visitorEntity:t.HEAPU32[i+1]})}}e.insertResource(P,{collisionEnters:i,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,i,s)},{name:"PhysicsSystem"})),e.physicsModule=i,e.insertResource(w,U._fromModule(i)),e.setFixedTimestep(this.config_.fixedTimestep)});i.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=i}}function B(e,t,n){const i=e.world;if(i.has(n,b)){const e=i.get(n,b);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(i.has(n,x)){const e=i.get(n,x);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(i.has(n,E)){const e=i.get(n,E);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class U{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(U.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}export{S as BodyType,b as BoxCollider,E as CapsuleCollider,x as CircleCollider,U as Physics,w as PhysicsAPI,P as PhysicsEvents,v as PhysicsPlugin,g as RigidBody,h as loadPhysicsModule,f as loadPhysicsSideModule};
+const e=4294967295;function t(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(t);const n={};for(const s in e)n[s]=t(e[s]);return n}let n=0;function s(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function r(e,r){const o=i.get(e)??s().get(e);if(o)return o;const a=function(e,s){const r=++n,i=function(e){for(const t in e){const n=e[t];if(null!==n&&"object"==typeof n)return!0}return!1}(s);return{_id:Symbol(`Component_${r}_${e}`),_name:e,_default:s,_builtin:!1,create:e=>i?e?{...t(s),...e}:t(s):e?{...s,...e}:{...s}}}(e,r);return s().set(e,a),i.set(e,a),function(e,t,n){const s=globalThis;s.__esengine_registerComponent&&s.__esengine_registerComponent(e,t,n)}(e,r,!1),a}const i=new Map;function o(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return i.set(e,n),n}const a=o("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}});o("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}),o("Camera",{projectionType:1,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3});const l=o("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}});o("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}});const c=o("Parent",{entity:0});o("Children",{entities:[]}),o("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:4294967295,enabled:!0}),o("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});const u=0;o("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:3,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:u,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:u,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:e,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:0,enabled:!0}),r("Name",{value:""}),r("SceneOwner",{scene:"",persistent:!1}),r("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});let y=0;function d(e,t){const n=++y;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}const p=d({delta:0,elapsed:0,frameCount:0},"Time");function h(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e)}var f;!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"}(f||(f={}));let _=0;async function m(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}async function g(e,t){await t.loadDynamicLibrary(new Uint8Array(e),{loadAsync:!0,allowUndefined:!0});const n=t.cwrap.bind(t);return{_physics_init:n("physics_init",null,["number","number","number","number"]),_physics_shutdown:n("physics_shutdown",null,[]),_physics_createBody:n("physics_createBody",null,["number","number","number","number","number","number","number","number","number","number"]),_physics_destroyBody:n("physics_destroyBody",null,["number"]),_physics_hasBody:n("physics_hasBody","number",["number"]),_physics_addBoxShape:n("physics_addBoxShape",null,["number","number","number","number","number","number","number","number","number"]),_physics_addCircleShape:n("physics_addCircleShape",null,["number","number","number","number","number","number","number","number"]),_physics_addCapsuleShape:n("physics_addCapsuleShape",null,["number","number","number","number","number","number","number","number","number"]),_physics_step:n("physics_step",null,["number"]),_physics_setBodyTransform:n("physics_setBodyTransform",null,["number","number","number","number"]),_physics_getDynamicBodyCount:n("physics_getDynamicBodyCount","number",[]),_physics_getDynamicBodyTransforms:n("physics_getDynamicBodyTransforms","number",[]),_physics_collectEvents:n("physics_collectEvents",null,[]),_physics_getCollisionEnterCount:n("physics_getCollisionEnterCount","number",[]),_physics_getCollisionEnterBuffer:n("physics_getCollisionEnterBuffer","number",[]),_physics_getCollisionExitCount:n("physics_getCollisionExitCount","number",[]),_physics_getCollisionExitBuffer:n("physics_getCollisionExitBuffer","number",[]),_physics_getSensorEnterCount:n("physics_getSensorEnterCount","number",[]),_physics_getSensorEnterBuffer:n("physics_getSensorEnterBuffer","number",[]),_physics_getSensorExitCount:n("physics_getSensorExitCount","number",[]),_physics_getSensorExitBuffer:n("physics_getSensorExitBuffer","number",[]),_physics_applyForce:n("physics_applyForce",null,["number","number","number"]),_physics_applyImpulse:n("physics_applyImpulse",null,["number","number","number"]),_physics_setLinearVelocity:n("physics_setLinearVelocity",null,["number","number","number"]),_physics_getLinearVelocity:n("physics_getLinearVelocity","number",["number"]),_physics_setGravity:n("physics_setGravity",null,["number","number"]),_physics_getGravity:n("physics_getGravity","number",[]),_physics_setAngularVelocity:n("physics_setAngularVelocity",null,["number","number"]),_physics_getAngularVelocity:n("physics_getAngularVelocity","number",["number"]),_physics_applyTorque:n("physics_applyTorque",null,["number","number"]),_physics_applyAngularImpulse:n("physics_applyAngularImpulse",null,["number","number"]),_physics_updateBodyProperties:n("physics_updateBodyProperties",null,["number","number","number","number","number","number","number"]),get HEAPF32(){return t.HEAPF32},get HEAPU8(){return t.HEAPU8},get HEAPU32(){return t.HEAPU32},_malloc:t._malloc.bind(t),_free:t._free.bind(t)}}const b=o("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),x=o("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),w=o("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),M=o("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),E={Static:0,Kinematic:1,Dynamic:2};var P;function S(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"}(P||(P={}));let A=1;const C=new Map;function v(){throw new Error("Material API not initialized. Call initMaterialAPI() first.")}const D={createShader:(e,t)=>v().createShader(e,t),releaseShader(e){e>0&&v().releaseShader(e)},create(e){const t=A++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??P.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 C.set(t,n),t},get:e=>C.get(e),setUniform(e,t,n){const s=C.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=C.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=C.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=C.get(e);return t?.blendMode??P.Normal},setDepthTest(e,t){const n=C.get(e);n&&(n.depthTest=t)},getShader(e){const t=C.get(e);return t?.shader??0},release(e){C.delete(e)},isValid:e=>C.has(e),releaseAll(){C.clear()},createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??P.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=C.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=A++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return C.set(n,s),n},toAssetData(e,t){const n=C.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=C.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};const B=new Float32Array(256);function T(){throw new Error("Draw API not initialized. Call initDrawAPI() first.")}const R={r:1,g:1,b:1,a:1},U={begin(e){const t=T();try{t.HEAPF32.set(e,0),t.draw_begin(0)}catch(e){h(e,"Draw.begin")}},end(){try{T().draw_end()}catch(e){h(e,"Draw.end")}},line(e,t,n,s=1){try{T().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){h(e,"Draw.line")}},rect(e,t,n,s=!0){try{T().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){h(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{T().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){h(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,r=32){try{T().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)}catch(e){h(e,"Draw.circle")}},circleOutline(e,t,n,s=1,r=32){try{T().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)}catch(e){h(e,"Draw.circleOutline")}},texture(e,t,n,s=R){try{T().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){h(e,"Draw.texture")}},textureRotated(e,t,n,s,r=R){try{T().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)}catch(e){h(e,"Draw.textureRotated")}},setLayer(e){T().draw_setLayer(e)},setDepth(e){T().draw_setDepth(e)},getDrawCallCount:()=>0,getPrimitiveCount:()=>0,setBlendMode(e){T().draw_setBlendMode(e)},setDepthTest(e){T().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=T();s.HEAPF32.set(n,0),s.draw_mesh(e,t,0)}catch(n){h(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=T(),r=D.get(t);if(!r)return;if(U.setBlendMode(r.blendMode),U.setDepthTest(r.depthTest),0===r.uniforms.size)return void U.drawMesh(e,r.shader,n);let i;if(s.HEAPF32.set(n,0),!r.dirty_&&r.cachedBuffer_)i=r.cachedIdx_;else{i=0;let e=0;for(const[t,n]of r.uniforms){const s=H(t);if(!(s<0)){if(S(n))B[i++]=10,B[i++]=s,B[i++]=n.slot??e++,B[i++]=n.textureId;else if("number"==typeof n)B[i++]=1,B[i++]=s,B[i++]=n;else if(Array.isArray(n)){B[i++]=n.length,B[i++]=s;for(let e=0;e<n.length;e++)B[i++]=n[e]}else"w"in n?(B[i++]=4,B[i++]=s,B[i++]=n.x,B[i++]=n.y,B[i++]=n.z,B[i++]=n.w):"z"in n?(B[i++]=3,B[i++]=s,B[i++]=n.x,B[i++]=n.y,B[i++]=n.z):(B[i++]=2,B[i++]=s,B[i++]=n.x,B[i++]=n.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<i)&&(r.cachedBuffer_=new Float32Array(i)),r.cachedBuffer_.set(B.subarray(0,i)),r.cachedIdx_=i,r.dirty_=!1}if(0===i)return void s.draw_mesh(e,r.shader,0);s.HEAPF32.set(r.cachedBuffer_.subarray(0,i),0),s.draw_meshWithUniforms(e,r.shader,0,0,i)}catch(n){h(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},z={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},F=new Set;function H(e){const t=z[e];return void 0!==t?t:(F.has(e)||(F.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(z).join(", ")}`)),-1)}const I=new Map;const V=d({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),$={r:.2,g:.4,b:1,a:.7},L={r:.2,g:1,b:.2,a:.7},O={r:.2,g:1,b:1,a:.7},W={r:1,g:1,b:.2,a:.5},j={r:1,g:.2,b:.2,a:.8},G={r:1,g:.2,b:.2,a:1},k=1.5,N=16;function q(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function X(e){switch(e){case E.Static:return $;case E.Kinematic:return O;default:return L}}function Y(e,t,n,s,r,i){const o=Math.cos(r),a=Math.sin(r),l=[{x:-n,y:-s},{x:n,y:-s},{x:n,y:s},{x:-n,y:s}].map(n=>({x:e+n.x*o-n.y*a,y:t+n.x*a+n.y*o}));for(let e=0;e<4;e++)U.line(l[e],l[(e+1)%4],i,k)}function K(e,t,n,s,r,i){const o=Math.cos(r),a=Math.sin(r),l=(n,s)=>({x:e+n*o-s*a,y:t+n*a+s*o}),c=l(-n,s),u=l(n,s),y=l(-n,-s),d=l(n,-s);U.line(c,y,i,k),U.line(u,d,i,k);for(let e=0;e<N;e++){const t=e/N*Math.PI,r=(e+1)/N*Math.PI,o=l(-n*Math.cos(t),s+n*Math.sin(t)),a=l(-n*Math.cos(r),s+n*Math.sin(r));U.line(o,a,i,k)}for(let e=0;e<N;e++){const t=Math.PI+e/N*Math.PI,r=Math.PI+(e+1)/N*Math.PI,o=l(-n*Math.cos(t),-s+n*Math.sin(t)),a=l(-n*Math.cos(r),-s+n*Math.sin(r));U.line(o,a,i,k)}}function J(e,t,n,s){const r=e+.5*n,i=t+.5*s;U.line({x:e,y:t},{x:r,y:i},j,k);const o=Math.sqrt(n*n+s*s);if(o<1)return;const a=Math.PI/6,l=n/o,c=s/o,u=r-6*(l*Math.cos(a)-c*Math.sin(a)),y=i-6*(l*Math.sin(a)+c*Math.cos(a)),d=r-6*(l*Math.cos(a)+c*Math.sin(a)),p=i-6*(-l*Math.sin(a)+c*Math.cos(a));U.line({x:r,y:i},{x:u,y:y},j,k),U.line({x:r,y:i},{x:d,y:p},j,k)}function Q(e,t,n){const s=e.getResource(V);if(!s||!s.enabled)return;const r=function(e){const t=e.world.getEntitiesWithComponents([l]);for(const n of t){const t=e.world.get(n,l);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=e.world.getEntitiesWithComponents([b,a]);let o=null;s.showVelocity&&e.hasResource(t)&&(o=e.getResource(t));for(const t of i){const n=e.world.get(t,b);if(!n.enabled)continue;const i=e.world.get(t,a),l=i.worldPosition.x,c=i.worldPosition.y,u=q(i.worldRotation);if(s.showColliders){if(e.world.has(t,x)){const s=e.world.get(t,x),i=s.isSensor?W:X(n.bodyType),o=s.offset.x*r,a=s.offset.y*r,y=Math.cos(u),d=Math.sin(u);Y(l+o*y-a*d,c+o*d+a*y,s.halfExtents.x*r,s.halfExtents.y*r,u,i)}if(e.world.has(t,w)){const s=e.world.get(t,w),i=s.isSensor?W:X(n.bodyType),o=s.offset.x*r,a=s.offset.y*r,y=Math.cos(u),d=Math.sin(u),p=l+o*y-a*d,h=c+o*d+a*y;U.circleOutline({x:p,y:h},s.radius*r,i,k,32)}if(e.world.has(t,M)){const s=e.world.get(t,M),i=s.isSensor?W:X(n.bodyType),o=s.offset.x*r,a=s.offset.y*r,y=Math.cos(u),d=Math.sin(u);K(l+o*y-a*d,c+o*d+a*y,s.radius*r,s.halfHeight*r,u,i)}}if(s.showVelocity&&o&&n.bodyType===E.Dynamic){const e=o.getLinearVelocity(t);J(l,c,e.x*r,e.y*r)}}if(s.showContacts&&e.hasResource(n)){const t=e.getResource(n);for(const e of t.collisionEnters)U.circle({x:e.contactX,y:e.contactY},3,G,!0,32)}}function Z(e,t,n){var s,r;e.insertResource(V,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),s="physics-debug-draw",r=()=>{Q(e,t,n)},I.set(s,{fn:r,scene:""})}const ee=d({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),te=d(null,"PhysicsAPI");function ne(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function se(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class re{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(ee,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=m(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([l]);for(const n of t){const t=e.world.get(n,l);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/r,o=e.world;var u;o.onDespawn(e=>{t.has(e)&&(s._physics_destroyBody(e),t.delete(e),n.delete(e))}),e.addSystemToSchedule(f.PostUpdate,function(e,t,n){const s=++_;return{_id:Symbol(`System_${s}_${n?.name}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}([(u=p,{_type:"res",_resource:u})],l=>{const u=o.getEntitiesWithComponents([b,a]),y=new Set;for(const r of u){y.add(r);const l=o.get(r,b),c=o.get(r,a);if(t.has(r)){const e=n.get(r);!e||e.bodyType===l.bodyType&&e.gravityScale===l.gravityScale&&e.linearDamping===l.linearDamping&&e.angularDamping===l.angularDamping&&e.fixedRotation===l.fixedRotation&&e.bullet===l.bullet||(s._physics_updateBodyProperties(r,l.bodyType,l.gravityScale,l.linearDamping,l.angularDamping,l.fixedRotation?1:0,l.bullet?1:0),e.bodyType=l.bodyType,e.gravityScale=l.gravityScale,e.linearDamping=l.linearDamping,e.angularDamping=l.angularDamping,e.fixedRotation=l.fixedRotation,e.bullet=l.bullet)}else{if(!l.enabled)continue;const o=ne(c.worldRotation);s._physics_createBody(r,l.bodyType,c.worldPosition.x*i,c.worldPosition.y*i,o,l.gravityScale,l.linearDamping,l.angularDamping,l.fixedRotation?1:0,l.bullet?1:0),ie(e,s,r),t.add(r),n.set(r,{bodyType:l.bodyType,gravityScale:l.gravityScale,linearDamping:l.linearDamping,angularDamping:l.angularDamping,fixedRotation:l.fixedRotation,bullet:l.bullet})}if(l.bodyType===E.Kinematic){const e=ne(c.worldRotation);s._physics_setBodyTransform(r,c.worldPosition.x*i,c.worldPosition.y*i,e)}}for(const e of t)y.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(l.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),i=r>>2;for(let r=0;r<s;r++){const s=i+4*r,o=t.HEAPU32[s],l=t.HEAPF32[s+1]*n,u=t.HEAPF32[s+2]*n,y=t.HEAPF32[s+3];if(!e.world.valid(o))continue;const d=e.world.get(o,a);if(!d)continue;let p=l,h=u,f=y;if(e.world.has(o,c)){const t=e.world.get(o,c);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,a)){const n=e.world.get(t.entity,a),s=ne(n.worldRotation),r=l-n.worldPosition.x,i=u-n.worldPosition.y,o=Math.cos(-s),c=Math.sin(-s);p=(r*o-i*c)/(0!==n.worldScale.x?n.worldScale.x:1),h=(r*c+i*o)/(0!==n.worldScale.y?n.worldScale.y:1),f=y-s}}d.position.x=p,d.position.y=h;const _=se(f);d.rotation.w=_.w,d.rotation.x=_.x,d.rotation.y=_.y,d.rotation.z=_.z,e.world.insert(o,a,d)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<r;i++){const r=e+6*i;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const i=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<o;n++){const s=e+2*n;i.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],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(ee,{collisionEnters:s,collisionExits:i,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(te,oe._fromModule(s)),Z(e,te,ee),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function ie(e,t,n){const s=e.world;if(s.has(n,x)){const e=s.get(n,x);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,w)){const e=s.get(n,w);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,M)){const e=s.get(n,M);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 oe{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(oe.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)}static setDebugDraw(e,t){const n=e.getResource(V);n&&(n.enabled=t,e.insertResource(V,n))}static setDebugDrawConfig(e,t){const n=e.getResource(V);n&&e.insertResource(V,{...n,...t})}}export{E as BodyType,x as BoxCollider,M as CapsuleCollider,w as CircleCollider,oe as Physics,te as PhysicsAPI,V as PhysicsDebugDraw,ee as PhysicsEvents,re as PhysicsPlugin,b as RigidBody,Q as drawPhysicsDebug,m as loadPhysicsModule,g as loadPhysicsSideModule,Z as setupPhysicsDebugDraw};
//# sourceMappingURL=index.js.map
diff --git a/desktop/public/sdk/esm/spine/index.d.ts b/desktop/public/sdk/esm/spine/index.d.ts
index 000c4a3f1..a1a637489 100644
--- a/desktop/public/sdk/esm/spine/index.d.ts
+++ b/desktop/public/sdk/esm/spine/index.d.ts
@@ -491,6 +491,13 @@ interface ESEngineModule {
postprocess_clearPasses(): void;
postprocess_setOutputTarget(fboId: number): void;
postprocess_setOutputViewport(x: number, y: number, w: number, h: number): void;
+ postprocess_beginScreenCapture(): void;
+ postprocess_endScreenCapture(): void;
+ postprocess_executeScreenPasses(): void;
+ postprocess_addScreenPass(name: string, shaderHandle: number): number;
+ postprocess_clearScreenPasses(): void;
+ postprocess_setScreenUniformFloat(passName: string, uniform: string, value: number): void;
+ postprocess_setScreenUniformVec4(passName: string, uniform: string, x: number, y: number, z: number, w: number): void;
renderer_init(width: number, height: number): void;
renderer_resize(width: number, height: number): void;
renderer_begin(matrixPtr: number, targetHandle: number): void;
@@ -781,6 +788,8 @@ declare class RenderPipeline {
get maskProcessor(): MaskProcessorFn | null;
setMaskProcessor(fn: MaskProcessorFn | null): void;
setActiveScenes(scenes: Set<string> | null): void;
+ beginScreenCapture(): void;
+ endScreenCapture(): void;
render(params: RenderParams): void;
renderCamera(params: CameraRenderParams): void;
private executeDrawCallbacks;
@@ -955,11 +964,6 @@ interface SceneData {
*/
type DrawCallback = (elapsed: number) => void;
-/**
- * @file postprocess.ts
- * @brief Per-camera post-processing effects API
- */
-
interface PassConfig {
name: string;
shader: ShaderHandle;
diff --git a/desktop/public/sdk/esm/spine/index.js b/desktop/public/sdk/esm/spine/index.js
index dc6414a07..9edff7f19 100644
--- a/desktop/public/sdk/esm/spine/index.js
+++ b/desktop/public/sdk/esm/spine/index.js
@@ -1,2 +1,2 @@
-let e=0;function t(t,n){const r=++e;return{_id:Symbol(`Resource_${r}_${n??""}`),_name:n??`Resource_${r}`,_default:t}}t({delta:0,elapsed:0,frameCount:0},"Time");const n=4294967295;function r(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(r);const t={};for(const n in e)t[n]=r(e[n]);return t}let i=0;function a(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function s(e,t){const n=o.get(e)??a().get(e);if(n)return n;const s=function(e,t){const n=++i,a=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=>a?e?{...r(t),...e}:r(t):e?{...t,...e}:{...t}}}(e,t);return a().set(e,s),o.set(e,s),function(e,t,n){const r=globalThis;r.__esengine_registerComponent&&r.__esengine_registerComponent(e,t,n)}(e,t,!1),s}const o=new Map;function l(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return o.set(e,n),n}const u=l("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}});l("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}),l("Camera",{projectionType:1,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),l("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),l("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),l("Parent",{entity:0}),l("Children",{entities:[]}),l("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:4294967295,enabled:!0});const c=l("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),p=0;var d;l("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:3,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:p,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:p,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:n,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:0,enabled:!0}),s("Name",{value:""}),s("SceneOwner",{scene:"",persistent:!1}),s("PostProcessVolume",{effects:[]}),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"}(d||(d={}));const h=t(null,"Assets");function m(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}async function _(e,t){if(!t)throw new Error("SpineModuleLoader: factory parameter is required. Pass the Spine WASM factory function explicitly via loadSpineModule(url, factory).");const n=await t();return{raw:n,api:m(n)}}class g{constructor(e,t){this.raw_=e,this.api_=t,this.listeners_=new Map}get raw(){return this.raw_}loadSkeleton(e,t,n){let r,i;if("string"==typeof e){const t=(new TextEncoder).encode(e);i=t.length,r=this.raw_._malloc(i+1),this.raw_.HEAPU8.set(t,r),this.raw_.HEAPU8[r+i]=0}else i=e.length,r=this.raw_._malloc(i),this.raw_.HEAPU8.set(e,r);const a=this.api_.loadSkeleton(r,i,t,t.length,n);return this.raw_._free(r),a}getLastError(){return this.api_.getLastError()}unloadSkeleton(e){this.api_.unloadSkeleton(e)}getAtlasPageCount(e){return this.api_.getAtlasPageCount(e)}getAtlasPageTextureName(e,t){return this.api_.getAtlasPageTextureName(e,t)}setAtlasPageTexture(e,t,n,r,i){this.api_.setAtlasPageTexture(e,t,n,r,i)}createInstance(e){return this.api_.createInstance(e)}destroyInstance(e){this.api_.destroyInstance(e),this.listeners_.delete(e)}play(e,t,n=!0,r=0){return!!this.api_.playAnimation(e,t,n,r)}addAnimation(e,t,n=!0,r=0,i=0){return!!this.api_.addAnimation(e,t,n,r,i)}setSkin(e,t){this.api_.setSkin(e,t)}update(e,t){this.api_.update(e,t)}getAnimations(e){const t=this.api_.getAnimations(e);try{return JSON.parse(t)}catch{return[]}}getSkins(e){const t=this.api_.getSkins(e);try{return JSON.parse(t)}catch{return[]}}getBonePosition(e,t){const n=this.raw_._malloc(4),r=this.raw_._malloc(4);if(!this.api_.getBonePosition(e,t,n,r))return this.raw_._free(n),this.raw_._free(r),null;const i=this.raw_.HEAPF32[n>>2],a=this.raw_.HEAPF32[r>>2];return this.raw_._free(n),this.raw_._free(r),{x:i,y:a}}getBoneRotation(e,t){return this.api_.getBoneRotation(e,t)}getBounds(e){const t=this.raw_._malloc(16);this.api_.getBounds(e,t,t+4,t+8,t+12);const n=this.raw_.HEAPF32,r=t>>2,i={x:n[r],y:n[r+1],width:n[r+2],height:n[r+3]};return this.raw_._free(t),i}extractMeshBatches(e){const t=this.api_.getMeshBatchCount(e),n=[],r=this.raw_._malloc(8),i=r,a=r+4;for(let r=0;r<t;r++){const t=this.api_.getMeshBatchVertexCount(e,r),s=this.api_.getMeshBatchIndexCount(e,r);if(t<=0||s<=0)continue;const o=8*t*4,l=2*s,u=this.raw_._malloc(o),c=this.raw_._malloc(l);this.api_.getMeshBatchData(e,r,u,c,i,a);const p=new Float32Array(this.raw_.HEAPF32.buffer,u,8*t),d=new Uint16Array(this.raw_.HEAPU8.buffer,c,s);n.push({vertices:new Float32Array(p),indices:new Uint16Array(d),textureId:this.raw_.HEAPU32[i>>2],blendMode:this.raw_.HEAPU32[a>>2]}),this.raw_._free(u),this.raw_._free(c)}return this.raw_._free(r),n}on(e,t,n){this.listeners_.has(e)||this.listeners_.set(e,new Map);const r=this.listeners_.get(e);r.has(t)||r.set(t,new Set),r.get(t).add(n)}off(e,t,n){const r=this.listeners_.get(e);if(!r)return;const i=r.get(t);i&&i.delete(n)}removeAllListeners(e){this.listeners_.delete(e)}}const b=t(null,"SpineController"),f=new Float32Array(16);function w(e,t,n,r){const i=e.worldScale.x*t*(n?-1:1),a=e.worldScale.y*t*(r?-1:1),s=e.worldScale.z,o=e.worldRotation.x,l=e.worldRotation.y,u=e.worldRotation.z,c=e.worldRotation.w,p=o+o,d=l+l,h=u+u,m=o*p,_=o*d,g=o*h,b=l*d,w=l*h,y=u*h,S=c*p,x=c*d,P=c*h;return f[0]=(1-(b+y))*i,f[1]=(_+P)*i,f[2]=(g-x)*i,f[3]=0,f[4]=(_-P)*a,f[5]=(1-(m+y))*a,f[6]=(w+S)*a,f[7]=0,f[8]=(g+x)*s,f[9]=(w-S)*s,f[10]=(1-(m+b))*s,f[11]=0,f[12]=e.worldPosition.x,f[13]=e.worldPosition.y,f[14]=e.worldPosition.z,f[15]=1,f}class y{constructor(e,t){this.wasmUrl_=e,this.factory_=t}build(e){const t=e.wasmModule,n=_(this.wasmUrl_,this.factory_).then(({raw:n,api:r})=>{const i=new g(n,r);e.insertResource(b,i),e.hasResource(h)&&e.getResource(h).setSpineController(i);const a=new Map,s=new Map,o=new Map,l={_id:Symbol("SpineAutoSystem"),_name:"SpineAutoSystem",_params:[],_fn:()=>{const t=e.world,n=e.hasResource(h)?e.getResource(h):null;if(!n)return;const r=t.getEntitiesWithComponents([c]),l=new Set;for(const e of r){l.add(e);const r=t.get(e,c),u=`${r.skeletonPath}:${r.atlasPath}`;if(!a.has(e)||s.get(e)!==u){a.has(e)&&(i.destroyInstance(a.get(e)),a.delete(e),s.delete(e),o.delete(e));const t=n.getSpineSkeletonHandle(r.skeletonPath,r.atlasPath);if(void 0===t)continue;const l=i.createInstance(t);if(l<0)continue;a.set(e,l),s.set(e,u),r.skin&&i.setSkin(l,r.skin),r.animation&&i.play(l,r.animation,r.loop),o.set(e,{animation:r.animation,skin:r.skin,loop:r.loop});continue}const p=o.get(e);if(!p)continue;const d=a.get(e);p.skin!==r.skin&&(i.setSkin(d,r.skin),p.skin=r.skin),p.animation===r.animation&&p.loop===r.loop||(r.animation&&i.play(d,r.animation,r.loop),p.animation=r.animation,p.loop=r.loop)}for(const[e,t]of a)l.has(e)||(i.destroyInstance(t),a.delete(e),s.delete(e),o.delete(e))}};if(e.addSystemToSchedule(d.PreUpdate,l),!e.pipeline?.spineRenderer){let n=0;e.setSpineRenderer((r,s)=>{let o=s-n;n=s,(o<=0||o>.5)&&(o=1/60);const l=e.world;for(const[e,n]of a){const r=l.has(e,c)?l.get(e,c):null,a=!1!==r?.playing,s=r?.timeScale??1;let p;if(a&&i.update(n,o*s),l.has(e,u)){p=w(l.get(e,u),r?.skeletonScale??1,r?.flipX??!1,r?.flipY??!1)}const d=r?.color;U(t,i,n,p,d)}})}return{controller:i,coreModule:t}});e.insertResource(b,null),n.catch(()=>{}),e.spineInitPromise=n}}let S=new Float32Array(0),x=0,P=0,A=0,M=0,k=0,B=null;function C(e,t,n,r){if(t&&n>=r)return[t,n];t&&e._free(t);const i=2*r;return[e._malloc(i),i]}function U(e,t,n,r,i){B&&B!==e&&B&&(x&&(B._free(x),x=0,P=0),A&&(B._free(A),A=0,M=0),k&&(B._free(k),k=0),B=null),B=e;const a=t.extractMeshBatches(n);r&&(k||(k=e._malloc(64)),e.HEAPF32.set(r,k>>2));const s=i&&(1!==i.r||1!==i.g||1!==i.b||1!==i.a);for(const t of a){let n=t.vertices;if(s){const e=t.blendMode>=4;S.length<n.length&&(S=new Float32Array(2*n.length)),S.set(n);const r=S.subarray(0,n.length);for(let t=0;t<r.length;t+=8)e?(r[t+4]*=i.r*i.a,r[t+5]*=i.g*i.a,r[t+6]*=i.b*i.a):(r[t+4]*=i.r,r[t+5]*=i.g,r[t+6]*=i.b),r[t+7]*=i.a;n=r}const a=n.byteLength,o=t.indices.byteLength;[x,P]=C(e,x,P,a),[A,M]=C(e,A,M,o),e.HEAPF32.set(n,x>>2),new Uint16Array(e.HEAPU8.buffer,A,t.indices.length).set(t.indices),e.renderer_submitTriangles(x,n.length/8,A,t.indices.length,t.textureId,t.blendMode,r?k:0)}}export{g as SpineModuleController,y as SpinePlugin,b as SpineResource,_ as loadSpineModule,U as submitSpineMeshesToCore,m as wrapSpineModule};
+let e=0;function t(t,n){const r=++e;return{_id:Symbol(`Resource_${r}_${n??""}`),_name:n??`Resource_${r}`,_default:t}}t({delta:0,elapsed:0,frameCount:0},"Time");const n=4294967295;function r(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(r);const t={};for(const n in e)t[n]=r(e[n]);return t}let i=0;function a(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function s(e,t){const n=o.get(e)??a().get(e);if(n)return n;const s=function(e,t){const n=++i,a=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=>a?e?{...r(t),...e}:r(t):e?{...t,...e}:{...t}}}(e,t);return a().set(e,s),o.set(e,s),function(e,t,n){const r=globalThis;r.__esengine_registerComponent&&r.__esengine_registerComponent(e,t,n)}(e,t,!1),s}const o=new Map;function l(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return o.set(e,n),n}const u=l("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}});l("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}),l("Camera",{projectionType:1,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),l("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),l("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),l("Parent",{entity:0}),l("Children",{entities:[]}),l("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:4294967295,enabled:!0});const c=l("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),p=0;var d;l("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:3,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:p,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:p,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:n,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:0,enabled:!0}),s("Name",{value:""}),s("SceneOwner",{scene:"",persistent:!1}),s("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0}),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"}(d||(d={}));const h=t(null,"Assets");function m(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}async function _(e,t){if(!t)throw new Error("SpineModuleLoader: factory parameter is required. Pass the Spine WASM factory function explicitly via loadSpineModule(url, factory).");const n=await t();return{raw:n,api:m(n)}}class g{constructor(e,t){this.raw_=e,this.api_=t,this.listeners_=new Map}get raw(){return this.raw_}loadSkeleton(e,t,n){let r,i;if("string"==typeof e){const t=(new TextEncoder).encode(e);i=t.length,r=this.raw_._malloc(i+1),this.raw_.HEAPU8.set(t,r),this.raw_.HEAPU8[r+i]=0}else i=e.length,r=this.raw_._malloc(i),this.raw_.HEAPU8.set(e,r);const a=this.api_.loadSkeleton(r,i,t,t.length,n);return this.raw_._free(r),a}getLastError(){return this.api_.getLastError()}unloadSkeleton(e){this.api_.unloadSkeleton(e)}getAtlasPageCount(e){return this.api_.getAtlasPageCount(e)}getAtlasPageTextureName(e,t){return this.api_.getAtlasPageTextureName(e,t)}setAtlasPageTexture(e,t,n,r,i){this.api_.setAtlasPageTexture(e,t,n,r,i)}createInstance(e){return this.api_.createInstance(e)}destroyInstance(e){this.api_.destroyInstance(e),this.listeners_.delete(e)}play(e,t,n=!0,r=0){return!!this.api_.playAnimation(e,t,n,r)}addAnimation(e,t,n=!0,r=0,i=0){return!!this.api_.addAnimation(e,t,n,r,i)}setSkin(e,t){this.api_.setSkin(e,t)}update(e,t){this.api_.update(e,t)}getAnimations(e){const t=this.api_.getAnimations(e);try{return JSON.parse(t)}catch{return[]}}getSkins(e){const t=this.api_.getSkins(e);try{return JSON.parse(t)}catch{return[]}}getBonePosition(e,t){const n=this.raw_._malloc(4),r=this.raw_._malloc(4);if(!this.api_.getBonePosition(e,t,n,r))return this.raw_._free(n),this.raw_._free(r),null;const i=this.raw_.HEAPF32[n>>2],a=this.raw_.HEAPF32[r>>2];return this.raw_._free(n),this.raw_._free(r),{x:i,y:a}}getBoneRotation(e,t){return this.api_.getBoneRotation(e,t)}getBounds(e){const t=this.raw_._malloc(16);this.api_.getBounds(e,t,t+4,t+8,t+12);const n=this.raw_.HEAPF32,r=t>>2,i={x:n[r],y:n[r+1],width:n[r+2],height:n[r+3]};return this.raw_._free(t),i}extractMeshBatches(e){const t=this.api_.getMeshBatchCount(e),n=[],r=this.raw_._malloc(8),i=r,a=r+4;for(let r=0;r<t;r++){const t=this.api_.getMeshBatchVertexCount(e,r),s=this.api_.getMeshBatchIndexCount(e,r);if(t<=0||s<=0)continue;const o=8*t*4,l=2*s,u=this.raw_._malloc(o),c=this.raw_._malloc(l);this.api_.getMeshBatchData(e,r,u,c,i,a);const p=new Float32Array(this.raw_.HEAPF32.buffer,u,8*t),d=new Uint16Array(this.raw_.HEAPU8.buffer,c,s);n.push({vertices:new Float32Array(p),indices:new Uint16Array(d),textureId:this.raw_.HEAPU32[i>>2],blendMode:this.raw_.HEAPU32[a>>2]}),this.raw_._free(u),this.raw_._free(c)}return this.raw_._free(r),n}on(e,t,n){this.listeners_.has(e)||this.listeners_.set(e,new Map);const r=this.listeners_.get(e);r.has(t)||r.set(t,new Set),r.get(t).add(n)}off(e,t,n){const r=this.listeners_.get(e);if(!r)return;const i=r.get(t);i&&i.delete(n)}removeAllListeners(e){this.listeners_.delete(e)}}const b=t(null,"SpineController"),f=new Float32Array(16);function w(e,t,n,r){const i=e.worldScale.x*t*(n?-1:1),a=e.worldScale.y*t*(r?-1:1),s=e.worldScale.z,o=e.worldRotation.x,l=e.worldRotation.y,u=e.worldRotation.z,c=e.worldRotation.w,p=o+o,d=l+l,h=u+u,m=o*p,_=o*d,g=o*h,b=l*d,w=l*h,y=u*h,S=c*p,x=c*d,P=c*h;return f[0]=(1-(b+y))*i,f[1]=(_+P)*i,f[2]=(g-x)*i,f[3]=0,f[4]=(_-P)*a,f[5]=(1-(m+y))*a,f[6]=(w+S)*a,f[7]=0,f[8]=(g+x)*s,f[9]=(w-S)*s,f[10]=(1-(m+b))*s,f[11]=0,f[12]=e.worldPosition.x,f[13]=e.worldPosition.y,f[14]=e.worldPosition.z,f[15]=1,f}class y{constructor(e,t){this.wasmUrl_=e,this.factory_=t}build(e){const t=e.wasmModule,n=_(this.wasmUrl_,this.factory_).then(({raw:n,api:r})=>{const i=new g(n,r);e.insertResource(b,i),e.hasResource(h)&&e.getResource(h).setSpineController(i);const a=new Map,s=new Map,o=new Map,l={_id:Symbol("SpineAutoSystem"),_name:"SpineAutoSystem",_params:[],_fn:()=>{const t=e.world,n=e.hasResource(h)?e.getResource(h):null;if(!n)return;const r=t.getEntitiesWithComponents([c]),l=new Set;for(const e of r){l.add(e);const r=t.get(e,c),u=`${r.skeletonPath}:${r.atlasPath}`;if(!a.has(e)||s.get(e)!==u){a.has(e)&&(i.destroyInstance(a.get(e)),a.delete(e),s.delete(e),o.delete(e));const t=n.getSpineSkeletonHandle(r.skeletonPath,r.atlasPath);if(void 0===t)continue;const l=i.createInstance(t);if(l<0)continue;a.set(e,l),s.set(e,u),r.skin&&i.setSkin(l,r.skin),r.animation&&i.play(l,r.animation,r.loop),o.set(e,{animation:r.animation,skin:r.skin,loop:r.loop});continue}const p=o.get(e);if(!p)continue;const d=a.get(e);p.skin!==r.skin&&(i.setSkin(d,r.skin),p.skin=r.skin),p.animation===r.animation&&p.loop===r.loop||(r.animation&&i.play(d,r.animation,r.loop),p.animation=r.animation,p.loop=r.loop)}for(const[e,t]of a)l.has(e)||(i.destroyInstance(t),a.delete(e),s.delete(e),o.delete(e))}};if(e.addSystemToSchedule(d.PreUpdate,l),!e.pipeline?.spineRenderer){let n=0;e.setSpineRenderer((r,s)=>{let o=s-n;n=s,(o<=0||o>.5)&&(o=1/60);const l=e.world;for(const[e,n]of a){const r=l.has(e,c)?l.get(e,c):null,a=!1!==r?.playing,s=r?.timeScale??1;let p;if(a&&i.update(n,o*s),l.has(e,u)){p=w(l.get(e,u),r?.skeletonScale??1,r?.flipX??!1,r?.flipY??!1)}const d=r?.color;U(t,i,n,p,d)}})}return{controller:i,coreModule:t}});e.insertResource(b,null),n.catch(()=>{}),e.spineInitPromise=n}}let S=new Float32Array(0),x=0,P=0,A=0,M=0,k=0,B=null;function C(e,t,n,r){if(t&&n>=r)return[t,n];t&&e._free(t);const i=2*r;return[e._malloc(i),i]}function U(e,t,n,r,i){B&&B!==e&&B&&(x&&(B._free(x),x=0,P=0),A&&(B._free(A),A=0,M=0),k&&(B._free(k),k=0),B=null),B=e;const a=t.extractMeshBatches(n);r&&(k||(k=e._malloc(64)),e.HEAPF32.set(r,k>>2));const s=i&&(1!==i.r||1!==i.g||1!==i.b||1!==i.a);for(const t of a){let n=t.vertices;if(s){const e=t.blendMode>=4;S.length<n.length&&(S=new Float32Array(2*n.length)),S.set(n);const r=S.subarray(0,n.length);for(let t=0;t<r.length;t+=8)e?(r[t+4]*=i.r*i.a,r[t+5]*=i.g*i.a,r[t+6]*=i.b*i.a):(r[t+4]*=i.r,r[t+5]*=i.g,r[t+6]*=i.b),r[t+7]*=i.a;n=r}const a=n.byteLength,o=t.indices.byteLength;[x,P]=C(e,x,P,a),[A,M]=C(e,A,M,o),e.HEAPF32.set(n,x>>2),new Uint16Array(e.HEAPU8.buffer,A,t.indices.length).set(t.indices),e.renderer_submitTriangles(x,n.length/8,A,t.indices.length,t.textureId,t.blendMode,r?k:0)}}export{g as SpineModuleController,y as SpinePlugin,b as SpineResource,_ as loadSpineModule,U as submitSpineMeshesToCore,m as wrapSpineModule};
//# sourceMappingURL=index.js.map
diff --git a/desktop/public/sdk/esm/wasm.d.ts b/desktop/public/sdk/esm/wasm.d.ts
index 6d1f5d7c8..c76f2a463 100644
--- a/desktop/public/sdk/esm/wasm.d.ts
+++ b/desktop/public/sdk/esm/wasm.d.ts
@@ -451,6 +451,13 @@ interface ESEngineModule {
postprocess_clearPasses(): void;
postprocess_setOutputTarget(fboId: number): void;
postprocess_setOutputViewport(x: number, y: number, w: number, h: number): void;
+ postprocess_beginScreenCapture(): void;
+ postprocess_endScreenCapture(): void;
+ postprocess_executeScreenPasses(): void;
+ postprocess_addScreenPass(name: string, shaderHandle: number): number;
+ postprocess_clearScreenPasses(): void;
+ postprocess_setScreenUniformFloat(passName: string, uniform: string, value: number): void;
+ postprocess_setScreenUniformVec4(passName: string, uniform: string, x: number, y: number, z: number, w: number): void;
renderer_init(width: number, height: number): void;
renderer_resize(width: number, height: number): void;
renderer_begin(matrixPtr: number, targetHandle: number): void;
diff --git a/desktop/public/wasm/esengine.single.js b/desktop/public/wasm/esengine.single.js
index 5a9dbdb06..31e7fc1e9 100644
Binary files a/desktop/public/wasm/esengine.single.js and b/desktop/public/wasm/esengine.single.js differ
diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json
index c74912aa2..394b6d3d2 100644
--- a/desktop/src-tauri/tauri.conf.json
+++ b/desktop/src-tauri/tauri.conf.json
@@ -23,7 +23,7 @@
}
],
"security": {
- "csp": "default-src 'self' asset: http://asset.localhost ipc: http://ipc.localhost; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' 'unsafe-eval' blob:; img-src 'self' asset: http://asset.localhost data:; style-src 'self' 'unsafe-inline'",
+ "csp": "default-src 'self' asset: http://asset.localhost ipc: http://ipc.localhost; connect-src 'self' blob:; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' 'unsafe-eval' blob:; img-src 'self' asset: http://asset.localhost data:; style-src 'self' 'unsafe-inline'",
"dangerousDisableAssetCspModification": [
"style-src"
],
diff --git a/editor/src/panels/inspector/PostProcessVolumeInspector.ts b/editor/src/panels/inspector/PostProcessVolumeInspector.ts
index 62c5f2655..21c908f9b 100644
--- a/editor/src/panels/inspector/PostProcessVolumeInspector.ts
+++ b/editor/src/panels/inspector/PostProcessVolumeInspector.ts
@@ -8,10 +8,11 @@ import {
getEffectDef,
syncPostProcessVolume,
type PostProcessEffectData,
+ type PostProcessVolumeData,
} from 'esengine';
import type { ComponentInspectorContext, ComponentInspectorInstance } from './InspectorRegistry';
import { registerComponentInspector } from './InspectorRegistry';
-import { createFloatEditor } from './SharedEditors';
+import { createFloatEditor, createIntEditor, createVec2Editor } from './SharedEditors';
import { icons } from '../../utils/icons';
function cloneEffects(effects: PostProcessEffectData[]): PostProcessEffectData[] {
@@ -22,29 +23,60 @@ function cloneEffects(effects: PostProcessEffectData[]): PostProcessEffectData[]
}));
}
+interface VolumeProps {
+ isGlobal: boolean;
+ shape: 'box' | 'sphere';
+ size: { x: number; y: number };
+ priority: number;
+ weight: number;
+ blendDistance: number;
+}
+
+function extractVolumeProps(data: Record<string, unknown>): VolumeProps {
+ return {
+ isGlobal: (data.isGlobal as boolean) ?? true,
+ shape: (data.shape as 'box' | 'sphere') ?? 'box',
+ size: (data.size as { x: number; y: number }) ?? { x: 5, y: 5 },
+ priority: (data.priority as number) ?? 0,
+ weight: (data.weight as number) ?? 1,
+ blendDistance: (data.blendDistance as number) ?? 0,
+ };
+}
+
+function buildVolumeData(effects: PostProcessEffectData[], props: VolumeProps): PostProcessVolumeData {
+ return { effects, ...props };
+}
+
function renderInspector(
container: HTMLElement,
ctx: ComponentInspectorContext,
): ComponentInspectorInstance {
let currentEffects: PostProcessEffectData[] =
(ctx.componentData.effects as PostProcessEffectData[]) ?? [];
+ let volumeProps = extractVolumeProps(ctx.componentData);
- function emitChange(newEffects: PostProcessEffectData[]): void {
+ function emitEffectsChange(newEffects: PostProcessEffectData[]): void {
const old = cloneEffects(currentEffects);
currentEffects = newEffects;
ctx.onChange('effects', old, cloneEffects(newEffects));
+ syncToRuntime();
+ }
+ function emitPropChange<K extends keyof VolumeProps>(key: K, oldVal: VolumeProps[K], newVal: VolumeProps[K]): void {
+ volumeProps[key] = newVal;
+ ctx.onChange(key, oldVal, newVal);
syncToRuntime();
}
function syncToRuntime(): void {
- syncPostProcessVolume(ctx.entity, { effects: currentEffects });
+ syncPostProcessVolume(ctx.entity, buildVolumeData(currentEffects, volumeProps));
}
function rebuild(): void {
container.innerHTML = '';
- renderEffectList(container, currentEffects, emitChange);
- renderAddButton(container, currentEffects, emitChange);
+ renderVolumeProps(container, volumeProps, emitPropChange, rebuild);
+ renderEffectList(container, currentEffects, emitEffectsChange);
+ renderAddButton(container, currentEffects, emitEffectsChange);
}
rebuild();
@@ -53,14 +85,117 @@ function renderInspector(
return {
dispose() {},
update(data: Record<string, unknown>) {
- const newEffects = (data.effects as PostProcessEffectData[]) ?? [];
- currentEffects = newEffects;
+ currentEffects = (data.effects as PostProcessEffectData[]) ?? [];
+ volumeProps = extractVolumeProps(data);
rebuild();
syncToRuntime();
},
};
}
+function renderVolumeProps(
+ container: HTMLElement,
+ props: VolumeProps,
+ onChange: <K extends keyof VolumeProps>(key: K, oldVal: VolumeProps[K], newVal: VolumeProps[K]) => void,
+ rebuild: () => void,
+): void {
+ const section = document.createElement('div');
+ section.className = 'es-pp-volume-props';
+
+ const createRow = (label: string): { row: HTMLElement; value: HTMLElement } => {
+ const row = document.createElement('div');
+ row.className = 'es-property-row';
+ const propLabel = document.createElement('span');
+ propLabel.className = 'es-property-label';
+ propLabel.textContent = label;
+ const propValue = document.createElement('div');
+ propValue.className = 'es-property-value';
+ row.appendChild(propLabel);
+ row.appendChild(propValue);
+ return { row, value: propValue };
+ };
+
+ // isGlobal
+ {
+ const { row, value } = createRow('Is Global');
+ const input = document.createElement('input');
+ input.type = 'checkbox';
+ input.className = 'es-input es-input-checkbox';
+ input.checked = props.isGlobal;
+ input.addEventListener('change', () => {
+ const old = props.isGlobal;
+ onChange('isGlobal', old, input.checked);
+ rebuild();
+ });
+ value.appendChild(input);
+ section.appendChild(row);
+ }
+
+ // priority
+ {
+ const { row, value } = createRow('Priority');
+ createIntEditor(value, props.priority, (v) => {
+ const old = props.priority;
+ onChange('priority', old, v);
+ });
+ section.appendChild(row);
+ }
+
+ // weight
+ {
+ const { row, value } = createRow('Weight');
+ createFloatEditor(value, props.weight, (v) => {
+ const old = props.weight;
+ onChange('weight', old, v);
+ }, 0, 1, 0.01);
+ section.appendChild(row);
+ }
+
+ if (!props.isGlobal) {
+ // shape
+ {
+ const { row, value } = createRow('Shape');
+ const select = document.createElement('select');
+ select.className = 'es-input es-input-select';
+ for (const opt of ['box', 'sphere'] as const) {
+ const option = document.createElement('option');
+ option.value = opt;
+ option.textContent = opt.charAt(0).toUpperCase() + opt.slice(1);
+ if (opt === props.shape) option.selected = true;
+ select.appendChild(option);
+ }
+ select.addEventListener('change', () => {
+ const old = props.shape;
+ onChange('shape', old, select.value as 'box' | 'sphere');
+ });
+ value.appendChild(select);
+ section.appendChild(row);
+ }
+
+ // size
+ {
+ const { row, value } = createRow('Size');
+ createVec2Editor(value, { ...props.size }, (v) => {
+ const old = { ...props.size };
+ onChange('size', old, v);
+ });
+ section.appendChild(row);
+ }
+
+ // blendDistance
+ {
+ const { row, value } = createRow('Blend Distance');
+ createFloatEditor(value, props.blendDistance, (v) => {
+ const old = props.blendDistance;
+ onChange('blendDistance', old, v);
+ }, 0, undefined, 0.1);
+ section.appendChild(row);
+ }
+ }
+
+ container.appendChild(section);
+}
+
function renderEffectList(
container: HTMLElement,
effects: PostProcessEffectData[],
diff --git a/editor/src/renderer/EditorSceneRenderer.ts b/editor/src/renderer/EditorSceneRenderer.ts
index f62e7ac9c..2d693351e 100644
--- a/editor/src/renderer/EditorSceneRenderer.ts
+++ b/editor/src/renderer/EditorSceneRenderer.ts
@@ -9,6 +9,7 @@ import {
syncPostProcessVolume,
cleanupPostProcessVolume,
type PostProcessEffectData,
+ type PostProcessVolumeData,
} from 'esengine';
import type { SpineModuleController } from 'esengine/spine';
import type { SceneData, ComponentData } from '../types/SceneTypes';
@@ -511,13 +512,24 @@ export class EditorSceneRenderer {
return -1;
}
+ private extractVolumeData(data: Record<string, unknown>): PostProcessVolumeData {
+ return {
+ effects: (data.effects as PostProcessEffectData[]) ?? [],
+ isGlobal: (data.isGlobal as boolean) ?? true,
+ shape: (data.shape as 'box' | 'sphere') ?? 'box',
+ size: (data.size as { x: number; y: number }) ?? { x: 5, y: 5 },
+ priority: (data.priority as number) ?? 0,
+ weight: (data.weight as number) ?? 1,
+ blendDistance: (data.blendDistance as number) ?? 0,
+ };
+ }
+
private syncPostProcessVolumeForEntity(entityId: number): void {
const entityData = this.store_?.getEntityData(entityId);
if (!entityData) return;
const ppComp = entityData.components.find(c => c.type === 'PostProcessVolume');
if (ppComp) {
- const effects = (ppComp.data.effects as PostProcessEffectData[]) ?? [];
- syncPostProcessVolume(entityId, { effects });
+ syncPostProcessVolume(entityId, this.extractVolumeData(ppComp.data));
} else {
cleanupPostProcessVolume(entityId);
}
@@ -528,8 +540,7 @@ export class EditorSceneRenderer {
for (const entity of this.store_.scene.entities) {
const ppComp = entity.components.find(c => c.type === 'PostProcessVolume');
if (ppComp) {
- const effects = (ppComp.data.effects as PostProcessEffectData[]) ?? [];
- syncPostProcessVolume(entity.id, { effects });
+ syncPostProcessVolume(entity.id, this.extractVolumeData(ppComp.data));
}
}
}
diff --git a/sdk/src/app.ts b/sdk/src/app.ts
index ce3e37ae2..adb544359 100644
--- a/sdk/src/app.ts
+++ b/sdk/src/app.ts
@@ -766,6 +766,7 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): A
width, height, elapsed,
});
} else {
+ pipeline.beginScreenCapture();
for (const cam of cameras) {
const vp = cam.viewportRect;
const px = Math.round(vp.x * width);
@@ -781,6 +782,7 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): A
cameraEntity: cam.entity,
});
}
+ pipeline.endScreenCapture();
Renderer.setViewport(0, 0, width, height);
}
}
diff --git a/sdk/src/component.ts b/sdk/src/component.ts
index 85a002051..6e80faf18 100644
--- a/sdk/src/component.ts
+++ b/sdk/src/component.ts
@@ -530,10 +530,22 @@ export const SceneOwner = defineComponent<SceneOwnerData>('SceneOwner', {
export interface PostProcessVolumeData {
effects: { type: string; enabled: boolean; uniforms: Record<string, number> }[];
+ isGlobal: boolean;
+ shape: 'box' | 'sphere';
+ size: { x: number; y: number };
+ priority: number;
+ weight: number;
+ blendDistance: number;
}
export const PostProcessVolume = defineComponent<PostProcessVolumeData>('PostProcessVolume', {
effects: [],
+ isGlobal: true,
+ shape: 'box',
+ size: { x: 5, y: 5 },
+ priority: 0,
+ weight: 1,
+ blendDistance: 0,
});
export type {
diff --git a/sdk/src/physics/PhysicsDebugDraw.ts b/sdk/src/physics/PhysicsDebugDraw.ts
new file mode 100644
index 000000000..7068799e2
--- /dev/null
+++ b/sdk/src/physics/PhysicsDebugDraw.ts
@@ -0,0 +1,268 @@
+import type { App } from '../app';
+import type { Color } from '../types';
+import type { TransformData, CanvasData } from '../component';
+import type { ResourceDef } from '../resource';
+import type { RigidBodyData, BoxColliderData, CircleColliderData, CapsuleColliderData } from './PhysicsComponents';
+import type { PhysicsEventsData } from './PhysicsPlugin';
+import { Transform, Canvas } from '../component';
+import { Draw } from '../draw';
+import { defineResource } from '../resource';
+import { registerDrawCallback } from '../customDraw';
+import { RigidBody, BoxCollider, CircleCollider, CapsuleCollider, BodyType } from './PhysicsComponents';
+
+export interface PhysicsDebugDrawConfig {
+ enabled: boolean;
+ showColliders: boolean;
+ showVelocity: boolean;
+ showContacts: boolean;
+}
+
+export const PhysicsDebugDraw = defineResource<PhysicsDebugDrawConfig>({
+ enabled: false,
+ showColliders: true,
+ showVelocity: false,
+ showContacts: false,
+}, 'PhysicsDebugDraw');
+
+interface VelocityProvider {
+ getLinearVelocity(entity: number): { x: number; y: number };
+}
+
+const STATIC_COLOR: Color = { r: 0.2, g: 0.4, b: 1.0, a: 0.7 };
+const DYNAMIC_COLOR: Color = { r: 0.2, g: 1.0, b: 0.2, a: 0.7 };
+const KINEMATIC_COLOR: Color = { r: 0.2, g: 1.0, b: 1.0, a: 0.7 };
+const SENSOR_COLOR: Color = { r: 1.0, g: 1.0, b: 0.2, a: 0.5 };
+const VELOCITY_COLOR: Color = { r: 1.0, g: 0.2, b: 0.2, a: 0.8 };
+const CONTACT_COLOR: Color = { r: 1.0, g: 0.2, b: 0.2, a: 1.0 };
+const DEBUG_LINE_THICKNESS = 1.5;
+const CONTACT_POINT_RADIUS = 3;
+const VELOCITY_SCALE = 0.5;
+const CIRCLE_SEGMENTS = 32;
+const CAPSULE_ARC_SEGMENTS = 16;
+
+function quatToAngleZ(q: { w: number; x: number; y: number; z: number }): number {
+ return Math.atan2(2 * (q.w * q.z + q.x * q.y), 1 - 2 * (q.y * q.y + q.z * q.z));
+}
+
+function bodyTypeColor(bodyType: number): Color {
+ switch (bodyType) {
+ case BodyType.Static: return STATIC_COLOR;
+ case BodyType.Kinematic: return KINEMATIC_COLOR;
+ case BodyType.Dynamic: return DYNAMIC_COLOR;
+ default: return DYNAMIC_COLOR;
+ }
+}
+
+function readPixelsPerUnit(app: App): number {
+ const entities = app.world.getEntitiesWithComponents([Canvas]);
+ for (const entity of entities) {
+ const canvas = app.world.get(entity, Canvas) as CanvasData;
+ if (canvas && canvas.pixelsPerUnit) {
+ return canvas.pixelsPerUnit;
+ }
+ }
+ return 100;
+}
+
+function drawRotatedBox(
+ cx: number, cy: number,
+ halfW: number, halfH: number,
+ angle: number, color: Color,
+): void {
+ const cos = Math.cos(angle);
+ const sin = Math.sin(angle);
+ const corners = [
+ { x: -halfW, y: -halfH },
+ { x: halfW, y: -halfH },
+ { x: halfW, y: halfH },
+ { x: -halfW, y: halfH },
+ ];
+ const pts = corners.map(c => ({
+ x: cx + c.x * cos - c.y * sin,
+ y: cy + c.x * sin + c.y * cos,
+ }));
+ for (let i = 0; i < 4; i++) {
+ Draw.line(pts[i], pts[(i + 1) % 4], color, DEBUG_LINE_THICKNESS);
+ }
+}
+
+function drawCapsule(
+ cx: number, cy: number,
+ radius: number, halfHeight: number,
+ angle: number, color: Color,
+): void {
+ const cos = Math.cos(angle);
+ const sin = Math.sin(angle);
+
+ const toWorld = (lx: number, ly: number) => ({
+ x: cx + lx * cos - ly * sin,
+ y: cy + lx * sin + ly * cos,
+ });
+
+ const topLeft = toWorld(-radius, halfHeight);
+ const topRight = toWorld(radius, halfHeight);
+ const bottomLeft = toWorld(-radius, -halfHeight);
+ const bottomRight = toWorld(radius, -halfHeight);
+
+ Draw.line(topLeft, bottomLeft, color, DEBUG_LINE_THICKNESS);
+ Draw.line(topRight, bottomRight, color, DEBUG_LINE_THICKNESS);
+
+ for (let i = 0; i < CAPSULE_ARC_SEGMENTS; i++) {
+ const a0 = (i / CAPSULE_ARC_SEGMENTS) * Math.PI;
+ const a1 = ((i + 1) / CAPSULE_ARC_SEGMENTS) * Math.PI;
+ const p0 = toWorld(
+ -radius * Math.cos(a0),
+ halfHeight + radius * Math.sin(a0),
+ );
+ const p1 = toWorld(
+ -radius * Math.cos(a1),
+ halfHeight + radius * Math.sin(a1),
+ );
+ Draw.line(p0, p1, color, DEBUG_LINE_THICKNESS);
+ }
+
+ for (let i = 0; i < CAPSULE_ARC_SEGMENTS; i++) {
+ const a0 = Math.PI + (i / CAPSULE_ARC_SEGMENTS) * Math.PI;
+ const a1 = Math.PI + ((i + 1) / CAPSULE_ARC_SEGMENTS) * Math.PI;
+ const p0 = toWorld(
+ -radius * Math.cos(a0),
+ -halfHeight + radius * Math.sin(a0),
+ );
+ const p1 = toWorld(
+ -radius * Math.cos(a1),
+ -halfHeight + radius * Math.sin(a1),
+ );
+ Draw.line(p0, p1, color, DEBUG_LINE_THICKNESS);
+ }
+}
+
+function drawVelocityArrow(
+ x: number, y: number,
+ vx: number, vy: number,
+): void {
+ const endX = x + vx * VELOCITY_SCALE;
+ const endY = y + vy * VELOCITY_SCALE;
+ Draw.line({ x, y }, { x: endX, y: endY }, VELOCITY_COLOR, DEBUG_LINE_THICKNESS);
+
+ const len = Math.sqrt(vx * vx + vy * vy);
+ if (len < 1) return;
+
+ const ARROWHEAD_LENGTH = 6;
+ const ARROWHEAD_ANGLE = Math.PI / 6;
+ const dirX = vx / len;
+ const dirY = vy / len;
+
+ const leftX = endX - ARROWHEAD_LENGTH * (dirX * Math.cos(ARROWHEAD_ANGLE) - dirY * Math.sin(ARROWHEAD_ANGLE));
+ const leftY = endY - ARROWHEAD_LENGTH * (dirX * Math.sin(ARROWHEAD_ANGLE) + dirY * Math.cos(ARROWHEAD_ANGLE));
+ const rightX = endX - ARROWHEAD_LENGTH * (dirX * Math.cos(ARROWHEAD_ANGLE) + dirY * Math.sin(ARROWHEAD_ANGLE));
+ const rightY = endY - ARROWHEAD_LENGTH * (-dirX * Math.sin(ARROWHEAD_ANGLE) + dirY * Math.cos(ARROWHEAD_ANGLE));
+
+ Draw.line({ x: endX, y: endY }, { x: leftX, y: leftY }, VELOCITY_COLOR, DEBUG_LINE_THICKNESS);
+ Draw.line({ x: endX, y: endY }, { x: rightX, y: rightY }, VELOCITY_COLOR, DEBUG_LINE_THICKNESS);
+}
+
+export function drawPhysicsDebug(
+ app: App,
+ physicsApiRes: ResourceDef<VelocityProvider>,
+ physicsEventsRes: ResourceDef<PhysicsEventsData>,
+): void {
+ const config = app.getResource<PhysicsDebugDrawConfig>(PhysicsDebugDraw);
+ if (!config || !config.enabled) return;
+
+ const ppu = readPixelsPerUnit(app);
+ const entities = app.world.getEntitiesWithComponents([RigidBody, Transform]);
+
+ let physics: VelocityProvider | null = null;
+ if (config.showVelocity && app.hasResource(physicsApiRes)) {
+ physics = app.getResource<VelocityProvider>(physicsApiRes);
+ }
+
+ for (const entity of entities) {
+ const rb = app.world.get(entity, RigidBody) as RigidBodyData;
+ if (!rb.enabled) continue;
+
+ const wt = app.world.get(entity, Transform) as TransformData;
+ const wx = wt.worldPosition.x;
+ const wy = wt.worldPosition.y;
+ const angle = quatToAngleZ(wt.worldRotation);
+
+ if (config.showColliders) {
+ if (app.world.has(entity, BoxCollider)) {
+ const box = app.world.get(entity, BoxCollider) as BoxColliderData;
+ const baseColor = box.isSensor ? SENSOR_COLOR : bodyTypeColor(rb.bodyType);
+ const offsetX = box.offset.x * ppu;
+ const offsetY = box.offset.y * ppu;
+ const cosA = Math.cos(angle);
+ const sinA = Math.sin(angle);
+ const cx = wx + offsetX * cosA - offsetY * sinA;
+ const cy = wy + offsetX * sinA + offsetY * cosA;
+ drawRotatedBox(cx, cy, box.halfExtents.x * ppu, box.halfExtents.y * ppu, angle, baseColor);
+ }
+
+ if (app.world.has(entity, CircleCollider)) {
+ const circle = app.world.get(entity, CircleCollider) as CircleColliderData;
+ const baseColor = circle.isSensor ? SENSOR_COLOR : bodyTypeColor(rb.bodyType);
+ const offsetX = circle.offset.x * ppu;
+ const offsetY = circle.offset.y * ppu;
+ const cosA = Math.cos(angle);
+ const sinA = Math.sin(angle);
+ const cx = wx + offsetX * cosA - offsetY * sinA;
+ const cy = wy + offsetX * sinA + offsetY * cosA;
+ Draw.circleOutline(
+ { x: cx, y: cy },
+ circle.radius * ppu,
+ baseColor,
+ DEBUG_LINE_THICKNESS,
+ CIRCLE_SEGMENTS,
+ );
+ }
+
+ if (app.world.has(entity, CapsuleCollider)) {
+ const capsule = app.world.get(entity, CapsuleCollider) as CapsuleColliderData;
+ const baseColor = capsule.isSensor ? SENSOR_COLOR : bodyTypeColor(rb.bodyType);
+ const offsetX = capsule.offset.x * ppu;
+ const offsetY = capsule.offset.y * ppu;
+ const cosA = Math.cos(angle);
+ const sinA = Math.sin(angle);
+ const cx = wx + offsetX * cosA - offsetY * sinA;
+ const cy = wy + offsetX * sinA + offsetY * cosA;
+ drawCapsule(cx, cy, capsule.radius * ppu, capsule.halfHeight * ppu, angle, baseColor);
+ }
+ }
+
+ if (config.showVelocity && physics && rb.bodyType === BodyType.Dynamic) {
+ const vel = physics.getLinearVelocity(entity);
+ drawVelocityArrow(wx, wy, vel.x * ppu, vel.y * ppu);
+ }
+ }
+
+ if (config.showContacts && app.hasResource(physicsEventsRes)) {
+ const events = app.getResource<PhysicsEventsData>(physicsEventsRes);
+ for (const collision of events.collisionEnters) {
+ Draw.circle(
+ { x: collision.contactX, y: collision.contactY },
+ CONTACT_POINT_RADIUS,
+ CONTACT_COLOR,
+ true,
+ CIRCLE_SEGMENTS,
+ );
+ }
+ }
+}
+
+export function setupPhysicsDebugDraw(
+ app: App,
+ physicsApiRes: ResourceDef<VelocityProvider>,
+ physicsEventsRes: ResourceDef<PhysicsEventsData>,
+): void {
+ app.insertResource(PhysicsDebugDraw, {
+ enabled: false,
+ showColliders: true,
+ showVelocity: false,
+ showContacts: false,
+ });
+
+ registerDrawCallback('physics-debug-draw', () => {
+ drawPhysicsDebug(app, physicsApiRes, physicsEventsRes);
+ });
+}
diff --git a/sdk/src/physics/PhysicsPlugin.ts b/sdk/src/physics/PhysicsPlugin.ts
index 86e52e27d..ee6377d2f 100644
--- a/sdk/src/physics/PhysicsPlugin.ts
+++ b/sdk/src/physics/PhysicsPlugin.ts
@@ -15,6 +15,7 @@ import {
type PhysicsModuleFactory,
} from './PhysicsModuleLoader';
import { RigidBody, BoxCollider, CircleCollider, CapsuleCollider, BodyType, type RigidBodyData } from './PhysicsComponents';
+import { setupPhysicsDebugDraw, PhysicsDebugDraw, type PhysicsDebugDrawConfig } from './PhysicsDebugDraw';
// =============================================================================
// Physics Config
@@ -223,6 +224,7 @@ export class PhysicsPlugin implements Plugin {
app.physicsModule = module;
app.insertResource(PhysicsAPI, Physics._fromModule(module));
+ setupPhysicsDebugDraw(app, PhysicsAPI, PhysicsEvents);
app.setFixedTimestep(this.config_.fixedTimestep);
}
);
@@ -454,4 +456,19 @@ export class Physics {
applyAngularImpulse(entity: Entity, impulse: number): void {
this.module_._physics_applyAngularImpulse(entity, impulse);
}
+
+ static setDebugDraw(app: App, enabled: boolean): void {
+ const config = app.getResource<PhysicsDebugDrawConfig>(PhysicsDebugDraw);
+ if (config) {
+ config.enabled = enabled;
+ app.insertResource(PhysicsDebugDraw, config);
+ }
+ }
+
+ static setDebugDrawConfig(app: App, config: Partial<PhysicsDebugDrawConfig>): void {
+ const current = app.getResource<PhysicsDebugDrawConfig>(PhysicsDebugDraw);
+ if (current) {
+ app.insertResource(PhysicsDebugDraw, { ...current, ...config });
+ }
+ }
}
diff --git a/sdk/src/physics/index.ts b/sdk/src/physics/index.ts
index 4f961f674..dce096243 100644
--- a/sdk/src/physics/index.ts
+++ b/sdk/src/physics/index.ts
@@ -39,3 +39,10 @@ export {
type CircleColliderData,
type CapsuleColliderData,
} from './PhysicsComponents';
+
+export {
+ PhysicsDebugDraw,
+ setupPhysicsDebugDraw,
+ drawPhysicsDebug,
+ type PhysicsDebugDrawConfig,
+} from './PhysicsDebugDraw';
diff --git a/sdk/src/postprocess.ts b/sdk/src/postprocess.ts
index bb3facb81..bcee35121 100644
--- a/sdk/src/postprocess.ts
+++ b/sdk/src/postprocess.ts
@@ -1,648 +1,22 @@
-/**
- * @file postprocess.ts
- * @brief Per-camera post-processing effects API
- */
-
-import type { ESEngineModule } from './wasm';
-import type { Entity } from './types';
-import type { ShaderHandle, Vec4 } from './material';
-import { Material } from './material';
-import { handleWasmError } from './wasmError';
-
-// =============================================================================
-// Internal State
-// =============================================================================
-
-let module: ESEngineModule | null = null;
-let nextStackId = 1;
-
-const stacks: Map<number, PostProcessStack> = new Map();
-const cameraBindings: Map<Entity, PostProcessStack> = new Map();
-
-// =============================================================================
-// Initialization
-// =============================================================================
-
-export function initPostProcessAPI(wasmModule: ESEngineModule): void {
- module = wasmModule;
-}
-
-export function shutdownPostProcessAPI(): void {
- for (const stack of stacks.values()) {
- stack.destroy();
- }
- stacks.clear();
- cameraBindings.clear();
- if (module && PostProcess.isInitialized()) {
- PostProcess.shutdown();
- }
- module = null;
-}
-
-// =============================================================================
-// PostProcessStack
-// =============================================================================
-
-interface PassConfig {
- name: string;
- shader: ShaderHandle;
- enabled: boolean;
- floatUniforms: Map<string, number>;
- vec4Uniforms: Map<string, Vec4>;
-}
-
-export class PostProcessStack {
- readonly id: number;
- private passes_: PassConfig[] = [];
- private destroyed_ = false;
-
- constructor() {
- this.id = nextStackId++;
- stacks.set(this.id, this);
- }
-
- addPass(name: string, shader: ShaderHandle): this {
- this.passes_.push({
- name,
- shader,
- enabled: true,
- floatUniforms: new Map(),
- vec4Uniforms: new Map(),
- });
- return this;
- }
-
- removePass(name: string): this {
- const idx = this.passes_.findIndex(p => p.name === name);
- if (idx !== -1) {
- this.passes_.splice(idx, 1);
- }
- return this;
- }
-
- setEnabled(name: string, enabled: boolean): this {
- const pass = this.passes_.find(p => p.name === name);
- if (pass) {
- pass.enabled = enabled;
- }
- return this;
- }
-
- setUniform(passName: string, uniform: string, value: number): this {
- const pass = this.passes_.find(p => p.name === passName);
- if (pass) {
- pass.floatUniforms.set(uniform, value);
- }
- return this;
- }
-
- setUniformVec4(passName: string, uniform: string, value: Vec4): this {
- const pass = this.passes_.find(p => p.name === passName);
- if (pass) {
- pass.vec4Uniforms.set(uniform, { ...value });
- }
- return this;
- }
-
- setAllPassesEnabled(enabled: boolean): void {
- for (const pass of this.passes_) {
- pass.enabled = enabled;
- }
- }
-
- get passCount(): number {
- return this.passes_.length;
- }
-
- get enabledPassCount(): number {
- let count = 0;
- for (const pass of this.passes_) {
- if (pass.enabled) count++;
- }
- return count;
- }
-
- get passes(): readonly PassConfig[] {
- return this.passes_;
- }
-
- get isDestroyed(): boolean {
- return this.destroyed_;
- }
-
- destroy(): void {
- if (this.destroyed_) return;
- this.destroyed_ = true;
-
- for (const [camera, stack] of cameraBindings) {
- if (stack === this) {
- cameraBindings.delete(camera);
- }
- }
-
- stacks.delete(this.id);
- }
-}
-
-// =============================================================================
-// Internal helpers
-// =============================================================================
-
-function getModule(): ESEngineModule {
- if (!module) {
- throw new Error('PostProcess API not initialized. Call initPostProcessAPI() first.');
- }
- return module;
-}
-
-function syncStackToWasm(stack: PostProcessStack): void {
- const m = getModule();
-
- try {
- m.postprocess_clearPasses();
- } catch (e) {
- handleWasmError(e, 'PostProcess._applyForCamera:clearPasses');
- return;
- }
-
- for (const pass of stack.passes) {
- if (!pass.enabled) continue;
- try {
- m.postprocess_addPass(pass.name, pass.shader);
- } catch (e) {
- handleWasmError(e, `PostProcess._applyForCamera:addPass("${pass.name}")`);
- continue;
- }
-
- for (const [name, value] of pass.floatUniforms) {
- try {
- m.postprocess_setUniformFloat(pass.name, name, value);
- } catch (e) {
- handleWasmError(e, `PostProcess._applyForCamera:setUniform("${pass.name}", "${name}")`);
- }
- }
-
- for (const [name, value] of pass.vec4Uniforms) {
- try {
- m.postprocess_setUniformVec4(pass.name, name, value.x, value.y, value.z, value.w);
- } catch (e) {
- handleWasmError(e, `PostProcess._applyForCamera:setUniformVec4("${pass.name}", "${name}")`);
- }
- }
- }
-}
-
-// =============================================================================
-// PostProcess Static API
-// =============================================================================
-
-export const PostProcess = {
- // =========================================================================
- // Stack Management
- // =========================================================================
-
- createStack(): PostProcessStack {
- return new PostProcessStack();
- },
-
- // =========================================================================
- // Camera Binding
- // =========================================================================
-
- bind(camera: Entity, stack: PostProcessStack): void {
- if (stack.isDestroyed) {
- throw new Error('Cannot bind a destroyed PostProcessStack');
- }
- cameraBindings.set(camera, stack);
- },
-
- unbind(camera: Entity): void {
- cameraBindings.delete(camera);
- },
-
- getStack(camera: Entity): PostProcessStack | null {
- return cameraBindings.get(camera) ?? null;
- },
-
- // =========================================================================
- // Pipeline Lifecycle (delegates to C++ singleton)
- // =========================================================================
-
- init(width: number, height: number): boolean {
- try {
- return getModule().postprocess_init(width, height);
- } catch (e) {
- handleWasmError(e, `PostProcess.init(${width}x${height})`);
- return false;
- }
- },
-
- shutdown(): void {
- try {
- getModule().postprocess_shutdown();
- } catch (e) {
- handleWasmError(e, 'PostProcess.shutdown');
- }
- },
-
- resize(width: number, height: number): void {
- try {
- getModule().postprocess_resize(width, height);
- } catch (e) {
- handleWasmError(e, `PostProcess.resize(${width}x${height})`);
- }
- },
-
- isInitialized(): boolean {
- if (!module) return false;
- try {
- return module.postprocess_isInitialized();
- } catch (e) {
- handleWasmError(e, 'PostProcess.isInitialized');
- return false;
- }
- },
-
- setBypass(bypass: boolean): void {
- try {
- getModule().postprocess_setBypass(bypass);
- } catch (e) {
- handleWasmError(e, 'PostProcess.setBypass');
- }
- },
-
- setOutputViewport(x: number, y: number, w: number, h: number): void {
- try {
- getModule().postprocess_setOutputViewport(x, y, w, h);
- } catch (e) {
- handleWasmError(e, 'PostProcess.setOutputViewport');
- }
- },
-
- // =========================================================================
- // Per-Camera Render Integration (called by RenderPipeline)
- // =========================================================================
-
- _applyForCamera(camera: Entity): void {
- const stack = cameraBindings.get(camera);
- if (!stack || stack.isDestroyed || stack.enabledPassCount === 0) {
- PostProcess.setBypass(true);
- return;
- }
-
- if (!PostProcess.isInitialized()) {
- PostProcess.init(1, 1);
- }
-
- PostProcess.setBypass(false);
- syncStackToWasm(stack);
- },
-
- _resetAfterCamera(): void {
- try {
- getModule().postprocess_clearPasses();
- getModule().postprocess_setBypass(true);
- } catch (e) {
- handleWasmError(e, 'PostProcess._resetAfterCamera');
- }
- },
-
- _cleanupDestroyedCameras(isValid: (e: Entity) => boolean): void {
- for (const camera of cameraBindings.keys()) {
- if (!isValid(camera)) {
- cameraBindings.delete(camera);
- }
- }
- },
-
- // =========================================================================
- // Built-in Effects
- // =========================================================================
-
- createBlur(): ShaderHandle {
- const fragmentSrc = `#version 300 es
-precision highp float;
-
-in vec2 v_texCoord;
-uniform sampler2D u_texture;
-uniform vec2 u_resolution;
-uniform float u_intensity;
-out vec4 fragColor;
-
-void main() {
- vec2 texelSize = 1.0 / u_resolution;
- float offset = u_intensity;
-
- vec4 color = vec4(0.0);
- color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;
- color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;
- color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;
- color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;
- color += texture(u_texture, v_texCoord) * 0.25;
- color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;
- color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;
- color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;
- color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;
-
- fragColor = color;
-}
-`;
- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
- },
-
- createVignette(): ShaderHandle {
- const fragmentSrc = `#version 300 es
-precision highp float;
-
-in vec2 v_texCoord;
-uniform sampler2D u_texture;
-uniform float u_intensity;
-uniform float u_softness;
-out vec4 fragColor;
-
-void main() {
- vec4 color = texture(u_texture, v_texCoord);
- vec2 uv = v_texCoord * 2.0 - 1.0;
- float dist = length(uv);
- float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);
- fragColor = vec4(color.rgb * vignette, color.a);
-}
-`;
- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
- },
-
- createGrayscale(): ShaderHandle {
- const fragmentSrc = `#version 300 es
-precision highp float;
-
-in vec2 v_texCoord;
-uniform sampler2D u_texture;
-uniform float u_intensity;
-out vec4 fragColor;
-
-void main() {
- vec4 color = texture(u_texture, v_texCoord);
- float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));
- fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);
-}
-`;
- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
- },
-
- createBloom(): ShaderHandle {
- const fragmentSrc = `#version 300 es
-precision highp float;
-
-in vec2 v_texCoord;
-uniform sampler2D u_texture;
-uniform vec2 u_resolution;
-uniform float u_threshold;
-uniform float u_intensity;
-uniform float u_radius;
-out vec4 fragColor;
-
-void main() {
- vec4 color = texture(u_texture, v_texCoord);
- vec2 texelSize = 1.0 / u_resolution;
-
- vec3 bloom = vec3(0.0);
- float total = 0.0;
- for (float x = -3.0; x <= 3.0; x += 1.0) {
- for (float y = -3.0; y <= 3.0; y += 1.0) {
- vec2 offset = vec2(x, y) * texelSize * u_radius;
- vec4 s = texture(u_texture, v_texCoord + offset);
- float brightness = dot(s.rgb, vec3(0.2126, 0.7152, 0.0722));
- float w = max(brightness - u_threshold, 0.0);
- bloom += s.rgb * w;
- total += w;
- }
- }
- if (total > 0.0) bloom /= total;
-
- fragColor = vec4(color.rgb + bloom * u_intensity, color.a);
-}
-`;
- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
- },
-
- createChromaticAberration(): ShaderHandle {
- const fragmentSrc = `#version 300 es
-precision highp float;
-
-in vec2 v_texCoord;
-uniform sampler2D u_texture;
-uniform vec2 u_resolution;
-uniform float u_intensity;
-out vec4 fragColor;
-
-void main() {
- vec2 offset = u_intensity / u_resolution;
- float r = texture(u_texture, v_texCoord + offset).r;
- float g = texture(u_texture, v_texCoord).g;
- float b = texture(u_texture, v_texCoord - offset).b;
- float a = texture(u_texture, v_texCoord).a;
- fragColor = vec4(r, g, b, a);
-}
-`;
- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
- },
-};
-
-// =============================================================================
-// Shared Vertex Shader
-// =============================================================================
-
-const POSTPROCESS_VERTEX = `#version 300 es
-precision highp float;
-
-layout(location = 0) in vec2 a_position;
-layout(location = 1) in vec2 a_texCoord;
-
-out vec2 v_texCoord;
-
-void main() {
- v_texCoord = a_texCoord;
- gl_Position = vec4(a_position, 0.0, 1.0);
-}
-`;
-
-// =============================================================================
-// Built-in Effect Metadata
-// =============================================================================
-
-export interface EffectUniformDef {
- name: string;
- label: string;
- min: number;
- max: number;
- step: number;
- defaultValue: number;
-}
-
-export interface EffectDef {
- type: string;
- label: string;
- factory: () => ShaderHandle;
- uniforms: EffectUniformDef[];
-}
-
-const effectRegistry = new Map<string, EffectDef>();
-
-function registerEffect(def: EffectDef): void {
- effectRegistry.set(def.type, def);
-}
-
-registerEffect({
- type: 'blur',
- label: 'Blur',
- factory: () => PostProcess.createBlur(),
- uniforms: [
- { name: 'u_intensity', label: 'Intensity', min: 0, max: 20, step: 0.1, defaultValue: 2 },
- ],
-});
-
-registerEffect({
- type: 'bloom',
- label: 'Bloom',
- factory: () => PostProcess.createBloom(),
- uniforms: [
- { name: 'u_threshold', label: 'Threshold', min: 0, max: 2, step: 0.01, defaultValue: 0.8 },
- { name: 'u_intensity', label: 'Intensity', min: 0, max: 10, step: 0.1, defaultValue: 1.5 },
- { name: 'u_radius', label: 'Radius', min: 0, max: 20, step: 0.1, defaultValue: 4 },
- ],
-});
-
-registerEffect({
- type: 'vignette',
- label: 'Vignette',
- factory: () => PostProcess.createVignette(),
- uniforms: [
- { name: 'u_intensity', label: 'Intensity', min: 0, max: 3, step: 0.01, defaultValue: 0.8 },
- { name: 'u_softness', label: 'Softness', min: 0, max: 2, step: 0.01, defaultValue: 0.3 },
- ],
-});
-
-registerEffect({
- type: 'grayscale',
- label: 'Grayscale',
- factory: () => PostProcess.createGrayscale(),
- uniforms: [
- { name: 'u_intensity', label: 'Intensity', min: 0, max: 1, step: 0.01, defaultValue: 1 },
- ],
-});
-
-registerEffect({
- type: 'chromaticAberration',
- label: 'Chromatic Aberration',
- factory: () => PostProcess.createChromaticAberration(),
- uniforms: [
- { name: 'u_intensity', label: 'Intensity', min: 0, max: 20, step: 0.1, defaultValue: 3 },
- ],
-});
-
-export function getEffectDef(type: string): EffectDef | undefined {
- return effectRegistry.get(type);
-}
-
-export function getEffectTypes(): string[] {
- return Array.from(effectRegistry.keys());
-}
-
-export function getAllEffectDefs(): EffectDef[] {
- return Array.from(effectRegistry.values());
-}
-
-// =============================================================================
-// PostProcessVolume Data
-// =============================================================================
-
-export interface PostProcessEffectData {
- type: string;
- enabled: boolean;
- uniforms: Record<string, number>;
-}
-
-export interface PostProcessVolumeData {
- effects: PostProcessEffectData[];
-}
-
-const volumeStacks = new Map<Entity, PostProcessStack>();
-const volumeShaders = new Map<Entity, Map<string, ShaderHandle>>();
-
-export function syncPostProcessVolume(camera: Entity, data: PostProcessVolumeData): void {
- let stack = volumeStacks.get(camera);
- let shaders = volumeShaders.get(camera);
-
- const activeEffects = data.effects.filter(e => e.enabled);
- if (activeEffects.length === 0) {
- if (stack) {
- PostProcess.unbind(camera);
- stack.destroy();
- volumeStacks.delete(camera);
- }
- if (shaders) {
- for (const handle of shaders.values()) {
- Material.releaseShader(handle);
- }
- volumeShaders.delete(camera);
- }
- return;
- }
-
- if (!stack) {
- stack = PostProcess.createStack();
- volumeStacks.set(camera, stack);
- }
-
- if (!shaders) {
- shaders = new Map();
- volumeShaders.set(camera, shaders);
- }
-
- while (stack.passCount > 0) {
- const passes = stack.passes;
- stack.removePass(passes[passes.length - 1].name);
- }
-
- for (const effect of activeEffects) {
- const def = getEffectDef(effect.type);
- if (!def) continue;
-
- let shader = shaders.get(effect.type);
- if (shader === undefined) {
- shader = def.factory();
- shaders.set(effect.type, shader);
- }
-
- stack.addPass(effect.type, shader);
-
- for (const uDef of def.uniforms) {
- const value = effect.uniforms[uDef.name] ?? uDef.defaultValue;
- stack.setUniform(effect.type, uDef.name, value);
- }
- }
-
- PostProcess.bind(camera, stack);
-}
-
-export function cleanupPostProcessVolume(camera: Entity): void {
- const stack = volumeStacks.get(camera);
- if (stack) {
- PostProcess.unbind(camera);
- stack.destroy();
- volumeStacks.delete(camera);
- }
- const shaders = volumeShaders.get(camera);
- if (shaders) {
- for (const handle of shaders.values()) {
- Material.releaseShader(handle);
- }
- volumeShaders.delete(camera);
- }
-}
-
-export function cleanupAllPostProcessVolumes(): void {
- for (const camera of volumeStacks.keys()) {
- cleanupPostProcessVolume(camera);
- }
-}
+export {
+ PostProcess,
+ PostProcessStack,
+ initPostProcessAPI,
+ shutdownPostProcessAPI,
+ syncStackToWasm,
+ POSTPROCESS_VERTEX,
+ type PassConfig,
+ type EffectDef,
+ type EffectUniformDef,
+ registerEffect,
+ getEffectDef,
+ getEffectTypes,
+ getAllEffectDefs,
+ type PostProcessEffectData,
+ type PostProcessVolumeData,
+ syncPostProcessVolume,
+ cleanupPostProcessVolume,
+ cleanupAllPostProcessVolumes,
+ PostProcessPlugin,
+ postProcessPlugin,
+} from './postprocess/index';
diff --git a/sdk/src/postprocess/PostProcessAPI.ts b/sdk/src/postprocess/PostProcessAPI.ts
new file mode 100644
index 000000000..f6a1a62f1
--- /dev/null
+++ b/sdk/src/postprocess/PostProcessAPI.ts
@@ -0,0 +1,370 @@
+import type { ESEngineModule } from '../wasm';
+import type { Entity } from '../types';
+import type { ShaderHandle } from '../material';
+import { Material } from '../material';
+import { handleWasmError } from '../wasmError';
+import { PostProcessStack, getCameraBindings, getStacks } from './PostProcessStack';
+import { POSTPROCESS_VERTEX } from './shaders';
+
+let module: ESEngineModule | null = null;
+
+export function initPostProcessAPI(wasmModule: ESEngineModule): void {
+ module = wasmModule;
+}
+
+export function shutdownPostProcessAPI(): void {
+ for (const stack of getStacks().values()) {
+ stack.destroy();
+ }
+ getStacks().clear();
+ getCameraBindings().clear();
+ if (module && PostProcess.isInitialized()) {
+ PostProcess.shutdown();
+ }
+ module = null;
+}
+
+function getModule(): ESEngineModule {
+ if (!module) {
+ throw new Error('PostProcess API not initialized. Call initPostProcessAPI() first.');
+ }
+ return module;
+}
+
+export function syncStackToWasm(stack: PostProcessStack): void {
+ const m = getModule();
+
+ try {
+ m.postprocess_clearPasses();
+ } catch (e) {
+ handleWasmError(e, 'PostProcess._applyForCamera:clearPasses');
+ return;
+ }
+
+ for (const pass of stack.passes) {
+ if (!pass.enabled) continue;
+ try {
+ m.postprocess_addPass(pass.name, pass.shader);
+ } catch (e) {
+ handleWasmError(e, `PostProcess._applyForCamera:addPass("${pass.name}")`);
+ continue;
+ }
+
+ for (const [name, value] of pass.floatUniforms) {
+ try {
+ m.postprocess_setUniformFloat(pass.name, name, value);
+ } catch (e) {
+ handleWasmError(e, `PostProcess._applyForCamera:setUniform("${pass.name}", "${name}")`);
+ }
+ }
+
+ for (const [name, value] of pass.vec4Uniforms) {
+ try {
+ m.postprocess_setUniformVec4(pass.name, name, value.x, value.y, value.z, value.w);
+ } catch (e) {
+ handleWasmError(e, `PostProcess._applyForCamera:setUniformVec4("${pass.name}", "${name}")`);
+ }
+ }
+ }
+}
+
+export const PostProcess = {
+ createStack(): PostProcessStack {
+ return new PostProcessStack();
+ },
+
+ bind(camera: Entity, stack: PostProcessStack): void {
+ if (stack.isDestroyed) {
+ throw new Error('Cannot bind a destroyed PostProcessStack');
+ }
+ getCameraBindings().set(camera, stack);
+ },
+
+ unbind(camera: Entity): void {
+ getCameraBindings().delete(camera);
+ },
+
+ getStack(camera: Entity): PostProcessStack | null {
+ return getCameraBindings().get(camera) ?? null;
+ },
+
+ init(width: number, height: number): boolean {
+ try {
+ return getModule().postprocess_init(width, height);
+ } catch (e) {
+ handleWasmError(e, `PostProcess.init(${width}x${height})`);
+ return false;
+ }
+ },
+
+ shutdown(): void {
+ try {
+ getModule().postprocess_shutdown();
+ } catch (e) {
+ handleWasmError(e, 'PostProcess.shutdown');
+ }
+ },
+
+ resize(width: number, height: number): void {
+ try {
+ getModule().postprocess_resize(width, height);
+ } catch (e) {
+ handleWasmError(e, `PostProcess.resize(${width}x${height})`);
+ }
+ },
+
+ isInitialized(): boolean {
+ if (!module) return false;
+ try {
+ return module.postprocess_isInitialized();
+ } catch (e) {
+ handleWasmError(e, 'PostProcess.isInitialized');
+ return false;
+ }
+ },
+
+ setBypass(bypass: boolean): void {
+ try {
+ getModule().postprocess_setBypass(bypass);
+ } catch (e) {
+ handleWasmError(e, 'PostProcess.setBypass');
+ }
+ },
+
+ setOutputViewport(x: number, y: number, w: number, h: number): void {
+ try {
+ getModule().postprocess_setOutputViewport(x, y, w, h);
+ } catch (e) {
+ handleWasmError(e, 'PostProcess.setOutputViewport');
+ }
+ },
+
+ _applyForCamera(camera: Entity): void {
+ const stack = getCameraBindings().get(camera);
+ if (!stack || stack.isDestroyed || stack.enabledPassCount === 0) {
+ PostProcess.setBypass(true);
+ return;
+ }
+
+ if (!PostProcess.isInitialized()) {
+ PostProcess.init(1, 1);
+ }
+
+ PostProcess.setBypass(false);
+ syncStackToWasm(stack);
+ },
+
+ _resetAfterCamera(): void {
+ try {
+ getModule().postprocess_clearPasses();
+ getModule().postprocess_setBypass(true);
+ } catch (e) {
+ handleWasmError(e, 'PostProcess._resetAfterCamera');
+ }
+ },
+
+ _cleanupDestroyedCameras(isValid: (e: Entity) => boolean): void {
+ for (const camera of getCameraBindings().keys()) {
+ if (!isValid(camera)) {
+ getCameraBindings().delete(camera);
+ }
+ }
+ },
+
+ screenStack: null as PostProcessStack | null,
+
+ setScreenStack(stack: PostProcessStack | null): void {
+ PostProcess.screenStack = stack;
+ },
+
+ _beginScreenCapture(): void {
+ try {
+ getModule().postprocess_beginScreenCapture();
+ } catch (e) {
+ handleWasmError(e, 'PostProcess._beginScreenCapture');
+ }
+ },
+
+ _endScreenCapture(): void {
+ try {
+ getModule().postprocess_endScreenCapture();
+ } catch (e) {
+ handleWasmError(e, 'PostProcess._endScreenCapture');
+ }
+ },
+
+ _applyScreenStack(): void {
+ const stack = PostProcess.screenStack;
+ if (!stack || stack.isDestroyed || stack.enabledPassCount === 0) return;
+
+ const m = getModule();
+ try {
+ m.postprocess_clearScreenPasses();
+ } catch (e) {
+ handleWasmError(e, 'PostProcess._applyScreenStack:clearScreenPasses');
+ return;
+ }
+
+ for (const pass of stack.passes) {
+ if (!pass.enabled) continue;
+ try {
+ m.postprocess_addScreenPass(pass.name, pass.shader);
+ } catch (e) {
+ handleWasmError(e, `PostProcess._applyScreenStack:addScreenPass("${pass.name}")`);
+ continue;
+ }
+
+ for (const [name, value] of pass.floatUniforms) {
+ try {
+ m.postprocess_setScreenUniformFloat(pass.name, name, value);
+ } catch (e) {
+ handleWasmError(e, `PostProcess._applyScreenStack:setScreenUniform("${pass.name}", "${name}")`);
+ }
+ }
+
+ for (const [name, value] of pass.vec4Uniforms) {
+ try {
+ m.postprocess_setScreenUniformVec4(pass.name, name, value.x, value.y, value.z, value.w);
+ } catch (e) {
+ handleWasmError(e, `PostProcess._applyScreenStack:setScreenUniformVec4("${pass.name}", "${name}")`);
+ }
+ }
+ }
+ },
+
+ _executeScreenPasses(): void {
+ try {
+ getModule().postprocess_executeScreenPasses();
+ } catch (e) {
+ handleWasmError(e, 'PostProcess._executeScreenPasses');
+ }
+ },
+
+ createBlur(): ShaderHandle {
+ const fragmentSrc = `#version 300 es
+precision highp float;
+
+in vec2 v_texCoord;
+uniform sampler2D u_texture;
+uniform vec2 u_resolution;
+uniform float u_intensity;
+out vec4 fragColor;
+
+void main() {
+ vec2 texelSize = 1.0 / u_resolution;
+ float offset = u_intensity;
+
+ vec4 color = vec4(0.0);
+ color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;
+ color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;
+ color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;
+ color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;
+ color += texture(u_texture, v_texCoord) * 0.25;
+ color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;
+ color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;
+ color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;
+ color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;
+
+ fragColor = color;
+}
+`;
+ return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
+ },
+
+ createVignette(): ShaderHandle {
+ const fragmentSrc = `#version 300 es
+precision highp float;
+
+in vec2 v_texCoord;
+uniform sampler2D u_texture;
+uniform float u_intensity;
+uniform float u_softness;
+out vec4 fragColor;
+
+void main() {
+ vec4 color = texture(u_texture, v_texCoord);
+ vec2 uv = v_texCoord * 2.0 - 1.0;
+ float dist = length(uv);
+ float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);
+ fragColor = vec4(color.rgb * vignette, color.a);
+}
+`;
+ return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
+ },
+
+ createGrayscale(): ShaderHandle {
+ const fragmentSrc = `#version 300 es
+precision highp float;
+
+in vec2 v_texCoord;
+uniform sampler2D u_texture;
+uniform float u_intensity;
+out vec4 fragColor;
+
+void main() {
+ vec4 color = texture(u_texture, v_texCoord);
+ float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));
+ fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);
+}
+`;
+ return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
+ },
+
+ createBloom(): ShaderHandle {
+ const fragmentSrc = `#version 300 es
+precision highp float;
+
+in vec2 v_texCoord;
+uniform sampler2D u_texture;
+uniform vec2 u_resolution;
+uniform float u_threshold;
+uniform float u_intensity;
+uniform float u_radius;
+out vec4 fragColor;
+
+void main() {
+ vec4 color = texture(u_texture, v_texCoord);
+ vec2 texelSize = 1.0 / u_resolution;
+
+ vec3 bloom = vec3(0.0);
+ float total = 0.0;
+ for (float x = -3.0; x <= 3.0; x += 1.0) {
+ for (float y = -3.0; y <= 3.0; y += 1.0) {
+ vec2 offset = vec2(x, y) * texelSize * u_radius;
+ vec4 s = texture(u_texture, v_texCoord + offset);
+ float brightness = dot(s.rgb, vec3(0.2126, 0.7152, 0.0722));
+ float w = max(brightness - u_threshold, 0.0);
+ bloom += s.rgb * w;
+ total += w;
+ }
+ }
+ if (total > 0.0) bloom /= total;
+
+ fragColor = vec4(color.rgb + bloom * u_intensity, color.a);
+}
+`;
+ return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
+ },
+
+ createChromaticAberration(): ShaderHandle {
+ const fragmentSrc = `#version 300 es
+precision highp float;
+
+in vec2 v_texCoord;
+uniform sampler2D u_texture;
+uniform vec2 u_resolution;
+uniform float u_intensity;
+out vec4 fragColor;
+
+void main() {
+ vec2 offset = u_intensity / u_resolution;
+ float r = texture(u_texture, v_texCoord + offset).r;
+ float g = texture(u_texture, v_texCoord).g;
+ float b = texture(u_texture, v_texCoord - offset).b;
+ float a = texture(u_texture, v_texCoord).a;
+ fragColor = vec4(r, g, b, a);
+}
+`;
+ return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
+ },
+};
diff --git a/sdk/src/postprocess/PostProcessPlugin.ts b/sdk/src/postprocess/PostProcessPlugin.ts
new file mode 100644
index 000000000..4ca8d496d
--- /dev/null
+++ b/sdk/src/postprocess/PostProcessPlugin.ts
@@ -0,0 +1,22 @@
+import type { App, Plugin } from '../app';
+import { Schedule } from '../system';
+import { PostProcess } from './PostProcessAPI';
+import { cleanupAllPostProcessVolumes } from './sync';
+import { postProcessVolumeSystem, cleanupVolumeSystem, PostProcessVolumeConfigResource } from './volumeSystem';
+
+export class PostProcessPlugin implements Plugin {
+ name = 'PostProcessPlugin';
+
+ build(app: App): void {
+ app.insertResource(PostProcessVolumeConfigResource, { enabled: true });
+ app.addSystemToSchedule(Schedule.PostUpdate, postProcessVolumeSystem);
+ }
+
+ cleanup(): void {
+ cleanupAllPostProcessVolumes();
+ cleanupVolumeSystem();
+ PostProcess.setScreenStack(null);
+ }
+}
+
+export const postProcessPlugin = new PostProcessPlugin();
diff --git a/sdk/src/postprocess/PostProcessStack.ts b/sdk/src/postprocess/PostProcessStack.ts
new file mode 100644
index 000000000..e20e86c90
--- /dev/null
+++ b/sdk/src/postprocess/PostProcessStack.ts
@@ -0,0 +1,120 @@
+import type { Entity } from '../types';
+import type { ShaderHandle, Vec4 } from '../material';
+
+export interface PassConfig {
+ name: string;
+ shader: ShaderHandle;
+ enabled: boolean;
+ floatUniforms: Map<string, number>;
+ vec4Uniforms: Map<string, Vec4>;
+}
+
+let nextStackId = 1;
+
+const stacks: Map<number, PostProcessStack> = new Map();
+const cameraBindings: Map<Entity, PostProcessStack> = new Map();
+
+export function getStacks(): Map<number, PostProcessStack> {
+ return stacks;
+}
+
+export function getCameraBindings(): Map<Entity, PostProcessStack> {
+ return cameraBindings;
+}
+
+export function resetNextStackId(): void {
+ nextStackId = 1;
+}
+
+export class PostProcessStack {
+ readonly id: number;
+ private passes_: PassConfig[] = [];
+ private destroyed_ = false;
+
+ constructor() {
+ this.id = nextStackId++;
+ stacks.set(this.id, this);
+ }
+
+ addPass(name: string, shader: ShaderHandle): this {
+ this.passes_.push({
+ name,
+ shader,
+ enabled: true,
+ floatUniforms: new Map(),
+ vec4Uniforms: new Map(),
+ });
+ return this;
+ }
+
+ removePass(name: string): this {
+ const idx = this.passes_.findIndex(p => p.name === name);
+ if (idx !== -1) {
+ this.passes_.splice(idx, 1);
+ }
+ return this;
+ }
+
+ setEnabled(name: string, enabled: boolean): this {
+ const pass = this.passes_.find(p => p.name === name);
+ if (pass) {
+ pass.enabled = enabled;
+ }
+ return this;
+ }
+
+ setUniform(passName: string, uniform: string, value: number): this {
+ const pass = this.passes_.find(p => p.name === passName);
+ if (pass) {
+ pass.floatUniforms.set(uniform, value);
+ }
+ return this;
+ }
+
+ setUniformVec4(passName: string, uniform: string, value: Vec4): this {
+ const pass = this.passes_.find(p => p.name === passName);
+ if (pass) {
+ pass.vec4Uniforms.set(uniform, { ...value });
+ }
+ return this;
+ }
+
+ setAllPassesEnabled(enabled: boolean): void {
+ for (const pass of this.passes_) {
+ pass.enabled = enabled;
+ }
+ }
+
+ get passCount(): number {
+ return this.passes_.length;
+ }
+
+ get enabledPassCount(): number {
+ let count = 0;
+ for (const pass of this.passes_) {
+ if (pass.enabled) count++;
+ }
+ return count;
+ }
+
+ get passes(): readonly PassConfig[] {
+ return this.passes_;
+ }
+
+ get isDestroyed(): boolean {
+ return this.destroyed_;
+ }
+
+ destroy(): void {
+ if (this.destroyed_) return;
+ this.destroyed_ = true;
+
+ for (const [camera, stack] of cameraBindings) {
+ if (stack === this) {
+ cameraBindings.delete(camera);
+ }
+ }
+
+ stacks.delete(this.id);
+ }
+}
diff --git a/sdk/src/postprocess/effects.ts b/sdk/src/postprocess/effects.ts
new file mode 100644
index 000000000..83a7ed64c
--- /dev/null
+++ b/sdk/src/postprocess/effects.ts
@@ -0,0 +1,84 @@
+import type { ShaderHandle } from '../material';
+import { PostProcess } from './PostProcessAPI';
+
+export interface EffectUniformDef {
+ name: string;
+ label: string;
+ min: number;
+ max: number;
+ step: number;
+ defaultValue: number;
+}
+
+export interface EffectDef {
+ type: string;
+ label: string;
+ factory: () => ShaderHandle;
+ uniforms: EffectUniformDef[];
+}
+
+const effectRegistry = new Map<string, EffectDef>();
+
+export function registerEffect(def: EffectDef): void {
+ effectRegistry.set(def.type, def);
+}
+
+export function getEffectDef(type: string): EffectDef | undefined {
+ return effectRegistry.get(type);
+}
+
+export function getEffectTypes(): string[] {
+ return Array.from(effectRegistry.keys());
+}
+
+export function getAllEffectDefs(): EffectDef[] {
+ return Array.from(effectRegistry.values());
+}
+
+registerEffect({
+ type: 'blur',
+ label: 'Blur',
+ factory: () => PostProcess.createBlur(),
+ uniforms: [
+ { name: 'u_intensity', label: 'Intensity', min: 0, max: 20, step: 0.1, defaultValue: 2 },
+ ],
+});
+
+registerEffect({
+ type: 'bloom',
+ label: 'Bloom',
+ factory: () => PostProcess.createBloom(),
+ uniforms: [
+ { name: 'u_threshold', label: 'Threshold', min: 0, max: 2, step: 0.01, defaultValue: 0.8 },
+ { name: 'u_intensity', label: 'Intensity', min: 0, max: 10, step: 0.1, defaultValue: 1.5 },
+ { name: 'u_radius', label: 'Radius', min: 0, max: 20, step: 0.1, defaultValue: 4 },
+ ],
+});
+
+registerEffect({
+ type: 'vignette',
+ label: 'Vignette',
+ factory: () => PostProcess.createVignette(),
+ uniforms: [
+ { name: 'u_intensity', label: 'Intensity', min: 0, max: 3, step: 0.01, defaultValue: 0.8 },
+ { name: 'u_softness', label: 'Softness', min: 0, max: 2, step: 0.01, defaultValue: 0.3 },
+ ],
+});
+
+registerEffect({
+ type: 'grayscale',
+ label: 'Grayscale',
+ factory: () => PostProcess.createGrayscale(),
+ uniforms: [
+ { name: 'u_intensity', label: 'Intensity', min: 0, max: 1, step: 0.01, defaultValue: 1 },
+ ],
+});
+
+registerEffect({
+ type: 'chromaticAberration',
+ label: 'Chromatic Aberration',
+ factory: () => PostProcess.createChromaticAberration(),
+ uniforms: [
+ { name: 'u_intensity', label: 'Intensity', min: 0, max: 20, step: 0.1, defaultValue: 3 },
+ ],
+});
diff --git a/sdk/src/postprocess/index.ts b/sdk/src/postprocess/index.ts
new file mode 100644
index 000000000..4f462df30
--- /dev/null
+++ b/sdk/src/postprocess/index.ts
@@ -0,0 +1,35 @@
+export { PostProcessStack } from './PostProcessStack';
+export type { PassConfig } from './PostProcessStack';
+export { PostProcess, initPostProcessAPI, shutdownPostProcessAPI, syncStackToWasm } from './PostProcessAPI';
+export { POSTPROCESS_VERTEX } from './shaders';
+export {
+ type EffectDef,
+ type EffectUniformDef,
+ registerEffect,
+ getEffectDef,
+ getEffectTypes,
+ getAllEffectDefs,
+} from './effects';
+export {
+ type PostProcessEffectData,
+ type PostProcessVolumeData,
+ syncPostProcessVolume,
+ cleanupPostProcessVolume,
+ cleanupAllPostProcessVolumes,
+} from './sync';
+export {
+ signedDistanceBox,
+ signedDistanceSphere,
+ computeVolumeFactor,
+ blendVolumeEffects,
+ type ActiveVolume,
+ type VolumeTransform,
+ type BlendedEffect,
+} from './volumeBlending';
+export {
+ postProcessVolumeSystem,
+ cleanupVolumeSystem,
+ PostProcessVolumeConfigResource,
+ type PostProcessVolumeConfig,
+} from './volumeSystem';
+export { PostProcessPlugin, postProcessPlugin } from './PostProcessPlugin';
diff --git a/sdk/src/postprocess/shaders.ts b/sdk/src/postprocess/shaders.ts
new file mode 100644
index 000000000..6c91e9500
--- /dev/null
+++ b/sdk/src/postprocess/shaders.ts
@@ -0,0 +1,13 @@
+export const POSTPROCESS_VERTEX = `#version 300 es
+precision highp float;
+
+layout(location = 0) in vec2 a_position;
+layout(location = 1) in vec2 a_texCoord;
+
+out vec2 v_texCoord;
+
+void main() {
+ v_texCoord = a_texCoord;
+ gl_Position = vec4(a_position, 0.0, 1.0);
+}
+`;
diff --git a/sdk/src/postprocess/sync.ts b/sdk/src/postprocess/sync.ts
new file mode 100644
index 000000000..7b9a94daa
--- /dev/null
+++ b/sdk/src/postprocess/sync.ts
@@ -0,0 +1,103 @@
+import type { Entity } from '../types';
+import type { ShaderHandle } from '../material';
+import { Material } from '../material';
+import { PostProcessStack } from './PostProcessStack';
+import { PostProcess } from './PostProcessAPI';
+import { getEffectDef } from './effects';
+
+export interface PostProcessEffectData {
+ type: string;
+ enabled: boolean;
+ uniforms: Record<string, number>;
+}
+
+export interface PostProcessVolumeData {
+ effects: PostProcessEffectData[];
+ isGlobal: boolean;
+ shape: 'box' | 'sphere';
+ size: { x: number; y: number };
+ priority: number;
+ weight: number;
+ blendDistance: number;
+}
+
+const volumeStacks = new Map<Entity, PostProcessStack>();
+const volumeShaders = new Map<Entity, Map<string, ShaderHandle>>();
+
+export function syncPostProcessVolume(camera: Entity, data: PostProcessVolumeData): void {
+ let stack = volumeStacks.get(camera);
+ let shaders = volumeShaders.get(camera);
+
+ const activeEffects = data.effects.filter(e => e.enabled);
+ if (activeEffects.length === 0) {
+ if (stack) {
+ PostProcess.unbind(camera);
+ stack.destroy();
+ volumeStacks.delete(camera);
+ }
+ if (shaders) {
+ for (const handle of shaders.values()) {
+ Material.releaseShader(handle);
+ }
+ volumeShaders.delete(camera);
+ }
+ return;
+ }
+
+ if (!stack) {
+ stack = PostProcess.createStack();
+ volumeStacks.set(camera, stack);
+ }
+
+ if (!shaders) {
+ shaders = new Map();
+ volumeShaders.set(camera, shaders);
+ }
+
+ while (stack.passCount > 0) {
+ const passes = stack.passes;
+ stack.removePass(passes[passes.length - 1].name);
+ }
+
+ for (const effect of activeEffects) {
+ const def = getEffectDef(effect.type);
+ if (!def) continue;
+
+ let shader = shaders.get(effect.type);
+ if (shader === undefined) {
+ shader = def.factory();
+ shaders.set(effect.type, shader);
+ }
+
+ stack.addPass(effect.type, shader);
+
+ for (const uDef of def.uniforms) {
+ const value = effect.uniforms[uDef.name] ?? uDef.defaultValue;
+ stack.setUniform(effect.type, uDef.name, value);
+ }
+ }
+
+ PostProcess.bind(camera, stack);
+}
+
+export function cleanupPostProcessVolume(camera: Entity): void {
+ const stack = volumeStacks.get(camera);
+ if (stack) {
+ PostProcess.unbind(camera);
+ stack.destroy();
+ volumeStacks.delete(camera);
+ }
+ const shaders = volumeShaders.get(camera);
+ if (shaders) {
+ for (const handle of shaders.values()) {
+ Material.releaseShader(handle);
+ }
+ volumeShaders.delete(camera);
+ }
+}
+
+export function cleanupAllPostProcessVolumes(): void {
+ for (const camera of volumeStacks.keys()) {
+ cleanupPostProcessVolume(camera);
+ }
+}
diff --git a/sdk/src/postprocess/volumeBlending.ts b/sdk/src/postprocess/volumeBlending.ts
new file mode 100644
index 000000000..8c4f822c8
--- /dev/null
+++ b/sdk/src/postprocess/volumeBlending.ts
@@ -0,0 +1,101 @@
+import type { PostProcessVolumeData } from './sync';
+
+export interface VolumeTransform {
+ x: number;
+ y: number;
+}
+
+export interface ActiveVolume {
+ data: PostProcessVolumeData;
+ factor: number;
+}
+
+export interface BlendedEffect {
+ enabled: boolean;
+ uniforms: Map<string, number>;
+}
+
+export function signedDistanceBox(
+ px: number, py: number,
+ cx: number, cy: number,
+ halfW: number, halfH: number
+): number {
+ const dx = Math.abs(px - cx) - halfW;
+ const dy = Math.abs(py - cy) - halfH;
+ const outsideDist = Math.sqrt(Math.max(dx, 0) ** 2 + Math.max(dy, 0) ** 2);
+ const insideDist = Math.min(Math.max(dx, dy), 0);
+ return outsideDist + insideDist;
+}
+
+export function signedDistanceSphere(
+ px: number, py: number,
+ cx: number, cy: number,
+ radius: number
+): number {
+ const dx = px - cx;
+ const dy = py - cy;
+ return Math.sqrt(dx * dx + dy * dy) - radius;
+}
+
+export function computeVolumeFactor(
+ volume: PostProcessVolumeData,
+ transform: VolumeTransform,
+ px: number, py: number
+): number {
+ if (volume.isGlobal) {
+ return 1;
+ }
+
+ let dist: number;
+ if (volume.shape === 'sphere') {
+ dist = signedDistanceSphere(px, py, transform.x, transform.y, volume.size.x);
+ } else {
+ dist = signedDistanceBox(px, py, transform.x, transform.y, volume.size.x, volume.size.y);
+ }
+
+ if (dist <= 0) {
+ return volume.weight;
+ }
+
+ if (volume.blendDistance <= 0) {
+ return 0;
+ }
+
+ if (dist >= volume.blendDistance) {
+ return 0;
+ }
+
+ return (1 - dist / volume.blendDistance) * volume.weight;
+}
+
+export function blendVolumeEffects(
+ activeVolumes: ActiveVolume[]
+): Map<string, BlendedEffect> {
+ const result = new Map<string, BlendedEffect>();
+
+ const sorted = [...activeVolumes].sort((a, b) => a.data.priority - b.data.priority);
+
+ for (const { data, factor } of sorted) {
+ if (factor <= 0) continue;
+
+ for (const effect of data.effects) {
+ if (!effect.enabled) continue;
+
+ const existing = result.get(effect.type);
+ if (!existing) {
+ const uniforms = new Map<string, number>();
+ for (const [key, value] of Object.entries(effect.uniforms)) {
+ uniforms.set(key, value * factor);
+ }
+ result.set(effect.type, { enabled: true, uniforms });
+ } else {
+ for (const [key, value] of Object.entries(effect.uniforms)) {
+ const prev = existing.uniforms.get(key) ?? 0;
+ existing.uniforms.set(key, prev + (value - prev) * factor);
+ }
+ }
+ }
+ }
+
+ return result;
+}
diff --git a/sdk/src/postprocess/volumeSystem.ts b/sdk/src/postprocess/volumeSystem.ts
new file mode 100644
index 000000000..1c6d3776d
--- /dev/null
+++ b/sdk/src/postprocess/volumeSystem.ts
@@ -0,0 +1,117 @@
+import { defineSystem } from '../system';
+import { defineResource } from '../resource';
+import { Query } from '../query';
+import type { Entity } from '../types';
+import { PostProcessVolume, Transform, type PostProcessVolumeData, type TransformData } from '../component';
+import { PostProcess } from './PostProcessAPI';
+import { PostProcessStack } from './PostProcessStack';
+import { getEffectDef } from './effects';
+import { computeVolumeFactor, blendVolumeEffects, type ActiveVolume } from './volumeBlending';
+import type { ShaderHandle } from '../material';
+import { Material } from '../material';
+
+export interface PostProcessVolumeConfig {
+ enabled: boolean;
+}
+
+export const PostProcessVolumeConfigResource = defineResource<PostProcessVolumeConfig>(
+ { enabled: true },
+ 'PostProcessVolumeConfig'
+);
+
+const volumeStacks = new Map<Entity, PostProcessStack>();
+const volumeShaders = new Map<string, ShaderHandle>();
+
+function getOrCreateShader(effectType: string): ShaderHandle | null {
+ const existing = volumeShaders.get(effectType);
+ if (existing !== undefined) return existing;
+
+ const def = getEffectDef(effectType);
+ if (!def) return null;
+
+ const shader = def.factory();
+ volumeShaders.set(effectType, shader);
+ return shader;
+}
+
+function applyBlendedEffects(camera: Entity, effects: Map<string, { enabled: boolean; uniforms: Map<string, number> }>): void {
+ if (effects.size === 0) {
+ const existing = volumeStacks.get(camera);
+ if (existing) {
+ PostProcess.unbind(camera);
+ existing.destroy();
+ volumeStacks.delete(camera);
+ }
+ return;
+ }
+
+ let stack = volumeStacks.get(camera);
+ if (!stack) {
+ stack = PostProcess.createStack();
+ volumeStacks.set(camera, stack);
+ }
+
+ while (stack.passCount > 0) {
+ const passes = stack.passes;
+ stack.removePass(passes[passes.length - 1].name);
+ }
+
+ for (const [effectType, effectData] of effects) {
+ if (!effectData.enabled) continue;
+
+ const shader = getOrCreateShader(effectType);
+ if (shader === null) continue;
+
+ stack.addPass(effectType, shader);
+
+ for (const [uniformName, uniformValue] of effectData.uniforms) {
+ stack.setUniform(effectType, uniformName, uniformValue);
+ }
+ }
+
+ if (stack.enabledPassCount > 0) {
+ PostProcess.bind(camera, stack);
+ } else {
+ PostProcess.unbind(camera);
+ }
+}
+
+export const postProcessVolumeSystem = defineSystem(
+ [Query(PostProcessVolume, Transform)],
+ (query: Iterable<[Entity, PostProcessVolumeData, TransformData]>) => {
+ const volumes: { data: PostProcessVolumeData; tx: { x: number; y: number } }[] = [];
+ for (const [_entity, volumeData, transform] of query) {
+ volumes.push({ data: volumeData, tx: { x: transform.position.x, y: transform.position.y } });
+ }
+
+ if (volumes.length === 0) return;
+
+ const activeVolumes: ActiveVolume[] = [];
+ for (const { data, tx } of volumes) {
+ if (data.isGlobal) {
+ activeVolumes.push({ data, factor: 1 });
+ }
+ }
+
+ if (activeVolumes.length > 0) {
+ const blended = blendVolumeEffects(activeVolumes);
+ for (const [camera] of volumeStacks) {
+ applyBlendedEffects(camera, blended);
+ }
+ }
+ },
+ { name: 'PostProcessVolumeSystem' }
+);
+
+export function cleanupVolumeSystem(): void {
+ for (const [camera, stack] of volumeStacks) {
+ PostProcess.unbind(camera);
+ stack.destroy();
+ }
+ volumeStacks.clear();
+
+ for (const shader of volumeShaders.values()) {
+ Material.releaseShader(shader);
+ }
+ volumeShaders.clear();
+}
diff --git a/sdk/src/renderPipeline.ts b/sdk/src/renderPipeline.ts
index fea7597a4..52f93afc4 100644
--- a/sdk/src/renderPipeline.ts
+++ b/sdk/src/renderPipeline.ts
@@ -70,6 +70,23 @@ export class RenderPipeline {
this.activeScenes_ = scenes;
}
+ beginScreenCapture(): void {
+ if (PostProcess.screenStack && PostProcess.screenStack.enabledPassCount > 0) {
+ if (!PostProcess.isInitialized()) {
+ PostProcess.init(1, 1);
+ }
+ PostProcess._applyScreenStack();
+ PostProcess._beginScreenCapture();
+ }
+ }
+
+ endScreenCapture(): void {
+ if (PostProcess.screenStack && PostProcess.screenStack.enabledPassCount > 0) {
+ PostProcess._endScreenCapture();
+ PostProcess._executeScreenPasses();
+ }
+ }
+
render(params: RenderParams): void {
const { registry, viewProjection, width, height, elapsed } = params;
diff --git a/sdk/src/tilemap/collisionMerge.ts b/sdk/src/tilemap/collisionMerge.ts
new file mode 100644
index 000000000..79729f6c8
--- /dev/null
+++ b/sdk/src/tilemap/collisionMerge.ts
@@ -0,0 +1,59 @@
+export interface MergedRect {
+ col: number;
+ row: number;
+ width: number;
+ height: number;
+}
+
+export function mergeCollisionTiles(
+ tiles: ArrayLike<number>,
+ mapWidth: number,
+ mapHeight: number,
+ collisionTileIds: Set<number>,
+): MergedRect[] {
+ const visited = new Uint8Array(mapWidth * mapHeight);
+ const results: MergedRect[] = [];
+
+ const isCollision = (col: number, row: number): boolean => {
+ if (col >= mapWidth || row >= mapHeight) return false;
+ const idx = row * mapWidth + col;
+ if (visited[idx]) return false;
+ const tileId = tiles[idx] & 0x1FFF;
+ return tileId !== 0 && collisionTileIds.has(tileId);
+ };
+
+ for (let row = 0; row < mapHeight; row++) {
+ for (let col = 0; col < mapWidth; col++) {
+ if (!isCollision(col, row)) continue;
+
+ let w = 1;
+ while (isCollision(col + w, row)) {
+ w++;
+ }
+
+ let h = 1;
+ let canExpand = true;
+ while (canExpand) {
+ const nextRow = row + h;
+ if (nextRow >= mapHeight) break;
+ for (let dx = 0; dx < w; dx++) {
+ if (!isCollision(col + dx, nextRow)) {
+ canExpand = false;
+ break;
+ }
+ }
+ if (canExpand) h++;
+ }
+
+ for (let dy = 0; dy < h; dy++) {
+ for (let dx = 0; dx < w; dx++) {
+ visited[(row + dy) * mapWidth + (col + dx)] = 1;
+ }
+ }
+
+ results.push({ col, row, width: w, height: h });
+ }
+ }
+
+ return results;
+}
diff --git a/sdk/src/tilemap/components.ts b/sdk/src/tilemap/components.ts
index 93b4fef7e..3dcd0c416 100644
--- a/sdk/src/tilemap/components.ts
+++ b/sdk/src/tilemap/components.ts
@@ -13,6 +13,10 @@ export interface TilemapLayerData {
tilesetColumns: number;
layer: number;
tiles: number[];
+ tint: { r: number; g: number; b: number; a: number };
+ opacity: number;
+ visible: boolean;
+ parallaxFactor: { x: number; y: number };
}
export const Tilemap = defineComponent<TilemapData>('Tilemap', {
@@ -28,4 +32,8 @@ export const TilemapLayer = defineComponent<TilemapLayerData>('TilemapLayer', {
tilesetColumns: 1,
layer: 0,
tiles: [],
+ tint: { r: 1, g: 1, b: 1, a: 1 },
+ opacity: 1,
+ visible: true,
+ parallaxFactor: { x: 1, y: 1 },
});
diff --git a/sdk/src/tilemap/index.ts b/sdk/src/tilemap/index.ts
index c6303b576..fc2b3ff93 100644
--- a/sdk/src/tilemap/index.ts
+++ b/sdk/src/tilemap/index.ts
@@ -2,9 +2,13 @@ export { Tilemap, TilemapLayer, type TilemapData, type TilemapLayerData } from '
export { TilemapAPI, initTilemapAPI, shutdownTilemapAPI } from './tilemapAPI';
export { TilemapPlugin, tilemapPlugin } from './tilemapPlugin';
export {
- parseTiledMap, parseTmjJson, loadTiledMap, resolveRelativePath,
+ parseTiledMap, parseTmjJson, loadTiledMap, loadTiledCollisionObjects,
+ generateTileCollision, resolveRelativePath,
type TiledMapData, type TiledLayerData, type TiledTilesetData,
+ type TiledObjectData, type TiledObjectGroupData, type TiledObjectShape,
+ type TilemapLoadOptions,
} from './tiledLoader';
+export { mergeCollisionTiles, type MergedRect } from './collisionMerge';
export {
registerTextureDimensions, getTextureDimensions, clearTextureDimensionsCache,
registerTilemapSource, getTilemapSource, clearTilemapSourceCache,
diff --git a/sdk/src/tilemap/tiledLoader.ts b/sdk/src/tilemap/tiledLoader.ts
index c0d2ffd5a..415f1014a 100644
--- a/sdk/src/tilemap/tiledLoader.ts
+++ b/sdk/src/tilemap/tiledLoader.ts
@@ -3,6 +3,8 @@ import type { World } from '../world';
import type { Entity } from '../types';
import { TilemapLayer } from './components';
import { Transform } from '../component';
+import { RigidBody, BoxCollider, CircleCollider, BodyType } from '../physics/PhysicsComponents';
+import { mergeCollisionTiles } from './collisionMerge';
export interface TiledLayerData {
name: string;
@@ -10,6 +12,10 @@ export interface TiledLayerData {
height: number;
visible: boolean;
tiles: Uint16Array;
+ opacity: number;
+ tintColor: { r: number; g: number; b: number; a: number };
+ parallaxX: number;
+ parallaxY: number;
}
export interface TiledTilesetData {
@@ -21,6 +27,24 @@ export interface TiledTilesetData {
tileCount: number;
}
+export type TiledObjectShape = 'rect' | 'ellipse' | 'polygon' | 'point';
+
+export interface TiledObjectData {
+ shape: TiledObjectShape;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ rotation: number;
+ vertices: number[] | null;
+ properties: Map<string, unknown>;
+}
+
+export interface TiledObjectGroupData {
+ name: string;
+ objects: TiledObjectData[];
+}
+
export interface TiledMapData {
width: number;
height: number;
@@ -28,6 +52,8 @@ export interface TiledMapData {
tileHeight: number;
layers: TiledLayerData[];
tilesets: TiledTilesetData[];
+ objectGroups: TiledObjectGroupData[];
+ collisionTileIds: number[];
}
const TILED_FLIP_H = 0x80000000;
@@ -38,6 +64,34 @@ const ENGINE_FLIP_H = 0x2000;
const ENGINE_FLIP_V = 0x4000;
const ENGINE_FLIP_D = 0x8000;
+function parseTintColorU32(val: number): { r: number; g: number; b: number; a: number } {
+ if (val === 0) return { r: 1, g: 1, b: 1, a: 1 };
+ const a = ((val >>> 24) & 0xFF) / 255;
+ const r = ((val >>> 16) & 0xFF) / 255;
+ const g = ((val >>> 8) & 0xFF) / 255;
+ const b = (val & 0xFF) / 255;
+ return { r, g, b, a: a === 0 ? 1 : a };
+}
+
+function parseTintColor(hex: string | undefined): { r: number; g: number; b: number; a: number } {
+ if (!hex) return { r: 1, g: 1, b: 1, a: 1 };
+ const s = hex.startsWith('#') ? hex.slice(1) : hex;
+ if (s.length === 8) {
+ const a = parseInt(s.slice(0, 2), 16) / 255;
+ const r = parseInt(s.slice(2, 4), 16) / 255;
+ const g = parseInt(s.slice(4, 6), 16) / 255;
+ const b = parseInt(s.slice(6, 8), 16) / 255;
+ return { r, g, b, a };
+ }
+ if (s.length === 6) {
+ const r = parseInt(s.slice(0, 2), 16) / 255;
+ const g = parseInt(s.slice(2, 4), 16) / 255;
+ const b = parseInt(s.slice(4, 6), 16) / 255;
+ return { r, g, b, a: 1 };
+ }
+ return { r: 1, g: 1, b: 1, a: 1 };
+}
+
function convertGid(gid: number, firstGid: number): number {
if (gid === 0) return 0;
let flags = 0;
@@ -93,17 +147,102 @@ export function parseTmjJson(json: Record<string, unknown>): TiledMapData | null
}
}
+ const opacity = typeof layer.opacity === 'number' ? layer.opacity : 1;
+ const rawTint = layer.tintcolor as string | undefined;
+ const tintColor = parseTintColor(rawTint);
+ const parallaxX = typeof layer.parallaxx === 'number' ? layer.parallaxx : 1;
+ const parallaxY = typeof layer.parallaxy === 'number' ? layer.parallaxy : 1;
+
layers.push({
name: (layer.name as string) ?? '',
width: lw,
height: lh,
visible,
tiles,
+ opacity,
+ tintColor,
+ parallaxX,
+ parallaxY,
});
}
}
- return { width, height, tileWidth, tileHeight, layers, tilesets };
+ const objectGroups: TiledObjectGroupData[] = [];
+ const collisionTileIds: number[] = [];
+
+ if (rawLayers) {
+ for (const layer of rawLayers) {
+ if (layer.type !== 'objectgroup') continue;
+ const objs = layer.objects as Array<Record<string, unknown>> | undefined;
+ if (!objs) continue;
+ const parsed: TiledObjectData[] = [];
+ for (const obj of objs) {
+ const props = new Map<string, unknown>();
+ const rawProps = obj.properties as Array<Record<string, unknown>> | undefined;
+ if (rawProps) {
+ for (const p of rawProps) {
+ props.set(p.name as string, p.value);
+ }
+ }
+ let shape: TiledObjectShape = 'rect';
+ let vertices: number[] | null = null;
+ if (obj.ellipse) {
+ shape = 'ellipse';
+ } else if (obj.point) {
+ shape = 'point';
+ } else if (obj.polygon) {
+ shape = 'polygon';
+ const polyPts = obj.polygon as Array<{ x: number; y: number }>;
+ vertices = [];
+ for (const pt of polyPts) {
+ vertices.push(pt.x, pt.y);
+ }
+ } else if (obj.polyline) {
+ shape = 'polygon';
+ const linePts = obj.polyline as Array<{ x: number; y: number }>;
+ vertices = [];
+ for (const pt of linePts) {
+ vertices.push(pt.x, pt.y);
+ }
+ }
+ parsed.push({
+ shape,
+ x: (obj.x as number) ?? 0,
+ y: (obj.y as number) ?? 0,
+ width: (obj.width as number) ?? 0,
+ height: (obj.height as number) ?? 0,
+ rotation: (obj.rotation as number) ?? 0,
+ vertices,
+ properties: props,
+ });
+ }
+ objectGroups.push({
+ name: (layer.name as string) ?? '',
+ objects: parsed,
+ });
+ }
+ }
+
+ if (rawTilesets) {
+ for (const ts of rawTilesets) {
+ const firstGid = (ts.firstgid as number) ?? 1;
+ const rawTiles = ts.tiles as Array<Record<string, unknown>> | undefined;
+ if (rawTiles) {
+ for (const tile of rawTiles) {
+ const tileProps = tile.properties as Array<Record<string, unknown>> | undefined;
+ if (tileProps) {
+ for (const p of tileProps) {
+ if (p.name === 'collision' && p.value === true) {
+ collisionTileIds.push((tile.id as number) + firstGid);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return { width, height, tileWidth, tileHeight, layers, tilesets, objectGroups, collisionTileIds };
}
export function resolveRelativePath(basePath: string, relativePath: string): string {
@@ -170,6 +309,8 @@ export async function parseTiledMap(
tileHeight: api.tiled_getMapTileHeight(handle),
layers: [],
tilesets: [],
+ objectGroups: [],
+ collisionTileIds: [],
};
const layerCount = api.tiled_getLayerCount(handle);
@@ -190,6 +331,12 @@ export async function parseTiledMap(
height: h,
visible: api.tiled_getLayerVisible(handle, i),
tiles,
+ opacity: api.tiled_getLayerOpacity(handle, i),
+ tintColor: api.tiled_getLayerTintColor
+ ? parseTintColorU32(api.tiled_getLayerTintColor(handle, i))
+ : { r: 1, g: 1, b: 1, a: 1 },
+ parallaxX: api.tiled_getLayerParallaxX(handle, i),
+ parallaxY: api.tiled_getLayerParallaxY(handle, i),
});
}
@@ -213,10 +360,119 @@ export async function parseTiledMap(
}
}
+export interface TilemapLoadOptions {
+ generateObjectCollision?: boolean;
+ collisionTileIds?: number[];
+}
+
+const DEG_TO_RAD = Math.PI / 180;
+
+export function loadTiledCollisionObjects(
+ world: World,
+ mapData: TiledMapData,
+ mapOriginX: number,
+ mapOriginY: number,
+): Entity[] {
+ const entities: Entity[] = [];
+ const mapPixelH = mapData.height * mapData.tileHeight;
+
+ for (const group of mapData.objectGroups) {
+ for (const obj of group.objects) {
+ if (obj.shape === 'point') continue;
+
+ const entity = world.spawn();
+ const tiledX = obj.x;
+ const tiledY = obj.y;
+ const worldX = mapOriginX + tiledX + obj.width * 0.5;
+ const worldY = mapOriginY + (mapPixelH - tiledY) - obj.height * 0.5;
+ const angle = -obj.rotation * DEG_TO_RAD;
+
+ world.insert(entity, Transform, {
+ position: { x: worldX, y: worldY, z: 0 },
+ });
+ world.insert(entity, RigidBody, { bodyType: BodyType.Static });
+
+ if (obj.shape === 'ellipse') {
+ const radius = Math.max(obj.width, obj.height) * 0.5;
+ world.insert(entity, CircleCollider, { radius });
+ } else if (obj.shape === 'polygon' && obj.vertices) {
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
+ for (let i = 0; i < obj.vertices.length; i += 2) {
+ const vx = obj.vertices[i];
+ const vy = obj.vertices[i + 1];
+ if (vx < minX) minX = vx;
+ if (vx > maxX) maxX = vx;
+ if (vy < minY) minY = vy;
+ if (vy > maxY) maxY = vy;
+ }
+ const polyW = maxX - minX;
+ const polyH = maxY - minY;
+ const polyCX = (minX + maxX) * 0.5;
+ const polyCY = (minY + maxY) * 0.5;
+ world.insert(entity, BoxCollider, {
+ halfExtents: { x: polyW * 0.5, y: polyH * 0.5 },
+ offset: { x: polyCX, y: -polyCY },
+ });
+ } else {
+ world.insert(entity, BoxCollider, {
+ halfExtents: { x: obj.width * 0.5, y: obj.height * 0.5 },
+ });
+ }
+
+ if (angle !== 0) {
+ const half = angle * 0.5;
+ world.insert(entity, Transform, {
+ position: { x: worldX, y: worldY, z: 0 },
+ rotation: { w: Math.cos(half), x: 0, y: 0, z: Math.sin(half) },
+ });
+ }
+
+ entities.push(entity);
+ }
+ }
+ return entities;
+}
+
+export function generateTileCollision(
+ world: World,
+ layer: TiledLayerData,
+ mapData: TiledMapData,
+ collisionIds: Set<number>,
+ originX: number,
+ originY: number,
+): Entity[] {
+ const merged = mergeCollisionTiles(
+ layer.tiles, layer.width, layer.height, collisionIds,
+ );
+ const entities: Entity[] = [];
+ const tileW = mapData.tileWidth;
+ const tileH = mapData.tileHeight;
+ const mapPixelH = mapData.height * tileH;
+
+ for (const rect of merged) {
+ const mergedW = rect.width * tileW;
+ const mergedH = rect.height * tileH;
+ const worldX = originX + rect.col * tileW + mergedW * 0.5;
+ const worldY = originY + (mapPixelH - rect.row * tileH) - mergedH * 0.5;
+
+ const entity = world.spawn();
+ world.insert(entity, Transform, {
+ position: { x: worldX, y: worldY, z: 0 },
+ });
+ world.insert(entity, RigidBody, { bodyType: BodyType.Static });
+ world.insert(entity, BoxCollider, {
+ halfExtents: { x: mergedW * 0.5, y: mergedH * 0.5 },
+ });
+ entities.push(entity);
+ }
+ return entities;
+}
+
export function loadTiledMap(
world: World,
mapData: TiledMapData,
textureHandles: Map<string, number>,
+ options: TilemapLoadOptions = {},
): Entity[] {
const entities: Entity[] = [];
const firstTileset = mapData.tilesets[0];
@@ -242,11 +498,34 @@ export function loadTiledMap(
tilesetColumns: columns,
layer: layerIndex,
tiles: Array.from(layer.tiles),
+ tint: { ...layer.tintColor },
+ opacity: layer.opacity,
+ visible: layer.visible,
+ parallaxFactor: { x: layer.parallaxX, y: layer.parallaxY },
});
entities.push(entity);
layerIndex++;
}
+ const generateCollision = options.generateObjectCollision !== false;
+ if (generateCollision && mapData.objectGroups.length > 0) {
+ const collisionEntities = loadTiledCollisionObjects(world, mapData, 0, 0);
+ entities.push(...collisionEntities);
+ }
+
+ const tileCollisionIds = new Set<number>(
+ options.collisionTileIds ?? mapData.collisionTileIds,
+ );
+ if (tileCollisionIds.size > 0) {
+ for (const layer of mapData.layers) {
+ if (!layer.visible) continue;
+ const tileEntities = generateTileCollision(
+ world, layer, mapData, tileCollisionIds, 0, 0,
+ );
+ entities.push(...tileEntities);
+ }
+ }
+
return entities;
}
diff --git a/sdk/src/tilemap/tilemapAPI.ts b/sdk/src/tilemap/tilemapAPI.ts
index b6e45b128..607e7744f 100644
--- a/sdk/src/tilemap/tilemapAPI.ts
+++ b/sdk/src/tilemap/tilemapAPI.ts
@@ -16,7 +16,10 @@ interface TilemapModule {
uvTileWidth: number, uvTileHeight: number,
originX: number, originY: number,
camLeft: number, camBottom: number,
- camRight: number, camTop: number): void;
+ camRight: number, camTop: number,
+ tintR: number, tintG: number, tintB: number, tintA: number,
+ opacity: number,
+ parallaxX: number, parallaxY: number): void;
tiled_loadMap(dataPtr: number, dataSize: number): number;
tiled_freeMap(handle: number): void;
@@ -44,6 +47,11 @@ interface TilemapModule {
tiled_getTilesetColumns(handle: number, index: number): number;
tiled_getTilesetTileCount(handle: number, index: number): number;
+ tiled_getLayerOpacity(handle: number, index: number): number;
+ tiled_getLayerTintColor(handle: number, index: number): number;
+ tiled_getLayerParallaxX(handle: number, index: number): number;
+ tiled_getLayerParallaxY(handle: number, index: number): number;
+
HEAPU8: Uint8Array;
_malloc(size: number): number;
_free(ptr: number): void;
@@ -107,11 +115,15 @@ export const TilemapAPI = {
uvTileWidth: number, uvTileHeight: number,
originX: number, originY: number,
camLeft: number, camBottom: number,
- camRight: number, camTop: number): void {
+ camRight: number, camTop: number,
+ tintR: number, tintG: number, tintB: number, tintA: number,
+ opacity: number,
+ parallaxX: number, parallaxY: number): void {
module_?.tilemap_submitLayer(
entity, textureId, sortLayer, depth,
tilesetColumns, uvTileWidth, uvTileHeight,
- originX, originY, camLeft, camBottom, camRight, camTop
+ originX, originY, camLeft, camBottom, camRight, camTop,
+ tintR, tintG, tintB, tintA, opacity, parallaxX, parallaxY
);
},
};
diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.ts
index 61b52f74f..b74fbe909 100644
--- a/sdk/src/tilemap/tilemapPlugin.ts
+++ b/sdk/src/tilemap/tilemapPlugin.ts
@@ -3,7 +3,7 @@ import type { ESEngineModule } from '../wasm';
import { Transform, type TransformData } from '../component';
import { UICameraInfo, type UICameraData } from '../ui/UICameraInfo';
import { initTilemapAPI, shutdownTilemapAPI, TilemapAPI } from './tilemapAPI';
-import { Tilemap, TilemapLayer } from './components';
+import { Tilemap, TilemapLayer, type TilemapLayerData } from './components';
import { getTextureDimensions, clearTextureDimensionsCache, getTilemapSource } from './tilesetCache';
const MAX_CAMERA_EXTENT = 1e6;
@@ -35,19 +35,12 @@ export class TilemapPlugin implements Plugin {
[TilemapLayer, Transform],
);
for (const entity of layerEntities) {
- const layerData = world.tryGet(entity, TilemapLayer) as {
- width: number;
- height: number;
- tileWidth: number;
- tileHeight: number;
- texture: number;
- tilesetColumns: number;
- layer: number;
- tiles: number[];
- } | null;
+ const layerData = world.tryGet(entity, TilemapLayer) as TilemapLayerData | null;
const transform = world.tryGet(entity, Transform) as TransformData | null;
if (!layerData || !transform) continue;
+ if (!layerData.visible) continue;
+
const textureHandle = layerData.texture;
if (!textureHandle) continue;
@@ -71,6 +64,8 @@ export class TilemapPlugin implements Plugin {
const uvTileWidth = layerData.tileWidth / dims.width;
const uvTileHeight = layerData.tileHeight / dims.height;
+ const tint = layerData.tint;
+ const pf = layerData.parallaxFactor;
TilemapAPI.submitLayer(
entity,
@@ -83,6 +78,9 @@ export class TilemapPlugin implements Plugin {
transform.worldPosition.x,
transform.worldPosition.y,
camLeft, camBottom, camRight, camTop,
+ tint.r, tint.g, tint.b, tint.a,
+ layerData.opacity,
+ pf.x, pf.y,
);
}
@@ -140,6 +138,9 @@ export class TilemapPlugin implements Plugin {
transform.worldPosition.x,
transform.worldPosition.y,
camLeft, camBottom, camRight, camTop,
+ 1, 1, 1, 1,
+ 1,
+ 1, 1,
);
}
}
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index a101ded00..3a882d657 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -148,6 +148,13 @@ export interface ESEngineModule {
postprocess_clearPasses(): void;
postprocess_setOutputTarget(fboId: number): void;
postprocess_setOutputViewport(x: number, y: number, w: number, h: number): void;
+ postprocess_beginScreenCapture(): void;
+ postprocess_endScreenCapture(): void;
+ postprocess_executeScreenPasses(): void;
+ postprocess_addScreenPass(name: string, shaderHandle: number): number;
+ postprocess_clearScreenPasses(): void;
+ postprocess_setScreenUniformFloat(passName: string, uniform: string, value: number): void;
+ postprocess_setScreenUniformVec4(passName: string, uniform: string, x: number, y: number, z: number, w: number): void;
// Renderer API (RenderFrame)
renderer_init(width: number, height: number): void;
diff --git a/sdk/src/webAppFactory.ts b/sdk/src/webAppFactory.ts
index 6f23399c0..be2be0279 100644
--- a/sdk/src/webAppFactory.ts
+++ b/sdk/src/webAppFactory.ts
@@ -6,6 +6,7 @@ import { animationPlugin } from './animation';
import { audioPlugin } from './audio';
import { particlePlugin } from './particle';
import { tilemapPlugin } from './tilemap';
+import { postProcessPlugin } from './postprocess';
export { uiPlugins };
export { textPlugin, TextPlugin } from './ui/TextPlugin';
@@ -31,8 +32,9 @@ export { PhysicsPlugin, PhysicsEvents, Physics, loadPhysicsModule } from './phys
export { AnimationPlugin, animationPlugin } from './animation';
export { AudioPlugin, audioPlugin } from './audio';
export { ParticlePlugin, particlePlugin } from './particle';
+export { PostProcessPlugin, postProcessPlugin } from './postprocess';
-const defaultPlugins = [...uiPlugins, animationPlugin, audioPlugin, particlePlugin, tilemapPlugin];
+const defaultPlugins = [...uiPlugins, animationPlugin, audioPlugin, particlePlugin, tilemapPlugin, postProcessPlugin];
export function createWebApp(module: ESEngineModule, options?: WebAppOptions): App {
return _createWebApp(module, { plugins: defaultPlugins, ...options });
diff --git a/sdk/tests/particle.test.ts b/sdk/tests/particle.test.ts
index 12bdca4ca..c8998b5ba 100644
--- a/sdk/tests/particle.test.ts
+++ b/sdk/tests/particle.test.ts
@@ -19,9 +19,9 @@ describe('ParticleEmitter Component', () => {
expect(defaults.duration).toBe(5);
expect(defaults.looping).toBe(true);
expect(defaults.playOnStart).toBe(true);
- expect(defaults.maxParticles).toBe(100);
- expect(defaults.lifetimeMin).toBe(1);
- expect(defaults.lifetimeMax).toBe(2);
+ expect(defaults.maxParticles).toBe(1000);
+ expect(defaults.lifetimeMin).toBe(5);
+ expect(defaults.lifetimeMax).toBe(5);
expect(defaults.enabled).toBe(true);
});
@@ -29,10 +29,10 @@ describe('ParticleEmitter Component', () => {
const def = getComponent('ParticleEmitter');
const defaults = def!._default as Record<string, unknown>;
- expect(defaults.shape).toBe(0);
- expect(defaults.shapeRadius).toBe(1);
- expect(defaults.shapeSize).toEqual({ x: 1, y: 1 });
- expect(defaults.shapeAngle).toBe(45);
+ expect(defaults.shape).toBe(3);
+ expect(defaults.shapeRadius).toBe(100);
+ expect(defaults.shapeSize).toEqual({ x: 100, y: 100 });
+ expect(defaults.shapeAngle).toBe(25);
});
it('should have color defaults', () => {
diff --git a/sdk/tests/physicsDebugDraw.test.ts b/sdk/tests/physicsDebugDraw.test.ts
new file mode 100644
index 000000000..fd1cf0d70
--- /dev/null
+++ b/sdk/tests/physicsDebugDraw.test.ts
@@ -0,0 +1,406 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import {
+ PhysicsDebugDraw,
+ drawPhysicsDebug,
+ setupPhysicsDebugDraw,
+ type PhysicsDebugDrawConfig,
+} from '../src/physics/PhysicsDebugDraw';
+import { BodyType } from '../src/physics/PhysicsComponents';
+import { defineResource } from '../src/resource';
+import type { ResourceDef } from '../src/resource';
+import { clearDrawCallbacks, getDrawCallbacks } from '../src/customDraw';
+import { clearUserComponents } from '../src/component';
+
+vi.mock('../src/draw', () => ({
+ Draw: {
+ line: vi.fn(),
+ circle: vi.fn(),
+ circleOutline: vi.fn(),
+ rect: vi.fn(),
+ rectOutline: vi.fn(),
+ },
+}));
+
+import { Draw } from '../src/draw';
+
+interface MockEntity {
+ components: Map<string, any>;
+}
+
+function createMockApp(entities: MockEntity[] = [], resources: Map<symbol, any> = new Map()) {
+ const entityList = entities;
+ const resourceMap = resources;
+ return {
+ world: {
+ getEntitiesWithComponents: vi.fn((_comps: any[]) => {
+ return entityList.map((_, i) => i);
+ }),
+ get: vi.fn((entityIdx: number, comp: any) => {
+ const entity = entityList[entityIdx];
+ return entity?.components.get(comp._name) ?? null;
+ }),
+ has: vi.fn((entityIdx: number, comp: any) => {
+ const entity = entityList[entityIdx];
+ return entity?.components.has(comp._name) ?? false;
+ }),
+ },
+ getResource: vi.fn(<T,>(res: ResourceDef<T>): T | null => {
+ return resourceMap.get(res._id) ?? null;
+ }),
+ hasResource: vi.fn((res: ResourceDef<any>) => {
+ return resourceMap.has(res._id);
+ }),
+ insertResource: vi.fn((res: ResourceDef<any>, value: any) => {
+ resourceMap.set(res._id, value);
+ }),
+ } as any;
+}
+
+function mockEntity(comps: Record<string, any>): MockEntity {
+ const map = new Map<string, any>();
+ for (const [name, data] of Object.entries(comps)) {
+ map.set(name, data);
+ }
+ return { components: map };
+}
+
+const MockPhysicsAPI = defineResource<any>({}, 'MockPhysicsAPI');
+const MockPhysicsEvents = defineResource<any>({}, 'MockPhysicsEvents');
+
+describe('PhysicsDebugDraw resource', () => {
+ it('should define resource with correct defaults', () => {
+ expect(PhysicsDebugDraw._name).toBe('PhysicsDebugDraw');
+ expect(PhysicsDebugDraw._default).toEqual({
+ enabled: false,
+ showColliders: true,
+ showVelocity: false,
+ showContacts: false,
+ });
+ });
+});
+
+describe('drawPhysicsDebug', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ clearUserComponents();
+ });
+
+ it('should do nothing when config is not present', () => {
+ const app = createMockApp();
+ drawPhysicsDebug(app, MockPhysicsAPI, MockPhysicsEvents);
+ expect(Draw.line).not.toHaveBeenCalled();
+ expect(Draw.circleOutline).not.toHaveBeenCalled();
+ });
+
+ it('should do nothing when enabled=false', () => {
+ const resources = new Map<symbol, any>();
+ resources.set(PhysicsDebugDraw._id, {
+ enabled: false, showColliders: true, showVelocity: false, showContacts: false,
+ });
+ const app = createMockApp([], resources);
+
+ drawPhysicsDebug(app, MockPhysicsAPI, MockPhysicsEvents);
+ expect(Draw.line).not.toHaveBeenCalled();
+ });
+
+ it('should draw box collider when enabled', () => {
+ const resources = new Map<symbol, any>();
+ resources.set(PhysicsDebugDraw._id, {
+ enabled: true, showColliders: true, showVelocity: false, showContacts: false,
+ } as PhysicsDebugDrawConfig);
+
+ const entity = mockEntity({
+ RigidBody: { bodyType: BodyType.Static, enabled: true },
+ Transform: {
+ worldPosition: { x: 100, y: 200 },
+ worldRotation: { w: 1, x: 0, y: 0, z: 0 },
+ },
+ BoxCollider: {
+ halfExtents: { x: 0.5, y: 0.5 },
+ offset: { x: 0, y: 0 },
+ isSensor: false,
+ },
+ });
+
+ const app = createMockApp([entity], resources);
+ drawPhysicsDebug(app, MockPhysicsAPI, MockPhysicsEvents);
+
+ expect(Draw.line).toHaveBeenCalledTimes(4);
+ });
+
+ it('should draw circle collider when enabled', () => {
+ const resources = new Map<symbol, any>();
+ resources.set(PhysicsDebugDraw._id, {
+ enabled: true, showColliders: true, showVelocity: false, showContacts: false,
+ } as PhysicsDebugDrawConfig);
+
+ const entity = mockEntity({
+ RigidBody: { bodyType: BodyType.Dynamic, enabled: true },
+ Transform: {
+ worldPosition: { x: 50, y: 50 },
+ worldRotation: { w: 1, x: 0, y: 0, z: 0 },
+ },
+ CircleCollider: {
+ radius: 1.0,
+ offset: { x: 0, y: 0 },
+ isSensor: false,
+ },
+ });
+
+ const app = createMockApp([entity], resources);
+ drawPhysicsDebug(app, MockPhysicsAPI, MockPhysicsEvents);
+
+ expect(Draw.circleOutline).toHaveBeenCalledTimes(1);
+ });
+
+ it('should draw capsule collider when enabled', () => {
+ const resources = new Map<symbol, any>();
+ resources.set(PhysicsDebugDraw._id, {
+ enabled: true, showColliders: true, showVelocity: false, showContacts: false,
+ } as PhysicsDebugDrawConfig);
+
+ const entity = mockEntity({
+ RigidBody: { bodyType: BodyType.Dynamic, enabled: true },
+ Transform: {
+ worldPosition: { x: 0, y: 0 },
+ worldRotation: { w: 1, x: 0, y: 0, z: 0 },
+ },
+ CapsuleCollider: {
+ radius: 0.25,
+ halfHeight: 0.5,
+ offset: { x: 0, y: 0 },
+ isSensor: false,
+ },
+ });
+
+ const app = createMockApp([entity], resources);
+ drawPhysicsDebug(app, MockPhysicsAPI, MockPhysicsEvents);
+
+ // 2 side lines + 16 top arc segments + 16 bottom arc segments = 34
+ expect(Draw.line).toHaveBeenCalledTimes(34);
+ });
+
+ it('should skip disabled rigid bodies', () => {
+ const resources = new Map<symbol, any>();
+ resources.set(PhysicsDebugDraw._id, {
+ enabled: true, showColliders: true, showVelocity: false, showContacts: false,
+ } as PhysicsDebugDrawConfig);
+
+ const entity = mockEntity({
+ RigidBody: { bodyType: BodyType.Dynamic, enabled: false },
+ Transform: {
+ worldPosition: { x: 0, y: 0 },
+ worldRotation: { w: 1, x: 0, y: 0, z: 0 },
+ },
+ BoxCollider: {
+ halfExtents: { x: 0.5, y: 0.5 },
+ offset: { x: 0, y: 0 },
+ isSensor: false,
+ },
+ });
+
+ const app = createMockApp([entity], resources);
+ drawPhysicsDebug(app, MockPhysicsAPI, MockPhysicsEvents);
+
+ expect(Draw.line).not.toHaveBeenCalled();
+ });
+
+ it('should use sensor color for sensor colliders', () => {
+ const resources = new Map<symbol, any>();
+ resources.set(PhysicsDebugDraw._id, {
+ enabled: true, showColliders: true, showVelocity: false, showContacts: false,
+ } as PhysicsDebugDrawConfig);
+
+ const entity = mockEntity({
+ RigidBody: { bodyType: BodyType.Static, enabled: true },
+ Transform: {
+ worldPosition: { x: 0, y: 0 },
+ worldRotation: { w: 1, x: 0, y: 0, z: 0 },
+ },
+ BoxCollider: {
+ halfExtents: { x: 1, y: 1 },
+ offset: { x: 0, y: 0 },
+ isSensor: true,
+ },
+ });
+
+ const app = createMockApp([entity], resources);
+ drawPhysicsDebug(app, MockPhysicsAPI, MockPhysicsEvents);
+
+ const calls = (Draw.line as any).mock.calls;
+ expect(calls.length).toBe(4);
+ const sensorColor = { r: 1.0, g: 1.0, b: 0.2, a: 0.5 };
+ expect(calls[0][2]).toEqual(sensorColor);
+ });
+
+ it('should draw velocity arrows for dynamic bodies', () => {
+ const resources = new Map<symbol, any>();
+ resources.set(PhysicsDebugDraw._id, {
+ enabled: true, showColliders: false, showVelocity: true, showContacts: false,
+ } as PhysicsDebugDrawConfig);
+ resources.set(MockPhysicsAPI._id, {
+ getLinearVelocity: vi.fn().mockReturnValue({ x: 10, y: 5 }),
+ });
+
+ const entity = mockEntity({
+ RigidBody: { bodyType: BodyType.Dynamic, enabled: true },
+ Transform: {
+ worldPosition: { x: 100, y: 200 },
+ worldRotation: { w: 1, x: 0, y: 0, z: 0 },
+ },
+ });
+
+ const app = createMockApp([entity], resources);
+ drawPhysicsDebug(app, MockPhysicsAPI, MockPhysicsEvents);
+
+ // velocity line + 2 arrowhead lines = 3
+ expect(Draw.line).toHaveBeenCalledTimes(3);
+ });
+
+ it('should not draw velocity for static bodies', () => {
+ const resources = new Map<symbol, any>();
+ resources.set(PhysicsDebugDraw._id, {
+ enabled: true, showColliders: false, showVelocity: true, showContacts: false,
+ } as PhysicsDebugDrawConfig);
+ resources.set(MockPhysicsAPI._id, {
+ getLinearVelocity: vi.fn(),
+ });
+
+ const entity = mockEntity({
+ RigidBody: { bodyType: BodyType.Static, enabled: true },
+ Transform: {
+ worldPosition: { x: 0, y: 0 },
+ worldRotation: { w: 1, x: 0, y: 0, z: 0 },
+ },
+ });
+
+ const app = createMockApp([entity], resources);
+ drawPhysicsDebug(app, MockPhysicsAPI, MockPhysicsEvents);
+
+ expect(Draw.line).not.toHaveBeenCalled();
+ });
+
+ it('should draw contact points when showContacts is enabled', () => {
+ const resources = new Map<symbol, any>();
+ resources.set(PhysicsDebugDraw._id, {
+ enabled: true, showColliders: false, showVelocity: false, showContacts: true,
+ } as PhysicsDebugDrawConfig);
+ resources.set(MockPhysicsEvents._id, {
+ collisionEnters: [
+ { contactX: 10, contactY: 20 },
+ { contactX: 30, contactY: 40 },
+ ],
+ });
+
+ const app = createMockApp([], resources);
+ drawPhysicsDebug(app, MockPhysicsAPI, MockPhysicsEvents);
+
+ expect(Draw.circle).toHaveBeenCalledTimes(2);
+ });
+
+ it('should not draw contacts when PhysicsEvents resource is missing', () => {
+ const resources = new Map<symbol, any>();
+ resources.set(PhysicsDebugDraw._id, {
+ enabled: true, showColliders: false, showVelocity: false, showContacts: true,
+ } as PhysicsDebugDrawConfig);
+
+ const app = createMockApp([], resources);
+ drawPhysicsDebug(app, MockPhysicsAPI, MockPhysicsEvents);
+
+ expect(Draw.circle).not.toHaveBeenCalled();
+ });
+
+ it('should use correct body type colors', () => {
+ const resources = new Map<symbol, any>();
+ resources.set(PhysicsDebugDraw._id, {
+ enabled: true, showColliders: true, showVelocity: false, showContacts: false,
+ } as PhysicsDebugDrawConfig);
+
+ const staticEntity = mockEntity({
+ RigidBody: { bodyType: BodyType.Static, enabled: true },
+ Transform: { worldPosition: { x: 0, y: 0 }, worldRotation: { w: 1, x: 0, y: 0, z: 0 } },
+ CircleCollider: { radius: 1, offset: { x: 0, y: 0 }, isSensor: false },
+ });
+
+ const dynamicEntity = mockEntity({
+ RigidBody: { bodyType: BodyType.Dynamic, enabled: true },
+ Transform: { worldPosition: { x: 0, y: 0 }, worldRotation: { w: 1, x: 0, y: 0, z: 0 } },
+ CircleCollider: { radius: 1, offset: { x: 0, y: 0 }, isSensor: false },
+ });
+
+ const kinematicEntity = mockEntity({
+ RigidBody: { bodyType: BodyType.Kinematic, enabled: true },
+ Transform: { worldPosition: { x: 0, y: 0 }, worldRotation: { w: 1, x: 0, y: 0, z: 0 } },
+ CircleCollider: { radius: 1, offset: { x: 0, y: 0 }, isSensor: false },
+ });
+
+ const app = createMockApp([staticEntity, dynamicEntity, kinematicEntity], resources);
+ drawPhysicsDebug(app, MockPhysicsAPI, MockPhysicsEvents);
+
+ expect(Draw.circleOutline).toHaveBeenCalledTimes(3);
+ const calls = (Draw.circleOutline as any).mock.calls;
+
+ const staticColor = { r: 0.2, g: 0.4, b: 1.0, a: 0.7 };
+ const dynamicColor = { r: 0.2, g: 1.0, b: 0.2, a: 0.7 };
+ const kinematicColor = { r: 0.2, g: 1.0, b: 1.0, a: 0.7 };
+
+ expect(calls[0][2]).toEqual(staticColor);
+ expect(calls[1][2]).toEqual(dynamicColor);
+ expect(calls[2][2]).toEqual(kinematicColor);
+ });
+
+ it('should apply collider offset with rotation', () => {
+ const resources = new Map<symbol, any>();
+ resources.set(PhysicsDebugDraw._id, {
+ enabled: true, showColliders: true, showVelocity: false, showContacts: false,
+ } as PhysicsDebugDrawConfig);
+
+ // 90 degree rotation: quat z=sin(45°), w=cos(45°)
+ const angle = Math.PI / 2;
+ const qW = Math.cos(angle / 2);
+ const qZ = Math.sin(angle / 2);
+
+ const entity = mockEntity({
+ RigidBody: { bodyType: BodyType.Static, enabled: true },
+ Transform: {
+ worldPosition: { x: 100, y: 100 },
+ worldRotation: { w: qW, x: 0, y: 0, z: qZ },
+ },
+ CircleCollider: {
+ radius: 1,
+ offset: { x: 1, y: 0 },
+ isSensor: false,
+ },
+ });
+
+ const app = createMockApp([entity], resources);
+ drawPhysicsDebug(app, MockPhysicsAPI, MockPhysicsEvents);
+
+ expect(Draw.circleOutline).toHaveBeenCalledTimes(1);
+ const call = (Draw.circleOutline as any).mock.calls[0];
+ const center = call[0];
+ // offset (1, 0) rotated 90° → (0, 1) * ppu=100
+ expect(center.x).toBeCloseTo(100 + 0, 0);
+ expect(center.y).toBeCloseTo(100 + 100, 0);
+ });
+});
+
+describe('setupPhysicsDebugDraw', () => {
+ beforeEach(() => {
+ clearDrawCallbacks();
+ });
+
+ it('should insert default resource and register draw callback', () => {
+ const resources = new Map<symbol, any>();
+ const app = createMockApp([], resources);
+
+ setupPhysicsDebugDraw(app, MockPhysicsAPI, MockPhysicsEvents);
+
+ expect(app.insertResource).toHaveBeenCalledWith(PhysicsDebugDraw, {
+ enabled: false, showColliders: true, showVelocity: false, showContacts: false,
+ });
+
+ const callbacks = getDrawCallbacks();
+ expect(callbacks.has('physics-debug-draw')).toBe(true);
+ });
+});
diff --git a/sdk/tests/postProcessPlugin.test.ts b/sdk/tests/postProcessPlugin.test.ts
new file mode 100644
index 000000000..2029e5de3
--- /dev/null
+++ b/sdk/tests/postProcessPlugin.test.ts
@@ -0,0 +1,21 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('../src/material', () => ({
+ Material: {
+ createShader: vi.fn().mockReturnValue(42),
+ releaseShader: vi.fn(),
+ },
+}));
+
+import { postProcessPlugin } from '../src/postprocess/PostProcessPlugin';
+
+describe('PostProcessPlugin', () => {
+ it('has correct name', () => {
+ expect(postProcessPlugin.name).toBe('PostProcessPlugin');
+ });
+
+ it('implements Plugin interface with build and cleanup', () => {
+ expect(typeof postProcessPlugin.build).toBe('function');
+ expect(typeof postProcessPlugin.cleanup).toBe('function');
+ });
+});
diff --git a/sdk/tests/postprocess.test.ts b/sdk/tests/postprocess.test.ts
index 59be9201d..928285ca9 100644
--- a/sdk/tests/postprocess.test.ts
+++ b/sdk/tests/postprocess.test.ts
@@ -1,11 +1,12 @@
vi.mock('../src/material', () => ({
Material: {
createShader: vi.fn().mockReturnValue(42),
+ releaseShader: vi.fn(),
},
}));
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
-import { PostProcess, initPostProcessAPI, shutdownPostProcessAPI } from '../src/postprocess';
+import { PostProcess, PostProcessStack, initPostProcessAPI, shutdownPostProcessAPI } from '../src/postprocess';
import { Material } from '../src/material';
import type { ESEngineModule } from '../src/wasm';
@@ -19,17 +20,12 @@ function createPostProcessMockModule() {
postprocess_shutdown: vi.fn(),
postprocess_resize: vi.fn(),
postprocess_addPass: vi.fn().mockReturnValue(0),
- postprocess_removePass: vi.fn(),
- postprocess_setPassEnabled: vi.fn(),
- postprocess_isPassEnabled: vi.fn().mockReturnValue(true),
+ postprocess_clearPasses: vi.fn(),
postprocess_setUniformFloat: vi.fn(),
postprocess_setUniformVec4: vi.fn(),
- postprocess_begin: vi.fn(),
- postprocess_end: vi.fn(),
- postprocess_getPassCount: vi.fn().mockReturnValue(3),
postprocess_isInitialized: vi.fn().mockReturnValue(true),
postprocess_setBypass: vi.fn(),
- postprocess_isBypassed: vi.fn().mockReturnValue(false),
+ postprocess_setOutputViewport: vi.fn(),
};
return mock;
@@ -95,24 +91,19 @@ describe('PostProcess API', () => {
expect(PostProcess.isInitialized()).toBe(false);
});
- it('should return true for isBypassed after shutdown', () => {
- shutdownPostProcessAPI();
- expect(PostProcess.isBypassed()).toBe(true);
- });
-
it('should return false from init after shutdown', () => {
shutdownPostProcessAPI();
expect(PostProcess.init(800, 600)).toBe(false);
});
- it('should return -1 from addPass after shutdown', () => {
+ it('should not throw from shutdown after shutdown', () => {
shutdownPostProcessAPI();
- expect(PostProcess.addPass('test', 1)).toBe(-1);
+ expect(() => PostProcess.shutdown()).not.toThrow();
});
- it('should not throw from begin after shutdown', () => {
+ it('should not throw from setBypass after shutdown', () => {
shutdownPostProcessAPI();
- expect(() => PostProcess.begin()).not.toThrow();
+ expect(() => PostProcess.setBypass(true)).not.toThrow();
});
});
@@ -146,73 +137,111 @@ describe('PostProcess API', () => {
});
// =========================================================================
- // Pass management
+ // PostProcessStack
// =========================================================================
- describe('pass management', () => {
- it('should call postprocess_addPass and return index', () => {
- mock.postprocess_addPass.mockReturnValue(2);
- const index = PostProcess.addPass('bloom', 10);
- expect(mock.postprocess_addPass).toHaveBeenCalledWith('bloom', 10);
- expect(index).toBe(2);
+ describe('PostProcessStack', () => {
+ it('should create a stack with unique id', () => {
+ const stack1 = PostProcess.createStack();
+ const stack2 = PostProcess.createStack();
+ expect(stack1.id).not.toBe(stack2.id);
});
- it('should call postprocess_removePass', () => {
- PostProcess.removePass('bloom');
- expect(mock.postprocess_removePass).toHaveBeenCalledWith('bloom');
+ it('should add passes and track count', () => {
+ const stack = PostProcess.createStack();
+ stack.addPass('bloom', 1);
+ stack.addPass('blur', 2);
+ expect(stack.passCount).toBe(2);
});
- it('should call postprocess_setPassEnabled', () => {
- PostProcess.setEnabled('bloom', true);
- expect(mock.postprocess_setPassEnabled).toHaveBeenCalledWith('bloom', true);
-
- PostProcess.setEnabled('bloom', false);
- expect(mock.postprocess_setPassEnabled).toHaveBeenCalledWith('bloom', false);
+ it('should remove passes by name', () => {
+ const stack = PostProcess.createStack();
+ stack.addPass('bloom', 1);
+ stack.addPass('blur', 2);
+ stack.removePass('bloom');
+ expect(stack.passCount).toBe(1);
+ expect(stack.passes[0].name).toBe('blur');
});
- it('should call postprocess_isPassEnabled and return result', () => {
- mock.postprocess_isPassEnabled.mockReturnValue(true);
- expect(PostProcess.isEnabled('bloom')).toBe(true);
+ it('should set pass enabled state', () => {
+ const stack = PostProcess.createStack();
+ stack.addPass('bloom', 1);
+ stack.setEnabled('bloom', false);
+ expect(stack.enabledPassCount).toBe(0);
+ stack.setEnabled('bloom', true);
+ expect(stack.enabledPassCount).toBe(1);
+ });
- mock.postprocess_isPassEnabled.mockReturnValue(false);
- expect(PostProcess.isEnabled('bloom')).toBe(false);
+ it('should set float uniforms on passes', () => {
+ const stack = PostProcess.createStack();
+ stack.addPass('bloom', 1);
+ stack.setUniform('bloom', 'u_intensity', 0.5);
+ const pass = stack.passes[0];
+ expect(pass.floatUniforms.get('u_intensity')).toBe(0.5);
});
- it('should call postprocess_getPassCount and return count', () => {
- mock.postprocess_getPassCount.mockReturnValue(5);
- expect(PostProcess.getPassCount()).toBe(5);
+ it('should set vec4 uniforms on passes', () => {
+ const stack = PostProcess.createStack();
+ stack.addPass('bloom', 1);
+ stack.setUniformVec4('bloom', 'u_color', { x: 1, y: 0.5, z: 0.25, w: 1 });
+ const pass = stack.passes[0];
+ expect(pass.vec4Uniforms.get('u_color')).toEqual({ x: 1, y: 0.5, z: 0.25, w: 1 });
});
- });
- // =========================================================================
- // Uniform setting
- // =========================================================================
+ it('should enable/disable all passes', () => {
+ const stack = PostProcess.createStack();
+ stack.addPass('bloom', 1);
+ stack.addPass('blur', 2);
+ stack.setAllPassesEnabled(false);
+ expect(stack.enabledPassCount).toBe(0);
+ stack.setAllPassesEnabled(true);
+ expect(stack.enabledPassCount).toBe(2);
+ });
- describe('uniform setting', () => {
- it('should call postprocess_setUniformFloat', () => {
- PostProcess.setUniform('bloom', 'u_intensity', 0.5);
- expect(mock.postprocess_setUniformFloat).toHaveBeenCalledWith('bloom', 'u_intensity', 0.5);
+ it('should mark as destroyed after destroy()', () => {
+ const stack = PostProcess.createStack();
+ expect(stack.isDestroyed).toBe(false);
+ stack.destroy();
+ expect(stack.isDestroyed).toBe(true);
});
- it('should call postprocess_setUniformVec4 with destructured values', () => {
- PostProcess.setUniformVec4('bloom', 'u_color', { x: 1, y: 0.5, z: 0.25, w: 1 });
- expect(mock.postprocess_setUniformVec4).toHaveBeenCalledWith('bloom', 'u_color', 1, 0.5, 0.25, 1);
+ it('should support chaining on addPass/removePass/setEnabled/setUniform', () => {
+ const stack = PostProcess.createStack();
+ const result = stack
+ .addPass('bloom', 1)
+ .setEnabled('bloom', true)
+ .setUniform('bloom', 'u_intensity', 0.5)
+ .removePass('bloom');
+ expect(result).toBe(stack);
});
});
// =========================================================================
- // Render frame
+ // Camera binding
// =========================================================================
- describe('render frame', () => {
- it('should call postprocess_begin', () => {
- PostProcess.begin();
- expect(mock.postprocess_begin).toHaveBeenCalledOnce();
+ describe('camera binding', () => {
+ it('should bind a stack to a camera entity', () => {
+ const stack = PostProcess.createStack();
+ PostProcess.bind(1 as any, stack);
+ expect(PostProcess.getStack(1 as any)).toBe(stack);
+ });
+
+ it('should unbind a camera', () => {
+ const stack = PostProcess.createStack();
+ PostProcess.bind(1 as any, stack);
+ PostProcess.unbind(1 as any);
+ expect(PostProcess.getStack(1 as any)).toBeNull();
});
- it('should call postprocess_end', () => {
- PostProcess.end();
- expect(mock.postprocess_end).toHaveBeenCalledOnce();
+ it('should return null for unbound camera', () => {
+ expect(PostProcess.getStack(99 as any)).toBeNull();
+ });
+
+ it('should throw when binding a destroyed stack', () => {
+ const stack = PostProcess.createStack();
+ stack.destroy();
+ expect(() => PostProcess.bind(1 as any, stack)).toThrow('destroyed');
});
});
@@ -230,18 +259,62 @@ describe('PostProcess API', () => {
PostProcess.setBypass(false);
expect(mock.postprocess_setBypass).toHaveBeenCalledWith(false);
});
+ });
- it('should return WASM result from isBypassed', () => {
- mock.postprocess_isBypassed.mockReturnValue(true);
- expect(PostProcess.isBypassed()).toBe(true);
+ // =========================================================================
+ // _applyForCamera
+ // =========================================================================
- mock.postprocess_isBypassed.mockReturnValue(false);
- expect(PostProcess.isBypassed()).toBe(false);
+ describe('_applyForCamera', () => {
+ it('should set bypass=true when camera has no bound stack', () => {
+ PostProcess._applyForCamera(1 as any);
+ expect(mock.postprocess_setBypass).toHaveBeenCalledWith(true);
});
- it('should return true for isBypassed when module is null', () => {
- shutdownPostProcessAPI();
- expect(PostProcess.isBypassed()).toBe(true);
+ it('should sync enabled passes to WASM when stack is bound', () => {
+ const stack = PostProcess.createStack();
+ stack.addPass('bloom', 42);
+ stack.setUniform('bloom', 'u_intensity', 0.5);
+ PostProcess.bind(1 as any, stack);
+
+ PostProcess._applyForCamera(1 as any);
+
+ expect(mock.postprocess_setBypass).toHaveBeenCalledWith(false);
+ expect(mock.postprocess_clearPasses).toHaveBeenCalled();
+ expect(mock.postprocess_addPass).toHaveBeenCalledWith('bloom', 42);
+ expect(mock.postprocess_setUniformFloat).toHaveBeenCalledWith('bloom', 'u_intensity', 0.5);
+ });
+
+ it('should set bypass=true when all passes are disabled', () => {
+ const stack = PostProcess.createStack();
+ stack.addPass('bloom', 42);
+ stack.setEnabled('bloom', false);
+ PostProcess.bind(1 as any, stack);
+
+ PostProcess._applyForCamera(1 as any);
+ expect(mock.postprocess_setBypass).toHaveBeenCalledWith(true);
+ });
+
+ it('should sync vec4 uniforms to WASM', () => {
+ const stack = PostProcess.createStack();
+ stack.addPass('bloom', 42);
+ stack.setUniformVec4('bloom', 'u_color', { x: 1, y: 0.5, z: 0.25, w: 1 });
+ PostProcess.bind(1 as any, stack);
+
+ PostProcess._applyForCamera(1 as any);
+ expect(mock.postprocess_setUniformVec4).toHaveBeenCalledWith('bloom', 'u_color', 1, 0.5, 0.25, 1);
+ });
+ });
+
+ // =========================================================================
+ // _resetAfterCamera
+ // =========================================================================
+
+ describe('_resetAfterCamera', () => {
+ it('should clear passes and set bypass=true', () => {
+ PostProcess._resetAfterCamera();
+ expect(mock.postprocess_clearPasses).toHaveBeenCalled();
+ expect(mock.postprocess_setBypass).toHaveBeenCalledWith(true);
});
});
@@ -311,21 +384,6 @@ describe('PostProcess API', () => {
expect(PostProcess.init(800, 600)).toBe(false);
});
- it('should return -1 when postprocess_addPass throws', () => {
- mock.postprocess_addPass.mockImplementation(() => { throw new Error('WASM crash'); });
- expect(PostProcess.addPass('test', 1)).toBe(-1);
- });
-
- it('should return 0 when postprocess_getPassCount throws', () => {
- mock.postprocess_getPassCount.mockImplementation(() => { throw new Error('WASM crash'); });
- expect(PostProcess.getPassCount()).toBe(0);
- });
-
- it('should return false when postprocess_isPassEnabled throws', () => {
- mock.postprocess_isPassEnabled.mockImplementation(() => { throw new Error('WASM crash'); });
- expect(PostProcess.isEnabled('test')).toBe(false);
- });
-
it('should not throw when postprocess_shutdown throws', () => {
mock.postprocess_shutdown.mockImplementation(() => { throw new Error('WASM crash'); });
expect(() => PostProcess.shutdown()).not.toThrow();
@@ -336,26 +394,6 @@ describe('PostProcess API', () => {
expect(() => PostProcess.resize(800, 600)).not.toThrow();
});
- it('should not throw when postprocess_removePass throws', () => {
- mock.postprocess_removePass.mockImplementation(() => { throw new Error('WASM crash'); });
- expect(() => PostProcess.removePass('test')).not.toThrow();
- });
-
- it('should not throw when postprocess_begin throws', () => {
- mock.postprocess_begin.mockImplementation(() => { throw new Error('WASM crash'); });
- expect(() => PostProcess.begin()).not.toThrow();
- });
-
- it('should not throw when postprocess_end throws', () => {
- mock.postprocess_end.mockImplementation(() => { throw new Error('WASM crash'); });
- expect(() => PostProcess.end()).not.toThrow();
- });
-
- it('should return true when postprocess_isBypassed throws', () => {
- mock.postprocess_isBypassed.mockImplementation(() => { throw new Error('WASM crash'); });
- expect(PostProcess.isBypassed()).toBe(true);
- });
-
it('should return false when postprocess_isInitialized throws', () => {
mock.postprocess_isInitialized.mockImplementation(() => { throw new Error('WASM crash'); });
expect(PostProcess.isInitialized()).toBe(false);
diff --git a/sdk/tests/renderPipeline.test.ts b/sdk/tests/renderPipeline.test.ts
index 65623e457..0cc851425 100644
--- a/sdk/tests/renderPipeline.test.ts
+++ b/sdk/tests/renderPipeline.test.ts
@@ -21,11 +21,19 @@ vi.mock('../src/renderer', () => ({
vi.mock('../src/postprocess', () => ({
PostProcess: {
- isInitialized: vi.fn().mockReturnValue(false),
- getPassCount: vi.fn().mockReturnValue(0),
+ getStack: vi.fn().mockReturnValue(null),
resize: vi.fn(),
- begin: vi.fn(),
- end: vi.fn(),
+ setBypass: vi.fn(),
+ setOutputViewport: vi.fn(),
+ _applyForCamera: vi.fn(),
+ _resetAfterCamera: vi.fn(),
+ screenStack: null,
+ isInitialized: vi.fn().mockReturnValue(false),
+ init: vi.fn().mockReturnValue(true),
+ _applyScreenStack: vi.fn(),
+ _beginScreenCapture: vi.fn(),
+ _endScreenCapture: vi.fn(),
+ _executeScreenPasses: vi.fn(),
},
}));
@@ -173,29 +181,37 @@ describe('RenderPipeline', () => {
expect(Renderer.resize).toHaveBeenCalledWith(800, 768);
});
- it('calls PostProcess.resize when PostProcess is initialized with passes', () => {
- (PostProcess.isInitialized as ReturnType<typeof vi.fn>).mockReturnValue(true);
- (PostProcess.getPassCount as ReturnType<typeof vi.fn>).mockReturnValue(2);
-
+ it('does not call PostProcess.resize on render() (only renderCamera does)', () => {
pipeline.render({ registry, viewProjection, width: 800, height: 600, elapsed: 0 });
-
- expect(PostProcess.resize).toHaveBeenCalledWith(800, 600);
+ expect(PostProcess.resize).not.toHaveBeenCalled();
});
- it('does not call PostProcess.resize when PostProcess is not initialized', () => {
- (PostProcess.isInitialized as ReturnType<typeof vi.fn>).mockReturnValue(false);
- (PostProcess.getPassCount as ReturnType<typeof vi.fn>).mockReturnValue(2);
+ it('calls PostProcess.resize in renderCamera when camera has postprocess stack', () => {
+ (PostProcess.getStack as ReturnType<typeof vi.fn>).mockReturnValue({});
- pipeline.render({ registry, viewProjection, width: 800, height: 600, elapsed: 0 });
+ pipeline.renderCamera({
+ registry,
+ viewProjection,
+ viewportPixels: { x: 0, y: 0, w: 800, h: 600 },
+ clearFlags: 3,
+ elapsed: 0,
+ cameraEntity: 1 as any,
+ });
- expect(PostProcess.resize).not.toHaveBeenCalled();
+ expect(PostProcess.resize).toHaveBeenCalledWith(800, 600);
});
- it('does not call PostProcess.resize when pass count is 0', () => {
- (PostProcess.isInitialized as ReturnType<typeof vi.fn>).mockReturnValue(true);
- (PostProcess.getPassCount as ReturnType<typeof vi.fn>).mockReturnValue(0);
+ it('does not call PostProcess.resize in renderCamera when no postprocess stack', () => {
+ (PostProcess.getStack as ReturnType<typeof vi.fn>).mockReturnValue(null);
- pipeline.render({ registry, viewProjection, width: 800, height: 600, elapsed: 0 });
+ pipeline.renderCamera({
+ registry,
+ viewProjection,
+ viewportPixels: { x: 0, y: 0, w: 800, h: 600 },
+ clearFlags: 3,
+ elapsed: 0,
+ cameraEntity: 1 as any,
+ });
expect(PostProcess.resize).not.toHaveBeenCalled();
});
@@ -437,4 +453,47 @@ describe('RenderPipeline', () => {
expect(Draw.end).toHaveBeenCalled();
});
});
+
+ describe('screen capture', () => {
+ it('does not call screen capture when screenStack is null', () => {
+ (PostProcess as any).screenStack = null;
+ pipeline.beginScreenCapture();
+ pipeline.endScreenCapture();
+ expect(PostProcess._beginScreenCapture).not.toHaveBeenCalled();
+ expect(PostProcess._endScreenCapture).not.toHaveBeenCalled();
+ expect(PostProcess._executeScreenPasses).not.toHaveBeenCalled();
+ });
+
+ it('calls screen capture when screenStack has enabled passes', () => {
+ const mockStack = { enabledPassCount: 1, passes: [] };
+ (PostProcess as any).screenStack = mockStack;
+
+ pipeline.beginScreenCapture();
+ expect(PostProcess._applyScreenStack).toHaveBeenCalled();
+ expect(PostProcess._beginScreenCapture).toHaveBeenCalled();
+
+ pipeline.endScreenCapture();
+ expect(PostProcess._endScreenCapture).toHaveBeenCalled();
+ expect(PostProcess._executeScreenPasses).toHaveBeenCalled();
+ });
+
+ it('does not call screen capture when screenStack has 0 enabled passes', () => {
+ const mockStack = { enabledPassCount: 0, passes: [] };
+ (PostProcess as any).screenStack = mockStack;
+
+ pipeline.beginScreenCapture();
+ pipeline.endScreenCapture();
+ expect(PostProcess._beginScreenCapture).not.toHaveBeenCalled();
+ expect(PostProcess._executeScreenPasses).not.toHaveBeenCalled();
+ });
+
+ it('initializes postprocess if not yet initialized', () => {
+ const mockStack = { enabledPassCount: 1, passes: [] };
+ (PostProcess as any).screenStack = mockStack;
+ (PostProcess.isInitialized as ReturnType<typeof vi.fn>).mockReturnValue(false);
+
+ pipeline.beginScreenCapture();
+ expect(PostProcess.init).toHaveBeenCalledWith(1, 1);
+ });
+ });
});
diff --git a/sdk/tests/sceneManager.test.ts b/sdk/tests/sceneManager.test.ts
index d394db9b7..37f7a22bd 100644
--- a/sdk/tests/sceneManager.test.ts
+++ b/sdk/tests/sceneManager.test.ts
@@ -11,9 +11,6 @@ vi.mock('../src/customDraw', () => ({
vi.mock('../src/postprocess', () => ({
PostProcess: {
- addPass: vi.fn().mockReturnValue(0),
- removePass: vi.fn(),
- setEnabled: vi.fn(),
bind: vi.fn(),
unbind: vi.fn(),
},
@@ -284,13 +281,14 @@ describe('SceneManager', () => {
expect(unregisterDrawCallback).toHaveBeenCalledWith('myDraw');
});
- it('unload() removes postprocess passes', async () => {
+ it('unload() unbinds postprocess stacks', async () => {
manager.register({ name: 'level1', data: makeSceneData() });
const ctx = await manager.load('level1');
- ctx.addPostProcessPass('bloom', 42 as any);
+ const mockStack = { setAllPassesEnabled: vi.fn(), isDestroyed: false } as any;
+ ctx.bindPostProcess(1 as any, mockStack);
await manager.unload('level1');
- expect(PostProcess.removePass).toHaveBeenCalledWith('bloom');
+ expect(PostProcess.unbind).toHaveBeenCalledWith(1);
});
it('unload() releases material handles from loadedAssets', async () => {
@@ -460,25 +458,27 @@ describe('SceneManager', () => {
expect(manager.getSceneStatus('level1')).toBe('running');
});
- it('pause() disables postprocess passes', async () => {
+ it('pause() disables postprocess passes via stack', async () => {
manager.register({ name: 'level1', data: makeSceneData() });
const ctx = await manager.load('level1');
- ctx.addPostProcessPass('bloom', 1 as any);
+ const mockStack = { setAllPassesEnabled: vi.fn(), isDestroyed: false } as any;
+ ctx.bindPostProcess(1 as any, mockStack);
manager.pause('level1');
- expect(PostProcess.setEnabled).toHaveBeenCalledWith('bloom', false);
+ expect(mockStack.setAllPassesEnabled).toHaveBeenCalledWith(false);
});
- it('resume() re-enables postprocess passes', async () => {
+ it('resume() re-enables postprocess passes via stack', async () => {
manager.register({ name: 'level1', data: makeSceneData() });
const ctx = await manager.load('level1');
- ctx.addPostProcessPass('bloom', 1 as any);
+ const mockStack = { setAllPassesEnabled: vi.fn(), isDestroyed: false } as any;
+ ctx.bindPostProcess(1 as any, mockStack);
manager.pause('level1');
- vi.mocked(PostProcess.setEnabled).mockClear();
+ mockStack.setAllPassesEnabled.mockClear();
manager.resume('level1');
- expect(PostProcess.setEnabled).toHaveBeenCalledWith('bloom', true);
+ expect(mockStack.setAllPassesEnabled).toHaveBeenCalledWith(true);
});
});
@@ -562,14 +562,15 @@ describe('SceneManager', () => {
it('wake() disables postprocess passes on sleep and re-enables on wake', async () => {
manager.register({ name: 'level1', data: makeSceneData() });
const ctx = await manager.load('level1');
- ctx.addPostProcessPass('blur', 2 as any);
+ const mockStack = { setAllPassesEnabled: vi.fn(), isDestroyed: false } as any;
+ ctx.bindPostProcess(1 as any, mockStack);
manager.sleep('level1');
- expect(PostProcess.setEnabled).toHaveBeenCalledWith('blur', false);
+ expect(mockStack.setAllPassesEnabled).toHaveBeenCalledWith(false);
- vi.mocked(PostProcess.setEnabled).mockClear();
+ mockStack.setAllPassesEnabled.mockClear();
manager.wake('level1');
- expect(PostProcess.setEnabled).toHaveBeenCalledWith('blur', true);
+ expect(mockStack.setAllPassesEnabled).toHaveBeenCalledWith(true);
});
});
@@ -892,13 +893,14 @@ describe('SceneManager', () => {
expect(lastInsertCall[2].persistent).toBe(true);
});
- it('removePostProcessPass() removes pass from instance tracking', async () => {
+ it('unbindPostProcess() removes binding from instance tracking', async () => {
manager.register({ name: 'level1', data: makeSceneData() });
const ctx = await manager.load('level1');
- ctx.addPostProcessPass('bloom', 1 as any);
- ctx.removePostProcessPass('bloom');
- expect(PostProcess.removePass).toHaveBeenCalledWith('bloom');
+ const mockStack = { setAllPassesEnabled: vi.fn(), isDestroyed: false } as any;
+ ctx.bindPostProcess(1 as any, mockStack);
+ ctx.unbindPostProcess(1 as any);
+ expect(PostProcess.unbind).toHaveBeenCalledWith(1);
});
});
diff --git a/sdk/tests/tilemap.test.ts b/sdk/tests/tilemap.test.ts
index 5bd9f270e..ff3a91120 100644
--- a/sdk/tests/tilemap.test.ts
+++ b/sdk/tests/tilemap.test.ts
@@ -14,8 +14,9 @@ import {
getTilemapSource,
clearTilemapSourceCache,
} from '../src/tilemap/tilesetCache';
-import { loadTiledMap, parseTmjJson, resolveRelativePath } from '../src/tilemap/tiledLoader';
+import { loadTiledMap, parseTmjJson, resolveRelativePath, loadTiledCollisionObjects } from '../src/tilemap/tiledLoader';
import type { TiledMapData } from '../src/tilemap/tiledLoader';
+import { mergeCollisionTiles } from '../src/tilemap/collisionMerge';
import { clearUserComponents } from '../src/component';
import type { World } from '../src/world';
import type { Entity } from '../src/types';
@@ -69,6 +70,10 @@ describe('Tilemap Components', () => {
tilesetColumns: 1,
layer: 0,
tiles: [],
+ tint: { r: 1, g: 1, b: 1, a: 1 },
+ opacity: 1,
+ visible: true,
+ parallaxFactor: { x: 1, y: 1 },
});
});
@@ -327,6 +332,13 @@ describe('loadTiledMap', () => {
} as unknown as World;
}
+ const defaultLayerProps = {
+ opacity: 1,
+ tintColor: { r: 1, g: 1, b: 1, a: 1 },
+ parallaxX: 1,
+ parallaxY: 1,
+ };
+
const sampleMapData: TiledMapData = {
width: 20,
height: 15,
@@ -339,6 +351,7 @@ describe('loadTiledMap', () => {
height: 15,
visible: true,
tiles: new Uint16Array([1, 2, 3, 0, 0]),
+ ...defaultLayerProps,
},
{
name: 'Objects',
@@ -346,6 +359,7 @@ describe('loadTiledMap', () => {
height: 15,
visible: true,
tiles: new Uint16Array([0, 0, 5, 6, 7]),
+ ...defaultLayerProps,
},
],
tilesets: [
@@ -358,6 +372,8 @@ describe('loadTiledMap', () => {
tileCount: 64,
},
],
+ objectGroups: [],
+ collisionTileIds: [],
};
it('should create one entity per visible layer', () => {
@@ -450,4 +466,570 @@ describe('loadTiledMap', () => {
expect(entities).toHaveLength(0);
expect(world.spawn).not.toHaveBeenCalled();
});
+
+ it('should pass tint/opacity/parallax from layer data to TilemapLayer component', () => {
+ const world = createMockWorld();
+ const textureHandles = new Map([['terrain.png', 42]]);
+ const mapData: TiledMapData = {
+ ...sampleMapData,
+ layers: [{
+ name: 'Tinted',
+ width: 2, height: 1, visible: true,
+ tiles: new Uint16Array([1, 2]),
+ opacity: 0.5,
+ tintColor: { r: 1, g: 0.5, b: 0, a: 0.8 },
+ parallaxX: 0.5,
+ parallaxY: 0.75,
+ }],
+ };
+
+ loadTiledMap(world, mapData, textureHandles);
+
+ const insertCalls = (world.insert as any).mock.calls;
+ const layerInsert = insertCalls.find((c: any) => c[1]._name === 'TilemapLayer');
+ expect(layerInsert[2].opacity).toBe(0.5);
+ expect(layerInsert[2].tint).toEqual({ r: 1, g: 0.5, b: 0, a: 0.8 });
+ expect(layerInsert[2].parallaxFactor).toEqual({ x: 0.5, y: 0.75 });
+ expect(layerInsert[2].visible).toBe(true);
+ });
+});
+
+describe('parseTmjJson — Phase A: layer render properties', () => {
+ it('should parse layer opacity', () => {
+ const json = {
+ width: 2, height: 1, tilewidth: 16, tileheight: 16,
+ tilesets: [{ firstgid: 1, name: 'ts', image: 'ts.png', tilewidth: 16, tileheight: 16, columns: 4, tilecount: 16 }],
+ layers: [{ type: 'tilelayer', name: 'L', width: 2, height: 1, visible: true, opacity: 0.6, data: [1, 2] }],
+ };
+ const result = parseTmjJson(json);
+ expect(result!.layers[0].opacity).toBeCloseTo(0.6);
+ });
+
+ it('should default opacity to 1 when missing', () => {
+ const json = {
+ width: 2, height: 1, tilewidth: 16, tileheight: 16,
+ tilesets: [{ firstgid: 1, name: 'ts', image: 'ts.png', tilewidth: 16, tileheight: 16, columns: 4, tilecount: 16 }],
+ layers: [{ type: 'tilelayer', name: 'L', width: 2, height: 1, visible: true, data: [1, 2] }],
+ };
+ const result = parseTmjJson(json);
+ expect(result!.layers[0].opacity).toBe(1);
+ });
+
+ it('should parse layer tintcolor hex string', () => {
+ const json = {
+ width: 2, height: 1, tilewidth: 16, tileheight: 16,
+ tilesets: [],
+ layers: [{
+ type: 'tilelayer', name: 'L', width: 2, height: 1, visible: true,
+ data: [0, 0],
+ tintcolor: '#ff0000',
+ }],
+ };
+ const result = parseTmjJson(json);
+ expect(result!.layers[0].tintColor.r).toBeCloseTo(1);
+ expect(result!.layers[0].tintColor.g).toBeCloseTo(0);
+ expect(result!.layers[0].tintColor.b).toBeCloseTo(0);
+ });
+
+ it('should parse layer tintcolor with alpha (#AARRGGBB)', () => {
+ const json = {
+ width: 2, height: 1, tilewidth: 16, tileheight: 16,
+ tilesets: [],
+ layers: [{
+ type: 'tilelayer', name: 'L', width: 2, height: 1, visible: true,
+ data: [0, 0],
+ tintcolor: '#80ff8000',
+ }],
+ };
+ const result = parseTmjJson(json);
+ expect(result!.layers[0].tintColor.a).toBeCloseTo(128 / 255);
+ expect(result!.layers[0].tintColor.r).toBeCloseTo(1);
+ expect(result!.layers[0].tintColor.g).toBeCloseTo(128 / 255);
+ expect(result!.layers[0].tintColor.b).toBeCloseTo(0);
+ });
+
+ it('should default tintColor to white when missing', () => {
+ const json = {
+ width: 2, height: 1, tilewidth: 16, tileheight: 16,
+ tilesets: [],
+ layers: [{ type: 'tilelayer', name: 'L', width: 2, height: 1, visible: true, data: [0, 0] }],
+ };
+ const result = parseTmjJson(json);
+ expect(result!.layers[0].tintColor).toEqual({ r: 1, g: 1, b: 1, a: 1 });
+ });
+
+ it('should parse parallax factors', () => {
+ const json = {
+ width: 2, height: 1, tilewidth: 16, tileheight: 16,
+ tilesets: [],
+ layers: [{
+ type: 'tilelayer', name: 'L', width: 2, height: 1, visible: true,
+ data: [0, 0],
+ parallaxx: 0.5,
+ parallaxy: 0.8,
+ }],
+ };
+ const result = parseTmjJson(json);
+ expect(result!.layers[0].parallaxX).toBeCloseTo(0.5);
+ expect(result!.layers[0].parallaxY).toBeCloseTo(0.8);
+ });
+
+ it('should default parallax to 1 when missing', () => {
+ const json = {
+ width: 2, height: 1, tilewidth: 16, tileheight: 16,
+ tilesets: [],
+ layers: [{ type: 'tilelayer', name: 'L', width: 2, height: 1, visible: true, data: [0, 0] }],
+ };
+ const result = parseTmjJson(json);
+ expect(result!.layers[0].parallaxX).toBe(1);
+ expect(result!.layers[0].parallaxY).toBe(1);
+ });
+});
+
+describe('parseTmjJson — Phase B: objectgroup parsing', () => {
+ it('should parse objectgroup layers into objectGroups', () => {
+ const json = {
+ width: 10, height: 10, tilewidth: 32, tileheight: 32,
+ tilesets: [],
+ layers: [
+ {
+ type: 'objectgroup',
+ name: 'Collisions',
+ objects: [
+ { x: 64, y: 128, width: 32, height: 32, rotation: 0 },
+ { x: 0, y: 0, width: 64, height: 16, rotation: 45 },
+ ],
+ },
+ ],
+ };
+ const result = parseTmjJson(json);
+ expect(result!.objectGroups).toHaveLength(1);
+ expect(result!.objectGroups[0].name).toBe('Collisions');
+ expect(result!.objectGroups[0].objects).toHaveLength(2);
+ });
+
+ it('should detect ellipse objects', () => {
+ const json = {
+ width: 10, height: 10, tilewidth: 32, tileheight: 32,
+ tilesets: [],
+ layers: [{
+ type: 'objectgroup',
+ name: 'Shapes',
+ objects: [
+ { x: 10, y: 20, width: 30, height: 30, ellipse: true, rotation: 0 },
+ ],
+ }],
+ };
+ const result = parseTmjJson(json);
+ expect(result!.objectGroups[0].objects[0].shape).toBe('ellipse');
+ });
+
+ it('should detect point objects', () => {
+ const json = {
+ width: 10, height: 10, tilewidth: 32, tileheight: 32,
+ tilesets: [],
+ layers: [{
+ type: 'objectgroup',
+ name: 'Points',
+ objects: [
+ { x: 10, y: 20, width: 0, height: 0, point: true, rotation: 0 },
+ ],
+ }],
+ };
+ const result = parseTmjJson(json);
+ expect(result!.objectGroups[0].objects[0].shape).toBe('point');
+ });
+
+ it('should detect polygon objects with vertices', () => {
+ const json = {
+ width: 10, height: 10, tilewidth: 32, tileheight: 32,
+ tilesets: [],
+ layers: [{
+ type: 'objectgroup',
+ name: 'Polys',
+ objects: [{
+ x: 0, y: 0, width: 0, height: 0, rotation: 0,
+ polygon: [{ x: 0, y: 0 }, { x: 32, y: 0 }, { x: 16, y: 32 }],
+ }],
+ }],
+ };
+ const result = parseTmjJson(json);
+ const obj = result!.objectGroups[0].objects[0];
+ expect(obj.shape).toBe('polygon');
+ expect(obj.vertices).toEqual([0, 0, 32, 0, 16, 32]);
+ });
+
+ it('should extract object custom properties', () => {
+ const json = {
+ width: 10, height: 10, tilewidth: 32, tileheight: 32,
+ tilesets: [],
+ layers: [{
+ type: 'objectgroup',
+ name: 'G',
+ objects: [{
+ x: 0, y: 0, width: 32, height: 32, rotation: 0,
+ properties: [
+ { name: 'friction', value: 0.5 },
+ { name: 'oneway', value: true },
+ ],
+ }],
+ }],
+ };
+ const result = parseTmjJson(json);
+ const props = result!.objectGroups[0].objects[0].properties;
+ expect(props.get('friction')).toBe(0.5);
+ expect(props.get('oneway')).toBe(true);
+ });
+
+ it('should default rect shape for plain objects', () => {
+ const json = {
+ width: 10, height: 10, tilewidth: 32, tileheight: 32,
+ tilesets: [],
+ layers: [{
+ type: 'objectgroup',
+ name: 'G',
+ objects: [{ x: 0, y: 0, width: 32, height: 64, rotation: 0 }],
+ }],
+ };
+ const result = parseTmjJson(json);
+ expect(result!.objectGroups[0].objects[0].shape).toBe('rect');
+ });
+
+ it('should still parse tilelayers alongside objectgroups', () => {
+ const json = {
+ width: 10, height: 10, tilewidth: 32, tileheight: 32,
+ tilesets: [{ firstgid: 1, name: 'ts', image: 'ts.png', tilewidth: 32, tileheight: 32, columns: 4, tilecount: 16 }],
+ layers: [
+ { type: 'tilelayer', name: 'Ground', width: 10, height: 10, visible: true, data: [] },
+ { type: 'objectgroup', name: 'Collision', objects: [{ x: 0, y: 0, width: 32, height: 32, rotation: 0 }] },
+ ],
+ };
+ const result = parseTmjJson(json);
+ expect(result!.layers).toHaveLength(1);
+ expect(result!.objectGroups).toHaveLength(1);
+ });
+});
+
+describe('parseTmjJson — Phase C: collision tile IDs', () => {
+ it('should collect tile IDs with collision=true property', () => {
+ const json = {
+ width: 2, height: 1, tilewidth: 32, tileheight: 32,
+ tilesets: [{
+ firstgid: 1,
+ name: 'ts',
+ image: 'ts.png',
+ tilewidth: 32,
+ tileheight: 32,
+ columns: 4,
+ tilecount: 16,
+ tiles: [
+ { id: 0, properties: [{ name: 'collision', value: true }] },
+ { id: 3, properties: [{ name: 'collision', value: true }] },
+ { id: 5, properties: [{ name: 'decoration', value: true }] },
+ ],
+ }],
+ layers: [{ type: 'tilelayer', name: 'L', width: 2, height: 1, visible: true, data: [1, 4] }],
+ };
+ const result = parseTmjJson(json);
+ expect(result!.collisionTileIds).toContain(1);
+ expect(result!.collisionTileIds).toContain(4);
+ expect(result!.collisionTileIds).not.toContain(6);
+ expect(result!.collisionTileIds).toHaveLength(2);
+ });
+
+ it('should return empty collisionTileIds when no collision properties', () => {
+ const json = {
+ width: 2, height: 1, tilewidth: 32, tileheight: 32,
+ tilesets: [{ firstgid: 1, name: 'ts', image: 'ts.png', tilewidth: 32, tileheight: 32, columns: 4, tilecount: 16 }],
+ layers: [{ type: 'tilelayer', name: 'L', width: 2, height: 1, visible: true, data: [1, 2] }],
+ };
+ const result = parseTmjJson(json);
+ expect(result!.collisionTileIds).toEqual([]);
+ });
+});
+
+describe('mergeCollisionTiles', () => {
+ it('should merge a single collision tile', () => {
+ const tiles = new Uint16Array([1, 0, 0, 0]);
+ const result = mergeCollisionTiles(tiles, 2, 2, new Set([1]));
+ expect(result).toHaveLength(1);
+ expect(result[0]).toEqual({ col: 0, row: 0, width: 1, height: 1 });
+ });
+
+ it('should merge a horizontal row of tiles', () => {
+ const tiles = new Uint16Array([1, 1, 1, 0, 0, 0]);
+ const result = mergeCollisionTiles(tiles, 3, 2, new Set([1]));
+ expect(result).toHaveLength(1);
+ expect(result[0]).toEqual({ col: 0, row: 0, width: 3, height: 1 });
+ });
+
+ it('should merge a vertical column of tiles', () => {
+ const tiles = new Uint16Array([
+ 1, 0,
+ 1, 0,
+ 1, 0,
+ ]);
+ const result = mergeCollisionTiles(tiles, 2, 3, new Set([1]));
+ expect(result).toHaveLength(1);
+ expect(result[0]).toEqual({ col: 0, row: 0, width: 1, height: 3 });
+ });
+
+ it('should merge a rectangular block', () => {
+ const tiles = new Uint16Array([
+ 1, 1, 0,
+ 1, 1, 0,
+ 0, 0, 0,
+ ]);
+ const result = mergeCollisionTiles(tiles, 3, 3, new Set([1]));
+ expect(result).toHaveLength(1);
+ expect(result[0]).toEqual({ col: 0, row: 0, width: 2, height: 2 });
+ });
+
+ it('should produce separate rectangles for non-contiguous tiles', () => {
+ const tiles = new Uint16Array([
+ 1, 0, 1,
+ 0, 0, 0,
+ 1, 0, 1,
+ ]);
+ const result = mergeCollisionTiles(tiles, 3, 3, new Set([1]));
+ expect(result).toHaveLength(4);
+ });
+
+ it('should return empty for no collision tiles', () => {
+ const tiles = new Uint16Array([0, 0, 0, 0]);
+ const result = mergeCollisionTiles(tiles, 2, 2, new Set([1]));
+ expect(result).toHaveLength(0);
+ });
+
+ it('should handle multiple collision tile IDs', () => {
+ const tiles = new Uint16Array([1, 2, 3, 0]);
+ const result = mergeCollisionTiles(tiles, 2, 2, new Set([1, 2]));
+ expect(result).toHaveLength(1);
+ expect(result[0]).toEqual({ col: 0, row: 0, width: 2, height: 1 });
+ });
+
+ it('should handle L-shaped tiles as multiple rects', () => {
+ const tiles = new Uint16Array([
+ 1, 1,
+ 1, 0,
+ ]);
+ const result = mergeCollisionTiles(tiles, 2, 2, new Set([1]));
+ expect(result).toHaveLength(2);
+ const totalArea = result.reduce((sum, r) => sum + r.width * r.height, 0);
+ expect(totalArea).toBe(3);
+ });
+});
+
+describe('loadTiledCollisionObjects', () => {
+ function createMockWorld(): World {
+ let nextId = 1;
+ const components = new Map<number, Map<string, any>>();
+
+ return {
+ spawn: vi.fn(() => {
+ const id = nextId++ as Entity;
+ components.set(id, new Map());
+ return id;
+ }),
+ insert: vi.fn((entity: Entity, comp: any, data: any) => {
+ const map = components.get(entity)!;
+ map.set(comp._name, data);
+ }),
+ setParent: vi.fn(),
+ get: vi.fn((entity: Entity, comp: any) => {
+ return components.get(entity)?.get(comp._name) ?? null;
+ }),
+ } as unknown as World;
+ }
+
+ it('should create entities for rect objects', () => {
+ const world = createMockWorld();
+ const mapData: TiledMapData = {
+ width: 10, height: 10, tileWidth: 32, tileHeight: 32,
+ layers: [], tilesets: [], collisionTileIds: [],
+ objectGroups: [{
+ name: 'Collision',
+ objects: [
+ { shape: 'rect' as const, x: 64, y: 96, width: 32, height: 32, rotation: 0, vertices: null, properties: new Map() },
+ ],
+ }],
+ };
+
+ const entities = loadTiledCollisionObjects(world, mapData, 0, 0);
+ expect(entities).toHaveLength(1);
+ expect(world.spawn).toHaveBeenCalledTimes(1);
+
+ const insertCalls = (world.insert as any).mock.calls;
+ const rbInsert = insertCalls.find((c: any) => c[1]._name === 'RigidBody');
+ expect(rbInsert).toBeDefined();
+ expect(rbInsert[2].bodyType).toBe(0);
+
+ const boxInsert = insertCalls.find((c: any) => c[1]._name === 'BoxCollider');
+ expect(boxInsert).toBeDefined();
+ expect(boxInsert[2].halfExtents.x).toBe(16);
+ expect(boxInsert[2].halfExtents.y).toBe(16);
+ });
+
+ it('should create CircleCollider for ellipse objects', () => {
+ const world = createMockWorld();
+ const mapData: TiledMapData = {
+ width: 10, height: 10, tileWidth: 32, tileHeight: 32,
+ layers: [], tilesets: [], collisionTileIds: [],
+ objectGroups: [{
+ name: 'Collision',
+ objects: [
+ { shape: 'ellipse' as const, x: 0, y: 0, width: 64, height: 32, rotation: 0, vertices: null, properties: new Map() },
+ ],
+ }],
+ };
+
+ loadTiledCollisionObjects(world, mapData, 0, 0);
+
+ const insertCalls = (world.insert as any).mock.calls;
+ const circleInsert = insertCalls.find((c: any) => c[1]._name === 'CircleCollider');
+ expect(circleInsert).toBeDefined();
+ expect(circleInsert[2].radius).toBe(32);
+ });
+
+ it('should skip point objects', () => {
+ const world = createMockWorld();
+ const mapData: TiledMapData = {
+ width: 10, height: 10, tileWidth: 32, tileHeight: 32,
+ layers: [], tilesets: [], collisionTileIds: [],
+ objectGroups: [{
+ name: 'Points',
+ objects: [
+ { shape: 'point' as const, x: 10, y: 20, width: 0, height: 0, rotation: 0, vertices: null, properties: new Map() },
+ ],
+ }],
+ };
+
+ const entities = loadTiledCollisionObjects(world, mapData, 0, 0);
+ expect(entities).toHaveLength(0);
+ expect(world.spawn).not.toHaveBeenCalled();
+ });
+
+ it('should create BoxCollider for polygon using bounding box', () => {
+ const world = createMockWorld();
+ const mapData: TiledMapData = {
+ width: 10, height: 10, tileWidth: 32, tileHeight: 32,
+ layers: [], tilesets: [], collisionTileIds: [],
+ objectGroups: [{
+ name: 'Polys',
+ objects: [{
+ shape: 'polygon' as const,
+ x: 0, y: 0, width: 0, height: 0, rotation: 0,
+ vertices: [0, 0, 40, 0, 40, 20, 0, 20],
+ properties: new Map(),
+ }],
+ }],
+ };
+
+ loadTiledCollisionObjects(world, mapData, 0, 0);
+
+ const insertCalls = (world.insert as any).mock.calls;
+ const boxInsert = insertCalls.find((c: any) => c[1]._name === 'BoxCollider');
+ expect(boxInsert).toBeDefined();
+ expect(boxInsert[2].halfExtents.x).toBe(20);
+ expect(boxInsert[2].halfExtents.y).toBe(10);
+ });
+});
+
+describe('loadTiledMap — collision integration', () => {
+ function createMockWorld(): World {
+ let nextId = 1;
+ const components = new Map<number, Map<string, any>>();
+
+ return {
+ spawn: vi.fn(() => {
+ const id = nextId++ as Entity;
+ components.set(id, new Map());
+ return id;
+ }),
+ insert: vi.fn((entity: Entity, comp: any, data: any) => {
+ const map = components.get(entity)!;
+ map.set(comp._name, data);
+ }),
+ setParent: vi.fn(),
+ get: vi.fn((entity: Entity, comp: any) => {
+ return components.get(entity)?.get(comp._name) ?? null;
+ }),
+ } as unknown as World;
+ }
+
+ const defaultLayerProps = {
+ opacity: 1,
+ tintColor: { r: 1, g: 1, b: 1, a: 1 },
+ parallaxX: 1,
+ parallaxY: 1,
+ };
+
+ it('should generate collision entities from objectGroups', () => {
+ const world = createMockWorld();
+ const mapData: TiledMapData = {
+ width: 10, height: 10, tileWidth: 32, tileHeight: 32,
+ layers: [{
+ name: 'Ground', width: 10, height: 10, visible: true,
+ tiles: new Uint16Array(100),
+ ...defaultLayerProps,
+ }],
+ tilesets: [{ name: 'ts', image: 'ts.png', tileWidth: 32, tileHeight: 32, columns: 4, tileCount: 16 }],
+ objectGroups: [{
+ name: 'Collision',
+ objects: [
+ { shape: 'rect' as const, x: 0, y: 0, width: 32, height: 32, rotation: 0, vertices: null, properties: new Map() },
+ ],
+ }],
+ collisionTileIds: [],
+ };
+
+ const entities = loadTiledMap(world, mapData, new Map([['ts.png', 1]]));
+ expect(entities).toHaveLength(2);
+ });
+
+ it('should skip collision generation when generateObjectCollision=false', () => {
+ const world = createMockWorld();
+ const mapData: TiledMapData = {
+ width: 10, height: 10, tileWidth: 32, tileHeight: 32,
+ layers: [{
+ name: 'Ground', width: 10, height: 10, visible: true,
+ tiles: new Uint16Array(100),
+ ...defaultLayerProps,
+ }],
+ tilesets: [{ name: 'ts', image: 'ts.png', tileWidth: 32, tileHeight: 32, columns: 4, tileCount: 16 }],
+ objectGroups: [{
+ name: 'Collision',
+ objects: [
+ { shape: 'rect' as const, x: 0, y: 0, width: 32, height: 32, rotation: 0, vertices: null, properties: new Map() },
+ ],
+ }],
+ collisionTileIds: [],
+ };
+
+ const entities = loadTiledMap(world, mapData, new Map([['ts.png', 1]]), {
+ generateObjectCollision: false,
+ });
+ expect(entities).toHaveLength(1);
+ });
+
+ it('should generate tile collision from collisionTileIds option', () => {
+ const world = createMockWorld();
+ const tiles = new Uint16Array([1, 1, 0, 0]);
+ const mapData: TiledMapData = {
+ width: 2, height: 2, tileWidth: 32, tileHeight: 32,
+ layers: [{
+ name: 'Ground', width: 2, height: 2, visible: true,
+ tiles,
+ ...defaultLayerProps,
+ }],
+ tilesets: [{ name: 'ts', image: 'ts.png', tileWidth: 32, tileHeight: 32, columns: 4, tileCount: 16 }],
+ objectGroups: [],
+ collisionTileIds: [],
+ };
+
+ const entities = loadTiledMap(world, mapData, new Map([['ts.png', 1]]), {
+ collisionTileIds: [1],
+ });
+ expect(entities.length).toBeGreaterThan(1);
+ });
});
diff --git a/sdk/tests/volumeBlending.test.ts b/sdk/tests/volumeBlending.test.ts
new file mode 100644
index 000000000..8a63539ca
--- /dev/null
+++ b/sdk/tests/volumeBlending.test.ts
@@ -0,0 +1,336 @@
+import { describe, it, expect } from 'vitest';
+import {
+ signedDistanceBox,
+ signedDistanceSphere,
+ computeVolumeFactor,
+ blendVolumeEffects,
+} from '../src/postprocess/volumeBlending';
+
+describe('volumeBlending', () => {
+ describe('signedDistanceBox', () => {
+ it('returns negative distance when point is inside box', () => {
+ const dist = signedDistanceBox(0, 0, 0, 0, 5, 5);
+ expect(dist).toBeLessThan(0);
+ });
+
+ it('returns 0 when point is on box edge', () => {
+ const dist = signedDistanceBox(5, 0, 0, 0, 5, 5);
+ expect(dist).toBeCloseTo(0, 5);
+ });
+
+ it('returns positive distance when point is outside box', () => {
+ const dist = signedDistanceBox(8, 0, 0, 0, 5, 5);
+ expect(dist).toBeCloseTo(3, 5);
+ });
+
+ it('handles offset center', () => {
+ const dist = signedDistanceBox(15, 10, 10, 10, 5, 5);
+ expect(dist).toBeCloseTo(0, 5);
+ });
+
+ it('handles point at corner outside', () => {
+ const dist = signedDistanceBox(8, 8, 0, 0, 5, 5);
+ expect(dist).toBeCloseTo(Math.sqrt(9 + 9), 5);
+ });
+ });
+
+ describe('signedDistanceSphere', () => {
+ it('returns negative distance when point is inside sphere', () => {
+ const dist = signedDistanceSphere(1, 0, 0, 0, 5);
+ expect(dist).toBeCloseTo(-4, 5);
+ });
+
+ it('returns 0 when point is on sphere edge', () => {
+ const dist = signedDistanceSphere(5, 0, 0, 0, 5);
+ expect(dist).toBeCloseTo(0, 5);
+ });
+
+ it('returns positive distance when point is outside sphere', () => {
+ const dist = signedDistanceSphere(8, 0, 0, 0, 5);
+ expect(dist).toBeCloseTo(3, 5);
+ });
+
+ it('handles offset center', () => {
+ const dist = signedDistanceSphere(15, 10, 10, 10, 5);
+ expect(dist).toBeCloseTo(0, 5);
+ });
+ });
+
+ describe('computeVolumeFactor', () => {
+ const baseTransform = { x: 0, y: 0 };
+
+ it('returns 1 for global volumes', () => {
+ const volume = {
+ effects: [],
+ isGlobal: true,
+ shape: 'box' as const,
+ size: { x: 5, y: 5 },
+ priority: 0,
+ weight: 1,
+ blendDistance: 0,
+ };
+ const factor = computeVolumeFactor(volume, baseTransform, 100, 100);
+ expect(factor).toBe(1);
+ });
+
+ it('returns weight when point is inside box volume', () => {
+ const volume = {
+ effects: [],
+ isGlobal: false,
+ shape: 'box' as const,
+ size: { x: 5, y: 5 },
+ priority: 0,
+ weight: 0.8,
+ blendDistance: 0,
+ };
+ const factor = computeVolumeFactor(volume, baseTransform, 0, 0);
+ expect(factor).toBeCloseTo(0.8, 5);
+ });
+
+ it('returns 0 when point is outside box volume with no blend distance', () => {
+ const volume = {
+ effects: [],
+ isGlobal: false,
+ shape: 'box' as const,
+ size: { x: 5, y: 5 },
+ priority: 0,
+ weight: 1,
+ blendDistance: 0,
+ };
+ const factor = computeVolumeFactor(volume, baseTransform, 10, 0);
+ expect(factor).toBe(0);
+ });
+
+ it('returns interpolated factor within blend distance', () => {
+ const volume = {
+ effects: [],
+ isGlobal: false,
+ shape: 'box' as const,
+ size: { x: 5, y: 5 },
+ priority: 0,
+ weight: 1,
+ blendDistance: 4,
+ };
+ const factor = computeVolumeFactor(volume, baseTransform, 7, 0);
+ expect(factor).toBeCloseTo(0.5, 5);
+ });
+
+ it('returns 0 when point is beyond blend distance', () => {
+ const volume = {
+ effects: [],
+ isGlobal: false,
+ shape: 'box' as const,
+ size: { x: 5, y: 5 },
+ priority: 0,
+ weight: 1,
+ blendDistance: 2,
+ };
+ const factor = computeVolumeFactor(volume, baseTransform, 10, 0);
+ expect(factor).toBe(0);
+ });
+
+ it('works with sphere shape', () => {
+ const volume = {
+ effects: [],
+ isGlobal: false,
+ shape: 'sphere' as const,
+ size: { x: 5, y: 5 },
+ priority: 0,
+ weight: 1,
+ blendDistance: 0,
+ };
+ const factor = computeVolumeFactor(volume, baseTransform, 3, 0);
+ expect(factor).toBeCloseTo(1, 5);
+ });
+
+ it('returns 0 for sphere when outside', () => {
+ const volume = {
+ effects: [],
+ isGlobal: false,
+ shape: 'sphere' as const,
+ size: { x: 5, y: 5 },
+ priority: 0,
+ weight: 1,
+ blendDistance: 0,
+ };
+ const factor = computeVolumeFactor(volume, baseTransform, 10, 0);
+ expect(factor).toBe(0);
+ });
+ });
+
+ describe('blendVolumeEffects', () => {
+ it('returns empty map when no active volumes', () => {
+ const result = blendVolumeEffects([]);
+ expect(result.size).toBe(0);
+ });
+
+ it('returns single volume effects when only one active', () => {
+ const result = blendVolumeEffects([
+ {
+ data: {
+ effects: [
+ { type: 'blur', enabled: true, uniforms: { u_intensity: 5 } },
+ ],
+ isGlobal: true,
+ shape: 'box',
+ size: { x: 5, y: 5 },
+ priority: 0,
+ weight: 1,
+ blendDistance: 0,
+ },
+ factor: 1,
+ },
+ ]);
+ expect(result.size).toBe(1);
+ const blur = result.get('blur')!;
+ expect(blur.enabled).toBe(true);
+ expect(blur.uniforms.get('u_intensity')).toBe(5);
+ });
+
+ it('higher priority volume overrides lower priority', () => {
+ const result = blendVolumeEffects([
+ {
+ data: {
+ effects: [
+ { type: 'blur', enabled: true, uniforms: { u_intensity: 2 } },
+ ],
+ isGlobal: true,
+ shape: 'box',
+ size: { x: 5, y: 5 },
+ priority: 0,
+ weight: 1,
+ blendDistance: 0,
+ },
+ factor: 1,
+ },
+ {
+ data: {
+ effects: [
+ { type: 'blur', enabled: true, uniforms: { u_intensity: 10 } },
+ ],
+ isGlobal: true,
+ shape: 'box',
+ size: { x: 5, y: 5 },
+ priority: 1,
+ weight: 1,
+ blendDistance: 0,
+ },
+ factor: 1,
+ },
+ ]);
+ const blur = result.get('blur')!;
+ expect(blur.uniforms.get('u_intensity')).toBe(10);
+ });
+
+ it('lerps uniforms based on factor', () => {
+ const result = blendVolumeEffects([
+ {
+ data: {
+ effects: [
+ { type: 'blur', enabled: true, uniforms: { u_intensity: 0 } },
+ ],
+ isGlobal: true,
+ shape: 'box',
+ size: { x: 5, y: 5 },
+ priority: 0,
+ weight: 1,
+ blendDistance: 0,
+ },
+ factor: 1,
+ },
+ {
+ data: {
+ effects: [
+ { type: 'blur', enabled: true, uniforms: { u_intensity: 10 } },
+ ],
+ isGlobal: true,
+ shape: 'box',
+ size: { x: 5, y: 5 },
+ priority: 1,
+ weight: 1,
+ blendDistance: 0,
+ },
+ factor: 0.5,
+ },
+ ]);
+ const blur = result.get('blur')!;
+ expect(blur.uniforms.get('u_intensity')).toBeCloseTo(5, 5);
+ });
+
+ it('combines different effect types from multiple volumes', () => {
+ const result = blendVolumeEffects([
+ {
+ data: {
+ effects: [
+ { type: 'blur', enabled: true, uniforms: { u_intensity: 5 } },
+ ],
+ isGlobal: true,
+ shape: 'box',
+ size: { x: 5, y: 5 },
+ priority: 0,
+ weight: 1,
+ blendDistance: 0,
+ },
+ factor: 1,
+ },
+ {
+ data: {
+ effects: [
+ { type: 'vignette', enabled: true, uniforms: { u_intensity: 0.8 } },
+ ],
+ isGlobal: true,
+ shape: 'box',
+ size: { x: 5, y: 5 },
+ priority: 1,
+ weight: 1,
+ blendDistance: 0,
+ },
+ factor: 1,
+ },
+ ]);
+ expect(result.size).toBe(2);
+ expect(result.has('blur')).toBe(true);
+ expect(result.has('vignette')).toBe(true);
+ });
+
+ it('disabled effects are not included', () => {
+ const result = blendVolumeEffects([
+ {
+ data: {
+ effects: [
+ { type: 'blur', enabled: false, uniforms: { u_intensity: 5 } },
+ ],
+ isGlobal: true,
+ shape: 'box',
+ size: { x: 5, y: 5 },
+ priority: 0,
+ weight: 1,
+ blendDistance: 0,
+ },
+ factor: 1,
+ },
+ ]);
+ expect(result.size).toBe(0);
+ });
+
+ it('zero factor volume does not contribute', () => {
+ const result = blendVolumeEffects([
+ {
+ data: {
+ effects: [
+ { type: 'blur', enabled: true, uniforms: { u_intensity: 10 } },
+ ],
+ isGlobal: true,
+ shape: 'box',
+ size: { x: 5, y: 5 },
+ priority: 0,
+ weight: 1,
+ blendDistance: 0,
+ },
+ factor: 0,
+ },
+ ]);
+ expect(result.size).toBe(0);
+ });
+ });
+});
diff --git a/src/esengine/bindings/PostProcessBindings.cpp b/src/esengine/bindings/PostProcessBindings.cpp
index 871ba7254..3eb746c24 100644
--- a/src/esengine/bindings/PostProcessBindings.cpp
+++ b/src/esengine/bindings/PostProcessBindings.cpp
@@ -140,6 +140,47 @@ void postprocess_setOutputViewport(u32 x, u32 y, u32 w, u32 h) {
}
}
+void postprocess_beginScreenCapture() {
+ if (!g_postProcessPipeline) return;
+ g_postProcessPipeline->beginScreenCapture();
+}
+
+void postprocess_endScreenCapture() {
+ if (!g_postProcessPipeline) return;
+ g_postProcessPipeline->endScreenCapture();
+}
+
+void postprocess_executeScreenPasses() {
+ if (!g_postProcessPipeline) return;
+ g_postProcessPipeline->executeScreenPasses();
+}
+
+u32 postprocess_addScreenPass(const std::string& name, u32 shaderHandle) {
+ if (!g_postProcessPipeline) return 0;
+ return g_postProcessPipeline->addScreenPass(name, resource::ShaderHandle(shaderHandle));
+}
+
+void postprocess_clearScreenPasses() {
+ if (g_postProcessPipeline) {
+ g_postProcessPipeline->clearScreenPasses();
+ }
+}
+
+void postprocess_setScreenUniformFloat(const std::string& passName,
+ const std::string& uniform, f32 value) {
+ if (g_postProcessPipeline) {
+ g_postProcessPipeline->setScreenPassUniformFloat(passName, uniform, value);
+ }
+}
+
+void postprocess_setScreenUniformVec4(const std::string& passName,
+ const std::string& uniform,
+ f32 x, f32 y, f32 z, f32 w) {
+ if (g_postProcessPipeline) {
+ g_postProcessPipeline->setScreenPassUniformVec4(passName, uniform, glm::vec4(x, y, z, w));
+ }
+}
+
} // namespace esengine
#endif // ES_PLATFORM_WEB
diff --git a/src/esengine/bindings/PostProcessBindings.hpp b/src/esengine/bindings/PostProcessBindings.hpp
index e9a52878c..a8b62811a 100644
--- a/src/esengine/bindings/PostProcessBindings.hpp
+++ b/src/esengine/bindings/PostProcessBindings.hpp
@@ -29,6 +29,17 @@ void postprocess_clearPasses();
void postprocess_setOutputTarget(u32 fboId);
void postprocess_setOutputViewport(u32 x, u32 y, u32 w, u32 h);
+void postprocess_beginScreenCapture();
+void postprocess_endScreenCapture();
+void postprocess_executeScreenPasses();
+u32 postprocess_addScreenPass(const std::string& name, u32 shaderHandle);
+void postprocess_clearScreenPasses();
+void postprocess_setScreenUniformFloat(const std::string& passName,
+ const std::string& uniform, f32 value);
+void postprocess_setScreenUniformVec4(const std::string& passName,
+ const std::string& uniform,
+ f32 x, f32 y, f32 z, f32 w);
+
} // namespace esengine
#endif // ES_PLATFORM_WEB
diff --git a/src/esengine/bindings/TilemapBindings.cpp b/src/esengine/bindings/TilemapBindings.cpp
index 5a4c624e8..5a1accad4 100644
--- a/src/esengine/bindings/TilemapBindings.cpp
+++ b/src/esengine/bindings/TilemapBindings.cpp
@@ -65,7 +65,10 @@ void tilemap_submitLayer(u32 entity, u32 textureId,
f32 uvTileWidth, f32 uvTileHeight,
f32 originX, f32 originY,
f32 camLeft, f32 camBottom,
- f32 camRight, f32 camTop) {
+ f32 camRight, f32 camTop,
+ f32 tintR, f32 tintG, f32 tintB, f32 tintA,
+ f32 opacity,
+ f32 parallaxX, f32 parallaxY) {
auto* frame = ctx().renderFrame();
if (!frame) return;
@@ -80,9 +83,18 @@ void tilemap_submitLayer(u32 entity, u32 textureId,
const auto* layerData = s_tilemapSystem.getLayerData(layerEntity);
if (!layerData) return;
+ glm::vec4 finalColor(tintR, tintG, tintB, tintA * opacity);
+
+ f32 camCenterX = (camLeft + camRight) * 0.5f;
+ f32 camCenterY = (camBottom + camTop) * 0.5f;
+ f32 parallaxOffsetX = camCenterX * (1.0f - parallaxX);
+ f32 parallaxOffsetY = camCenterY * (1.0f - parallaxY);
+ f32 adjOriginX = originX + parallaxOffsetX;
+ f32 adjOriginY = originY + parallaxOffsetY;
+
auto range = tilemap::computeVisibleRange(
camLeft, -camTop, camRight, -camBottom,
- originX, -originY,
+ adjOriginX, -adjOriginY,
layerData->tile_width, layerData->tile_height,
layerData->width, layerData->height);
if (range.empty()) return;
@@ -102,9 +114,9 @@ void tilemap_submitLayer(u32 entity, u32 textureId,
u32 tileCol = tileIndex % tilesetColumns;
u32 tileRow = tileIndex / tilesetColumns;
- f32 worldX = originX + static_cast<f32>(tx) * layerData->tile_width
+ f32 worldX = adjOriginX + static_cast<f32>(tx) * layerData->tile_width
+ layerData->tile_width * 0.5f;
- f32 worldY = originY - static_cast<f32>(ty) * layerData->tile_height
+ f32 worldY = adjOriginY - static_cast<f32>(ty) * layerData->tile_height
- layerData->tile_height * 0.5f;
f32 u0 = static_cast<f32>(tileCol) * uvTileWidth;
@@ -124,7 +136,7 @@ void tilemap_submitLayer(u32 entity, u32 textureId,
base.world_angle = 0.0f;
base.layer = sortLayer;
base.depth = depth;
- base.color = glm::vec4(1.0f);
+ base.color = finalColor;
base.texture_id = glTextureId;
SpriteData sd;
@@ -268,6 +280,124 @@ u32 tiled_getTilesetTileCount(u32 handle, u32 index) {
return map->tilesets[index].tile_count;
}
+u32 tiled_getObjectGroupCount(u32 handle) {
+ const auto* map = s_tiledLoader.getMap(handle);
+ return map ? static_cast<u32>(map->object_groups.size()) : 0;
+}
+
+std::string tiled_getObjectGroupName(u32 handle, u32 index) {
+ const auto* map = s_tiledLoader.getMap(handle);
+ if (!map || index >= map->object_groups.size()) return "";
+ return map->object_groups[index].name;
+}
+
+u32 tiled_getObjectCount(u32 handle, u32 groupIndex) {
+ const auto* map = s_tiledLoader.getMap(handle);
+ if (!map || groupIndex >= map->object_groups.size()) return 0;
+ return static_cast<u32>(map->object_groups[groupIndex].objects.size());
+}
+
+f32 tiled_getObjectX(u32 handle, u32 groupIndex, u32 objIndex) {
+ const auto* map = s_tiledLoader.getMap(handle);
+ if (!map || groupIndex >= map->object_groups.size()) return 0;
+ const auto& grp = map->object_groups[groupIndex];
+ if (objIndex >= grp.objects.size()) return 0;
+ return grp.objects[objIndex].x;
+}
+
+f32 tiled_getObjectY(u32 handle, u32 groupIndex, u32 objIndex) {
+ const auto* map = s_tiledLoader.getMap(handle);
+ if (!map || groupIndex >= map->object_groups.size()) return 0;
+ const auto& grp = map->object_groups[groupIndex];
+ if (objIndex >= grp.objects.size()) return 0;
+ return grp.objects[objIndex].y;
+}
+
+f32 tiled_getObjectWidth(u32 handle, u32 groupIndex, u32 objIndex) {
+ const auto* map = s_tiledLoader.getMap(handle);
+ if (!map || groupIndex >= map->object_groups.size()) return 0;
+ const auto& grp = map->object_groups[groupIndex];
+ if (objIndex >= grp.objects.size()) return 0;
+ return grp.objects[objIndex].width;
+}
+
+f32 tiled_getObjectHeight(u32 handle, u32 groupIndex, u32 objIndex) {
+ const auto* map = s_tiledLoader.getMap(handle);
+ if (!map || groupIndex >= map->object_groups.size()) return 0;
+ const auto& grp = map->object_groups[groupIndex];
+ if (objIndex >= grp.objects.size()) return 0;
+ return grp.objects[objIndex].height;
+}
+
+f32 tiled_getObjectRotation(u32 handle, u32 groupIndex, u32 objIndex) {
+ const auto* map = s_tiledLoader.getMap(handle);
+ if (!map || groupIndex >= map->object_groups.size()) return 0;
+ const auto& grp = map->object_groups[groupIndex];
+ if (objIndex >= grp.objects.size()) return 0;
+ return grp.objects[objIndex].rotation;
+}
+
+bool tiled_getObjectEllipse(u32 handle, u32 groupIndex, u32 objIndex) {
+ const auto* map = s_tiledLoader.getMap(handle);
+ if (!map || groupIndex >= map->object_groups.size()) return false;
+ const auto& grp = map->object_groups[groupIndex];
+ if (objIndex >= grp.objects.size()) return false;
+ return grp.objects[objIndex].ellipse;
+}
+
+bool tiled_getObjectPoint(u32 handle, u32 groupIndex, u32 objIndex) {
+ const auto* map = s_tiledLoader.getMap(handle);
+ if (!map || groupIndex >= map->object_groups.size()) return false;
+ const auto& grp = map->object_groups[groupIndex];
+ if (objIndex >= grp.objects.size()) return false;
+ return grp.objects[objIndex].point;
+}
+
+u32 tiled_getObjectVertexCount(u32 handle, u32 groupIndex, u32 objIndex) {
+ const auto* map = s_tiledLoader.getMap(handle);
+ if (!map || groupIndex >= map->object_groups.size()) return 0;
+ const auto& grp = map->object_groups[groupIndex];
+ if (objIndex >= grp.objects.size()) return 0;
+ return static_cast<u32>(grp.objects[objIndex].vert_count);
+}
+
+u32 tiled_getObjectVertices(u32 handle, u32 groupIndex, u32 objIndex,
+ uintptr_t outPtr, u32 maxFloats) {
+ const auto* map = s_tiledLoader.getMap(handle);
+ if (!map || groupIndex >= map->object_groups.size()) return 0;
+ const auto& grp = map->object_groups[groupIndex];
+ if (objIndex >= grp.objects.size()) return 0;
+ const auto& verts = grp.objects[objIndex].vertices;
+ u32 count = std::min(static_cast<u32>(verts.size()), maxFloats);
+ auto* out = reinterpret_cast<f32*>(outPtr);
+ std::memcpy(out, verts.data(), count * sizeof(f32));
+ return count;
+}
+
+f32 tiled_getLayerOpacity(u32 handle, u32 index) {
+ const auto* map = s_tiledLoader.getMap(handle);
+ if (!map || index >= map->layers.size()) return 1.0f;
+ return map->layers[index].opacity;
+}
+
+u32 tiled_getLayerTintColor(u32 handle, u32 index) {
+ const auto* map = s_tiledLoader.getMap(handle);
+ if (!map || index >= map->layers.size()) return 0;
+ return map->layers[index].tint_color;
+}
+
+f32 tiled_getLayerParallaxX(u32 handle, u32 index) {
+ const auto* map = s_tiledLoader.getMap(handle);
+ if (!map || index >= map->layers.size()) return 1.0f;
+ return map->layers[index].parallax_x;
+}
+
+f32 tiled_getLayerParallaxY(u32 handle, u32 index) {
+ const auto* map = s_tiledLoader.getMap(handle);
+ if (!map || index >= map->layers.size()) return 1.0f;
+ return map->layers[index].parallax_y;
+}
+
} // namespace esengine
EMSCRIPTEN_BINDINGS(esengine_tilemap) {
@@ -303,6 +433,22 @@ EMSCRIPTEN_BINDINGS(esengine_tilemap) {
emscripten::function("tiled_getTilesetTileHeight", &esengine::tiled_getTilesetTileHeight);
emscripten::function("tiled_getTilesetColumns", &esengine::tiled_getTilesetColumns);
emscripten::function("tiled_getTilesetTileCount", &esengine::tiled_getTilesetTileCount);
+ emscripten::function("tiled_getObjectGroupCount", &esengine::tiled_getObjectGroupCount);
+ emscripten::function("tiled_getObjectGroupName", &esengine::tiled_getObjectGroupName);
+ emscripten::function("tiled_getObjectCount", &esengine::tiled_getObjectCount);
+ emscripten::function("tiled_getObjectX", &esengine::tiled_getObjectX);
+ emscripten::function("tiled_getObjectY", &esengine::tiled_getObjectY);
+ emscripten::function("tiled_getObjectWidth", &esengine::tiled_getObjectWidth);
+ emscripten::function("tiled_getObjectHeight", &esengine::tiled_getObjectHeight);
+ emscripten::function("tiled_getObjectRotation", &esengine::tiled_getObjectRotation);
+ emscripten::function("tiled_getObjectEllipse", &esengine::tiled_getObjectEllipse);
+ emscripten::function("tiled_getObjectPoint", &esengine::tiled_getObjectPoint);
+ emscripten::function("tiled_getObjectVertexCount", &esengine::tiled_getObjectVertexCount);
+ emscripten::function("tiled_getObjectVertices", &esengine::tiled_getObjectVertices);
+ emscripten::function("tiled_getLayerOpacity", &esengine::tiled_getLayerOpacity);
+ emscripten::function("tiled_getLayerTintColor", &esengine::tiled_getLayerTintColor);
+ emscripten::function("tiled_getLayerParallaxX", &esengine::tiled_getLayerParallaxX);
+ emscripten::function("tiled_getLayerParallaxY", &esengine::tiled_getLayerParallaxY);
}
#endif // ES_PLATFORM_WEB
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index a6caad1ed..0e8b9b6f4 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -366,6 +366,13 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("postprocess_clearPasses", &esengine::postprocess_clearPasses);
emscripten::function("postprocess_setOutputTarget", &esengine::postprocess_setOutputTarget);
emscripten::function("postprocess_setOutputViewport", &esengine::postprocess_setOutputViewport);
+ emscripten::function("postprocess_beginScreenCapture", &esengine::postprocess_beginScreenCapture);
+ emscripten::function("postprocess_endScreenCapture", &esengine::postprocess_endScreenCapture);
+ emscripten::function("postprocess_executeScreenPasses", &esengine::postprocess_executeScreenPasses);
+ emscripten::function("postprocess_addScreenPass", &esengine::postprocess_addScreenPass);
+ emscripten::function("postprocess_clearScreenPasses", &esengine::postprocess_clearScreenPasses);
+ emscripten::function("postprocess_setScreenUniformFloat", &esengine::postprocess_setScreenUniformFloat);
+ emscripten::function("postprocess_setScreenUniformVec4", &esengine::postprocess_setScreenUniformVec4);
emscripten::function("renderer_init", &esengine::renderer_init);
emscripten::function("renderer_resize", &esengine::renderer_resize);
diff --git a/src/esengine/renderer/PostProcessPipeline.cpp b/src/esengine/renderer/PostProcessPipeline.cpp
index f6097ecbe..fa0e5ddff 100644
--- a/src/esengine/renderer/PostProcessPipeline.cpp
+++ b/src/esengine/renderer/PostProcessPipeline.cpp
@@ -128,10 +128,14 @@ void PostProcessPipeline::shutdown() {
if (!initialized_) return;
passes_.clear();
+ screenPasses_.clear();
screenQuadVAO_.reset();
fboA_.reset();
fboB_.reset();
+ screenFBO_.reset();
fbosCreated_ = false;
+ screenFBOCreated_ = false;
+ screenCaptureActive_ = false;
if (blitShader_.isValid()) {
resourceManager_.releaseShader(blitShader_);
@@ -153,6 +157,12 @@ void PostProcessPipeline::resize(u32 width, u32 height) {
fbosCreated_ = false;
ensureFBOs();
}
+
+ if (screenFBOCreated_) {
+ screenFBO_.reset();
+ screenFBOCreated_ = false;
+ ensureScreenFBO();
+ }
}
u32 PostProcessPipeline::addPass(const std::string& name, resource::ShaderHandle shader) {
@@ -349,4 +359,125 @@ u32 PostProcessPipeline::getOutputTexture() const {
return (currentFBO_ == 0) ? fboA_->getColorAttachment() : fboB_->getColorAttachment();
}
+void PostProcessPipeline::ensureScreenFBO() {
+ if (screenFBOCreated_) return;
+
+ FramebufferSpec spec;
+ spec.width = width_;
+ spec.height = height_;
+ spec.depthStencil = false;
+
+ screenFBO_ = Framebuffer::create(spec);
+ if (!screenFBO_) {
+ ES_LOG_ERROR("PostProcessPipeline: Failed to create screen FBO");
+ return;
+ }
+
+ screenFBOCreated_ = true;
+}
+
+void PostProcessPipeline::beginScreenCapture() {
+ if (!initialized_ || screenCaptureActive_) return;
+
+ ensureScreenFBO();
+ if (!screenFBOCreated_) return;
+
+ screenFBO_->bind();
+ RenderCommand::setViewport(0, 0, width_, height_);
+ RenderCommand::clear();
+
+ screenCaptureActive_ = true;
+}
+
+void PostProcessPipeline::endScreenCapture() {
+ if (!initialized_ || !screenCaptureActive_) return;
+
+ screenFBO_->unbind();
+ screenCaptureActive_ = false;
+}
+
+void PostProcessPipeline::executeScreenPasses() {
+ if (!initialized_ || !screenFBOCreated_) return;
+
+ u32 enabledCount = 0;
+ for (const auto& pass : screenPasses_) {
+ if (pass.enabled) enabledCount++;
+ }
+
+ if (enabledCount == 0) {
+ blitToOutput(screenFBO_->getColorAttachment());
+ return;
+ }
+
+ RenderCommand::setDepthTest(false);
+ RenderCommand::setBlending(false);
+
+ ensureFBOs();
+ if (!fbosCreated_) return;
+
+ u32 inputTexture = screenFBO_->getColorAttachment();
+ u32 pingPong = 0;
+
+ for (const auto& pass : screenPasses_) {
+ if (!pass.enabled) continue;
+
+ Framebuffer* targetFBO = (pingPong == 0) ? fboA_.get() : fboB_.get();
+ targetFBO->bind();
+ RenderCommand::setViewport(0, 0, width_, height_);
+
+ renderPass(pass, inputTexture);
+
+ inputTexture = targetFBO->getColorAttachment();
+ pingPong = 1 - pingPong;
+ }
+
+ Framebuffer* lastFBO = (pingPong == 0) ? fboA_.get() : fboB_.get();
+ lastFBO->unbind();
+
+ glBindFramebuffer(GL_FRAMEBUFFER, 0);
+ RenderCommand::setViewport(0, 0, width_, height_);
+ blitToOutput(inputTexture);
+
+ RenderCommand::setBlending(true);
+ RenderCommand::setDepthTest(true);
+}
+
+u32 PostProcessPipeline::addScreenPass(const std::string& name, resource::ShaderHandle shader) {
+ PostProcessPass pass;
+ pass.name = name;
+ pass.shader = shader;
+ pass.enabled = true;
+
+ screenPasses_.push_back(pass);
+ return static_cast<u32>(screenPasses_.size() - 1);
+}
+
+void PostProcessPipeline::clearScreenPasses() {
+ screenPasses_.clear();
+}
+
+PostProcessPass* PostProcessPipeline::findScreenPass(const std::string& name) {
+ for (auto& pass : screenPasses_) {
+ if (pass.name == name) {
+ return &pass;
+ }
+ }
+ return nullptr;
+}
+
+void PostProcessPipeline::setScreenPassUniformFloat(const std::string& passName,
+ const std::string& uniform, f32 value) {
+ if (auto* pass = findScreenPass(passName)) {
+ pass->floatUniforms[uniform] = value;
+ }
+}
+
+void PostProcessPipeline::setScreenPassUniformVec4(const std::string& passName,
+ const std::string& uniform,
+ const glm::vec4& value) {
+ if (auto* pass = findScreenPass(passName)) {
+ pass->vec4Uniforms[uniform] = value;
+ }
+}
+
} // namespace esengine
diff --git a/src/esengine/renderer/PostProcessPipeline.hpp b/src/esengine/renderer/PostProcessPipeline.hpp
index 90efbb5ae..4bddd2cfb 100644
--- a/src/esengine/renderer/PostProcessPipeline.hpp
+++ b/src/esengine/renderer/PostProcessPipeline.hpp
@@ -170,6 +170,51 @@ public:
*/
void setOutputViewport(u32 x, u32 y, u32 w, u32 h);
+ /**
+ * @brief Begins screen-level capture (all camera output goes into screen FBO)
+ */
+ void beginScreenCapture();
+
+ /**
+ * @brief Ends screen-level capture
+ */
+ void endScreenCapture();
+
+ /**
+ * @brief Executes screen-level post-process passes on captured output
+ */
+ void executeScreenPasses();
+
+ /**
+ * @brief Adds a screen-level post-process pass
+ */
+ u32 addScreenPass(const std::string& name, resource::ShaderHandle shader);
+
+ /**
+ * @brief Clears all screen-level passes
+ */
+ void clearScreenPasses();
+
+ /**
+ * @brief Sets a float uniform for a screen-level pass
+ */
+ void setScreenPassUniformFloat(const std::string& passName, const std::string& uniform, f32 value);
+
+ /**
+ * @brief Sets a vec4 uniform for a screen-level pass
+ */
+ void setScreenPassUniformVec4(const std::string& passName, const std::string& uniform, const glm::vec4& value);
+
+ /**
+ * @brief Gets the screen pass count
+ */
+ u32 getScreenPassCount() const { return static_cast<u32>(screenPasses_.size()); }
+
+ /**
+ * @brief Checks if screen capture is active
+ */
+ bool isScreenCaptureActive() const { return screenCaptureActive_; }
+
private:
PostProcessPass* findPass(const std::string& name);
void ensureFBOs();
@@ -198,6 +243,14 @@ private:
u32 output_vp_y_ = 0;
u32 output_vp_w_ = 0;
u32 output_vp_h_ = 0;
+
+ Unique<Framebuffer> screenFBO_;
+ bool screenFBOCreated_ = false;
+ bool screenCaptureActive_ = false;
+ std::vector<PostProcessPass> screenPasses_;
+
+ PostProcessPass* findScreenPass(const std::string& name);
+ void ensureScreenFBO();
};
} // namespace esengine
diff --git a/src/esengine/tilemap/TiledMapLoader.cpp b/src/esengine/tilemap/TiledMapLoader.cpp
index 44608d3bb..be48ed2d7 100644
--- a/src/esengine/tilemap/TiledMapLoader.cpp
+++ b/src/esengine/tilemap/TiledMapLoader.cpp
@@ -148,6 +148,29 @@ void TiledMapLoader::collectLayers(cute_tiled_map_t* map, TiledMapData& result,
continue;
}
+ if (layer->type.ptr && std::strcmp(layer->type.ptr, "objectgroup") == 0) {
+ TiledObjectGroupInfo groupInfo;
+ groupInfo.name = layer->name.ptr ? layer->name.ptr : "";
+ for (auto* obj = layer->objects; obj; obj = obj->next) {
+ TiledObjectInfo objInfo;
+ objInfo.x = obj->x;
+ objInfo.y = obj->y;
+ objInfo.width = obj->width;
+ objInfo.height = obj->height;
+ objInfo.rotation = obj->rotation;
+ objInfo.ellipse = obj->ellipse != 0;
+ objInfo.point = obj->point != 0;
+ objInfo.vert_count = obj->vert_count;
+ if (obj->vert_count > 0 && obj->vertices) {
+ objInfo.vertices.assign(obj->vertices,
+ obj->vertices + obj->vert_count * 2);
+ }
+ groupInfo.objects.push_back(std::move(objInfo));
+ }
+ result.object_groups.push_back(std::move(groupInfo));
+ continue;
+ }
+
if (!layer->type.ptr || std::strcmp(layer->type.ptr, "tilelayer") != 0) {
continue;
}
@@ -161,6 +184,10 @@ void TiledMapLoader::collectLayers(cute_tiled_map_t* map, TiledMapData& result,
info.width = static_cast<u32>(layer->width);
info.height = static_cast<u32>(layer->height);
info.visible = layer->visible != 0;
+ info.opacity = layer->opacity;
+ info.tint_color = layer->tintcolor;
+ info.parallax_x = layer->parallaxx;
+ info.parallax_y = layer->parallaxy;
auto tileCount = static_cast<u32>(layer->data_count);
info.tiles.resize(tileCount);
diff --git a/src/esengine/tilemap/TiledMapLoader.hpp b/src/esengine/tilemap/TiledMapLoader.hpp
index 6bf632623..7242839dc 100644
--- a/src/esengine/tilemap/TiledMapLoader.hpp
+++ b/src/esengine/tilemap/TiledMapLoader.hpp
@@ -18,6 +18,10 @@ struct TiledLayerInfo {
u32 height;
bool visible;
std::vector<u16> tiles;
+ f32 opacity = 1.0f;
+ u32 tint_color = 0;
+ f32 parallax_x = 1.0f;
+ f32 parallax_y = 1.0f;
};
struct TiledTilesetInfo {
@@ -30,6 +34,23 @@ struct TiledTilesetInfo {
u32 tile_count;
};
+struct TiledObjectInfo {
+ f32 x = 0;
+ f32 y = 0;
+ f32 width = 0;
+ f32 height = 0;
+ f32 rotation = 0;
+ bool ellipse = false;
+ bool point = false;
+ i32 vert_count = 0;
+ std::vector<f32> vertices;
+};
+
+struct TiledObjectGroupInfo {
+ std::string name;
+ std::vector<TiledObjectInfo> objects;
+};
+
struct TiledMapData {
u32 width;
u32 height;
@@ -37,6 +58,7 @@ struct TiledMapData {
u32 tile_height;
std::vector<TiledLayerInfo> layers;
std::vector<TiledTilesetInfo> tilesets;
+ std::vector<TiledObjectGroupInfo> object_groups;
};
class TiledMapLoader {