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 per-component enabled toggle with inspector UI

esengine8fb3558320a2
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.js
index df6751b7e..7449c5d59 100644
--- a/desktop/public/sdk/cjs/esengine.wechat.js
+++ b/desktop/public/sdk/cjs/esengine.wechat.js
@@ -1,2 +1,2 @@
-"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function s(e,s){return t().fetch(e,s)}async function n(e){return t().readFile(e)}async function r(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,s){return t().createCanvas(e,s)}function a(){return t().now()}function l(e,t){return new Promise((s,n)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function c(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const s=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(s,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${s}": ${t}`)}}const d=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],u={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},h=new Map,p=new Set;for(const e of d)for(const t of e.extensions)h.set(t,e),p.add(t);function f(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function g(e){return h.get(f(e))}function m(e){return p.has(e.toLowerCase())}function y(){const e=[];for(const t of d)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function x(e){const t=g(e);return t?.wechatPackInclude??!1}let _=null;function w(){return _||(_=wx.getFileSystemManager()),_}function v(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(x(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return s.includes("no such file")||s.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function b(e){return new Promise((t,s)=>{w().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(v(e,t.errMsg)))}})})}function S(e,t="utf-8"){return new Promise((s,n)=>{w().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(v(e,t.errMsg)))}})})}function P(e){return new Promise(t=>{w().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function T(e){return new Promise((t,s)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function M(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}let E=!1;const C=new class{constructor(){this.name="wechat"}async fetch(e,t){return l(e,t)}async readFile(e){return b(e)}async readTextFile(e){return S(e)}async fileExists(e){return P(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return c(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const s=wx.createCanvas();return s.width=e,s.height=t,s}now(){return Date.now()}bindInputEvents(e,t){const{pixelRatio:s}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX*s,n.clientY*s)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX*s,n.clientY*s)}),wx.onTouchEnd(t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)})}},A=1920,R=1080,I={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};const F=4294967295,B=4294967295;function D(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(D);const t={};for(const s in e)t[s]=D(e[s]);return t}let k=0;function L(e,t){const s=++k;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...D(t),...e}:D(t)}}function W(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function U(e,t){const s=W(),n=s.get(e);if(n)return n;const r=L(e,t);return s.set(e,r),O(e,t,!1),r}function $(e){const t=W(),s=t.get(e);if(s)return s;const n=L(e,{});return t.set(e,n),O(e,{},!0),n}function z(e){return W().get(e)}function O(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function H(e){return!0===e._builtin}const j=new Map;function X(e,t){j.set(e,t)}function N(e){return j.get(e)??z(e)}function V(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return j.set(e,s),s}const Y={Perspective:0,Orthographic:1},G={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},q={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},J=V("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),K=V("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Q=V("Sprite",{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),Z=V("Camera",{projectionType:Y.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:G.ColorAndDepth}),ee=V("Canvas",{designResolution:{x:A,y:R},pixelsPerUnit:100,scaleMode:q.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),te=V("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),se=V("Parent",{entity:0}),ne=V("Children",{entities:[]}),re=V("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:B}),oe=V("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),ie={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},ae=U("SceneOwner",{scene:"",persistent:!1});X("Name",ie);const le=V("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ce=V("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),de=V("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ue=V("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),he={Static:0,Kinematic:1,Dynamic:2};let pe=0;function fe(e,t){const s=++pe;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function ge(e){return{_type:"res",_resource:e}}function me(e){return{_type:"res_mut",_resource:e}}class ye{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class xe{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new ye(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const _e=fe({delta:0,elapsed:0,frameCount:0},"Time");function we(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}class ve{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>we(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=s.length,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let d=null;this.world_.beginIteration();try{for(const u of n){if(null!==d&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(d,t.component,t.data)}if(i){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(u,t[s])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,s[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];d=u}yield a}}finally{if(this.world_.endIteration(),null!==d&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(d,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class be{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let s;return s=H(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Se{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new be(this,null);return this.spawned_.push(e),e}entity(e){return new be(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Pe;exports.Schedule=void 0,(Pe=exports.Schedule||(exports.Schedule={}))[Pe.Startup=0]="Startup",Pe[Pe.First=1]="First",Pe[Pe.PreUpdate=2]="PreUpdate",Pe[Pe.Update=3]="Update",Pe[Pe.PostUpdate=4]="PostUpdate",Pe[Pe.Last=5]="Last",Pe[Pe.FixedPreUpdate=10]="FixedPreUpdate",Pe[Pe.FixedUpdate=11]="FixedUpdate",Pe[Pe.FixedPostUpdate=12]="FixedPostUpdate";let Te=0;function Me(e,t,s){const n=++Te;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Ee(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class Ce{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Se&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new ve(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Se(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ae{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const Re=fe(new Ae,"Input");class Ie{constructor(e){this.target_=e??null}build(e){const s=new Ae;e.insertResource(Re,s),t().bindInputEvents({onKeyDown(e){s.keysDown.has(e)||s.keysPressed.add(e),s.keysDown.add(e)},onKeyUp(e){s.keysDown.delete(e),s.keysReleased.add(e)},onPointerMove(e,t){s.mouseX=e,s.mouseY=t},onPointerDown(e,t,n){s.mouseX=t,s.mouseY=n,s.mouseButtons.add(e),s.mouseButtonsPressed.add(e)},onPointerUp(e){s.mouseButtons.delete(e),s.mouseButtonsReleased.add(e)},onWheel(e,t){s.scrollDeltaX+=e,s.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.Last,Me([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Fe=new Ie;function Be(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=De(t[e]),o=De(r);"null"!==s&&"undefined"!==s&&(s!==o&&null!=r&&n.push({field:e,expected:s,actual:o,value:r}))}return n}function De(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ke(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}let Le=null;function We(e){Le=e}function Ue(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Le&&Le(e,t)}function $e(e){const t={};for(const s of Object.keys(e)){const n=e[s];if(null==n||"object"!=typeof n||Array.isArray(n))t[s]=n;else{const e=n;t[s]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:$e(e)}}return t}class ze{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw Ue(e,"spawn"),e}else e=this.entities_.size+1;return this.entities_.add(e),e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){Ue(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t)this.tsStorage_.get(s)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){Ue(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Ue(t,`removeParent(entity=${e})`)}}insert(e,t,s){return H(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return H(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return H(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(H(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return Ue(s,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");H(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const s=this.cppRegistry_;return t={add:s[`add${e}`].bind(s),get:s[`get${e}`].bind(s),has:s[`has${e}`].bind(s),remove:s[`remove${e}`].bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Be(t._name,t._default,n);if(e.length>0)throw new Error(ke(t._name,e))}const r={...t._default,...n};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,$e(r))}catch(s){Ue(s,`insertBuiltin(${t._name}, entity=${e})`)}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return this.getBuiltinMethods(t._cppName).get(e)}catch(s){return Ue(s,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(s){return Ue(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Ue(s,`removeBuiltin(${t._name}, entity=${e})`)}}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const r=Be(t._name,t._default,e);if(r.length>0)throw new Error(ke(t._name,r));n=e}const r=t.create(n);this.getStorage(t).set(e,r),this.worldVersion_++;let o=this.entityComponents_.get(e);return o||(o=[],this.entityComponents_.set(e,o)),-1===o.indexOf(t._id)&&o.push(t._id),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getComponentTypes(e){const t=[];for(const[s,n]of this.builtinMethodCache_)try{n.has(e)&&t.push(s)}catch{}if(this.cppRegistry_)for(const[s,n]of j)if(H(n)&&!t.includes(s))try{this.getBuiltinMethods(n._cppName).has(e)&&t.push(s)}catch{}const s=this.entityComponents_.get(e);if(s){const e="undefined"!=typeof window?window.__esengine_componentRegistry:void 0;if(e)for(const n of s)for(const[s,r]of e)if(r._id===n){t.push(s);break}}return t}getEntitiesWithComponents(e,t=[],s=[]){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();let n=e.map(e=>e._name).sort().join(",");t.length>0&&(n+="|+"+t.map(e=>e._name).sort().join(",")),s.length>0&&(n+="|-"+s.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(n);if(r&&r.version===this.worldVersion_)return r.result;let o=null,i=1/0;for(const t of e)if(!H(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<i&&(i=s,o=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const l=o?o.keys():this.entities_;for(const t of l){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&a.push(t)}return this.queryCache_.set(n,{version:this.worldVersion_,result:a}),a}}const Oe=fe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var He;function je(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(He=exports.BlendMode||(exports.BlendMode={}))[He.Normal=0]="Normal",He[He.Additive=1]="Additive",He[He.Multiply=2]="Multiply",He[He.Screen=3]="Screen",He[He.PremultipliedAlpha=4]="PremultipliedAlpha";let Xe=null,Ne=null,Ve=1;const Ye=new Map;function Ge(e){Xe=e,Ne=e.getResourceManager(),rt()}function qe(){0!==Ze&&Xe&&(Xe._free(Ze),Ze=0),Ye.clear(),Ve=1,Qe=!1,tt.clear(),st=null,Ne=null,Xe=null}function Je(){if(!Ne)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ne}const Ke={createShader:(e,t)=>Je().createShader(e,t),releaseShader(e){e>0&&Je().releaseShader(e)},create(e){const t=Ve++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))s.uniforms.set(t,n);return Ye.set(t,s),t},get:e=>Ye.get(e),setUniform(e,t,s){const n=Ye.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ye.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ye.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ye.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=Ye.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ye.get(e);return t?.shader??0},release(e){Ye.delete(e)},isValid:e=>Ye.has(e),releaseAll(){Ye.clear()},createFromAsset(e,t){const s={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)s[t]=n;else if("object"==typeof n&&null!==n){const e=n;"a"in e?s[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(s[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:s,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ye.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Ve++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ye.set(s,n),s},toAssetData(e,t){const s=Ye.get(e);if(!s)return null;const n={};for(const[e,t]of s.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:s.blendMode,depthTest:s.depthTest,properties:n}},getUniforms(e){const t=Ye.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Qe=!1,Ze=0;const et=4096,tt=new Map;let st=null;function nt(e){const t=(0===Ze&&Xe&&(Ze=Xe._malloc(et)),Ze);if(0===t||!Xe)return{ptr:0,count:0};let s=0,n=0;const r=Xe.HEAPU8,o=Xe.HEAPU32,i=Xe.HEAPF32;for(const[a,l]of e){if(s+128>et)break;let e=tt.get(a);e||(st||(st=new TextEncoder),e=st.encode(a),tt.set(a,e));const c=e.length,d=4*Math.ceil(c/4);o[t+s>>2]=c,s+=4,r.set(e,t+s),s+=d;let u=0,h=[0,0,0,0];if("number"==typeof l)u=0,h[0]=l;else if(Array.isArray(l)){u=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(u=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(u=2,h=[l.x,l.y,l.z,0]):"y"in l&&(u=1,h=[l.x,l.y,0,0]);o[t+s>>2]=u,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function rt(){if(!Xe||Qe)return;Xe.materialDataProvider=(e,t,s,n,r)=>{const o=Ye.get(e);if(!o)return Xe.HEAPU32[t>>2]=0,Xe.HEAPU32[s>>2]=0,Xe.HEAPU32[n>>2]=0,void(Xe.HEAPU32[r>>2]=0);Xe.HEAPU32[t>>2]=o.shader,Xe.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=nt(o.uniforms);Xe.HEAPU32[n>>2]=i,Xe.HEAPU32[r>>2]=a},Qe=!0}const ot={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class it{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{o.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class at{constructor(e,t=""){this.cache_=new it,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ke.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ke.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await o(t))throw new Error(`Material file not found: ${t}`);const s=await r(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const i=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(i);return{handle:Ke.createFromAsset(n,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const lt=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}]]);function ct(e){return lt.get(e)?.fields??[]}function dt(e,t){const s=new Map;for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,ie,{value:n.name}),!1!==n.visible)for(const s of n.components)ht(e,t,s,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}async function ut(e,t,s){const n=new Map,r=s?.assetServer,o=s?.assetBaseUrl,i=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=lt.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,d=new Map,u=new Map,h=[];for(const e of r)h.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)h.push((async()=>{try{const n=await t.loadMaterial(e,s);d.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),d.set(e,0)}})());for(const e of i)h.push((async()=>{try{const n=await t.loadBitmapFont(e,s);u.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),u.set(e,0)}})());for(const e of a)h.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(h);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=lt.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":s[e.field]=c.get(t)??0;break;case"material":s[e.field]=d.get(t)??0;break;case"font":s[e.field]=u.get(t)??0}}}}(t,r,o,i);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,ie,{value:s.name}),!1!==s.visible)for(const n of s.components)ht(e,t,n,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function ht(e,t,s,n){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=N(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}class pt{constructor(e){this.textureCache_=new it,this.shaderCache_=new it,this.jsonCache_=new it,this.textCache_=new it,this.binaryCache_=new it,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new it,this.prefabCache_=new it,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.module_=e,this.canvas_=i(I.textCanvasSize,I.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new at(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),Ke.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),d="binary"===g(e)?.contentType,u=d?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(u,o,d);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=l.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=g(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${n}`:n,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return ut(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,s,a,o.length,1,n);return this.module_._free(a),{handle:l,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Ke.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await o(t))throw new Error(`Shader file not found: ${e}`);const n=await r(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:a}=this.parseEsShader(n);if(!i||!a)throw new Error(`Invalid shader format: ${e}`);return Ke.createShader(i,a)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return r(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return n(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const r=await s(e);if(!r.ok)throw new Error(`Failed to fetch binary: ${e} (${r.status})`);return r.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const ft=fe(null,"Assets");class gt{build(e){const t=e.wasmModule;t?e.insertResource(ft,new pt(t)):console.warn("AssetPlugin: No WASM module available")}}const mt=new gt;async function yt(e,t,s){const{entities:n,rootId:r}=await _t(t,s?.overrides??[],s,void 0,new Set),o={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await ut(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=i.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:i}}const xt=10;async function _t(e,t,s,n,r,o=0){if(o>xt)throw new Error(`Prefab nesting depth exceeded ${xt}. Check for deep or circular nesting in: ${e.name}`);const i=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,a++)}const l=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await _t(e,n.nestedPrefab.overrides,s,a,r,o+1);i.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?i.get(n.parent)??null:null),l.push(...t.entities);continue}const c=i.get(n.prefabEntityId),d=n.prefabEntityId===e.rootEntityId,u={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:d?null:null!==n.parent?i.get(n.parent)??null:null,children:n.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};wt(u,t),l.push(u)}const c=i.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function wt(e,t){for(const s of t)if(s.prefabEntityId===e.prefabEntityId)switch(s.type){case"property":if(s.componentType&&void 0!==s.propertyName){const t=e.components.find(e=>e.type===s.componentType);t&&(t.data[s.propertyName]=s.value)}break;case"name":"string"==typeof s.value&&(e.name=s.value);break;case"visibility":"boolean"==typeof s.value&&(e.visible=s.value);break;case"component_added":if(s.componentData){e.components.some(e=>e.type===s.componentData.type)||e.components.push({type:s.componentData.type,data:JSON.parse(JSON.stringify(s.componentData.data))})}break;case"component_removed":s.componentType&&(e.components=e.components.filter(e=>e.type!==s.componentType))}}class vt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return yt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const bt=fe(null,"Prefabs");class St{constructor(){this.name="PrefabsPlugin",this.dependencies=[ft]}build(e){const t=e.getResource(ft);e.insertResource(bt,new vt(e.world,t))}}const Pt=new St;let Tt=null,Mt=0,Et=0,Ct=0;const At=new Float32Array(256);function Rt(e){Tt=e,Mt=Tt._malloc(64),Et=Tt._malloc(64),Ct=Tt._malloc(1024)}function It(){Tt&&(Mt&&(Tt._free(Mt),Mt=0),Et&&(Tt._free(Et),Et=0),Ct&&(Tt._free(Ct),Ct=0)),Tt=null}function Ft(){if(!Tt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Tt}const Bt={r:1,g:1,b:1,a:1},Dt={begin(e){const t=Ft();try{t.HEAPF32.set(e,Mt/4),t.draw_begin(Mt)}catch(e){Ue(e,"Draw.begin")}},end(){try{Ft().draw_end()}catch(e){Ue(e,"Draw.end")}},line(e,t,s,n=1){try{Ft().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ue(e,"Draw.line")}},rect(e,t,s,n=!0){try{Ft().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ue(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{Ft().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ue(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,r=32){try{Ft().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Ue(e,"Draw.circle")}},circleOutline(e,t,s,n=1,r=32){try{Ft().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Ue(e,"Draw.circleOutline")}},texture(e,t,s,n=Bt){try{Ft().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Ue(e,"Draw.texture")}},textureRotated(e,t,s,n,r=Bt){try{Ft().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)}catch(e){Ue(e,"Draw.textureRotated")}},setLayer(e){Ft().draw_setLayer(e)},setDepth(e){Ft().draw_setDepth(e)},getDrawCallCount:()=>Tt?Tt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Tt?Tt.draw_getPrimitiveCount():0,setBlendMode(e){Ft().draw_setBlendMode(e)},setDepthTest(e){Ft().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=Ft();n.HEAPF32.set(s,Et/4),n.draw_mesh(e,t,Et)}catch(s){Ue(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=Ft(),r=Ke.get(t);if(!r)return;if(Dt.setBlendMode(r.blendMode),Dt.setDepthTest(r.depthTest),0===r.uniforms.size)return void Dt.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,Et/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=Wt(t);if(!(n<0)){if(je(s))At[o++]=10,At[o++]=n,At[o++]=s.slot??e++,At[o++]=s.textureId;else if("number"==typeof s)At[o++]=1,At[o++]=n,At[o++]=s;else if(Array.isArray(s)){At[o++]=s.length,At[o++]=n;for(let e=0;e<s.length;e++)At[o++]=s[e]}else"w"in s?(At[o++]=4,At[o++]=n,At[o++]=s.x,At[o++]=s.y,At[o++]=s.z,At[o++]=s.w):"z"in s?(At[o++]=3,At[o++]=n,At[o++]=s.x,At[o++]=s.y,At[o++]=s.z):(At[o++]=2,At[o++]=n,At[o++]=s.x,At[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(At.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void n.draw_mesh(e,r.shader,Et);n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),Ct/4),n.draw_meshWithUniforms(e,r.shader,Et,Ct,o)}catch(s){Ue(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},kt={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17},Lt=new Set;function Wt(e){const t=kt[e];return void 0!==t?t:(Lt.has(e)||(Lt.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(kt).join(", ")}`)),-1)}const Ut=new Map;function $t(e,t,s){Ut.set(e,{fn:t,scene:s??""})}function zt(e){Ut.delete(e)}function Ot(){Ut.clear()}var Ht;exports.DataType=void 0,(Ht=exports.DataType||(exports.DataType={}))[Ht.Float=1]="Float",Ht[Ht.Float2=2]="Float2",Ht[Ht.Float3=3]="Float3",Ht[Ht.Float4=4]="Float4",Ht[Ht.Int=5]="Int",Ht[Ht.Int2=6]="Int2",Ht[Ht.Int3=7]="Int3",Ht[Ht.Int4=8]="Int4";let jt=null,Xt=0,Nt=0,Vt=0;function Yt(e){jt=e,Xt=jt._malloc(262144),Nt=jt._malloc(65536),Vt=jt._malloc(256)}function Gt(){jt&&(Xt&&jt._free(Xt),Nt&&jt._free(Nt),Vt&&jt._free(Vt),Xt=0,Nt=0,Vt=0),jt=null}function qt(){if(!jt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return jt}const Jt={create(e){const t=qt(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,Xt/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Vt,r).set(o),t.geometry_init(s,Xt,n,Vt,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Nt,n).set(e.indices),t.geometry_setIndices16(s,Nt,n)}else{new Uint32Array(t.HEAPU8.buffer,Nt,n).set(e.indices),t.geometry_setIndices32(s,Nt,n)}}return s},updateVertices(e,t,s=0){const n=qt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,Xt/4),n.geometry_updateVertices(e,Xt,r,s)},release(e){e>0&&qt().geometry_release(e)},isValid:e=>!(!jt||e<=0)&&jt.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Jt.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;s.push(o,i,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Jt.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),s=Math.min(s,o.y),n=Math.max(n,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-s)/(r-s);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return Jt.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(i)})}};let Kt=null;function Qt(e){Kt=e}function Zt(){Kt&&ts.isInitialized()&&ts.shutdown(),Kt=null}function es(){if(!Kt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Kt}const ts={init(e,t){try{return es().postprocess_init(e,t)}catch(s){return Ue(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{es().postprocess_shutdown()}catch(e){Ue(e,"PostProcess.shutdown")}},resize(e,t){try{es().postprocess_resize(e,t)}catch(s){Ue(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return es().postprocess_addPass(e,t)}catch(t){return Ue(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{es().postprocess_removePass(e)}catch(t){Ue(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{es().postprocess_setPassEnabled(e,t)}catch(t){Ue(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return es().postprocess_isPassEnabled(e)}catch(t){return Ue(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{es().postprocess_setUniformFloat(e,t,s)}catch(s){Ue(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{es().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){Ue(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{es().postprocess_begin()}catch(e){Ue(e,"PostProcess.begin")}},end(){try{es().postprocess_end()}catch(e){Ue(e,"PostProcess.end")}},getPassCount(){try{return es().postprocess_getPassCount()}catch(e){return Ue(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Kt)return!1;try{return Kt.postprocess_isInitialized()}catch(e){return Ue(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{es().postprocess_setBypass(e)}catch(e){Ue(e,"PostProcess.setBypass")}},isBypassed(){if(!Kt)return!0;try{return Kt.postprocess_isBypassed()}catch(e){return Ue(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Ke.createShader(ss,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>Ke.createShader(ss,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Ke.createShader(ss,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Ke.createShader(ss,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},ss="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var ns;exports.RenderStage=void 0,(ns=exports.RenderStage||(exports.RenderStage={}))[ns.Background=0]="Background",ns[ns.Opaque=1]="Opaque",ns[ns.Transparent=2]="Transparent",ns[ns.Overlay=3]="Overlay";let rs=null,os=0;function is(e){rs=e,os=rs._malloc(64)}function as(){rs&&os&&(rs._free(os),os=0),rs=null}const ls={init(e,t){rs?.renderer_init(e,t)},resize(e,t){rs?.renderer_resize(e,t)},begin(e,t){if(rs&&os)try{rs.HEAPF32.set(e,os/4),rs.renderer_begin(os,t??0)}catch(e){Ue(e,"Renderer.begin")}},flush(){try{rs?.renderer_flush()}catch(e){Ue(e,"Renderer.flush")}},end(){try{rs?.renderer_end()}catch(e){Ue(e,"Renderer.end")}},submitSprites(e){if(rs)try{rs.renderer_submitSprites(e._cpp)}catch(e){Ue(e,"Renderer.submitSprites")}},submitBitmapText(e){if(rs)try{rs.renderer_submitBitmapText(e._cpp)}catch(e){Ue(e,"Renderer.submitBitmapText")}},submitSpine(e){if(rs)try{rs.renderer_submitSpine?.(e._cpp)}catch(e){Ue(e,"Renderer.submitSpine")}},setStage(e){rs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>rs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){rs?.renderer_releaseTarget(e)},getTargetTexture:e=>rs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>rs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){rs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){rs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){rs?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){rs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>rs?rs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>rs?{drawCalls:rs.renderer_getDrawCalls(),triangles:rs.renderer_getTriangles(),sprites:rs.renderer_getSprites(),text:rs.renderer_getText(),spine:rs.renderer_getSpine?.()??0,meshes:rs.renderer_getMeshes(),culled:rs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let cs=null;function ds(e){cs=e}function us(){cs=null}const hs={enable(){cs?.gl_enableErrorCheck(!0)},disable(){cs?.gl_enableErrorCheck(!1)},check:e=>cs?.gl_checkErrors(e)??0,diagnose(){cs?.renderer_diagnose()}};class ps{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:o}=e;n===this.lastWidth_&&r===this.lastHeight_||(ls.resize(n,r),ts.isInitialized()&&ts.getPassCount()>0&&ts.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),ls.setViewport(0,0,n,r),ls.clearBuffers(3),ls.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),ls.submitSprites(t),ls.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):ls.submitSpine(t),ls.flush(),this.executeDrawCallbacks(s,o),ls.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;ls.setViewport(n.x,n.y,n.w,n.h),ls.setScissor(n.x,n.y,n.w,n.h,!0),ls.clearBuffers(r),ls.setScissor(0,0,0,0,!1),ls.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),ls.submitSprites(t),ls.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):ls.submitSpine(t),ls.flush(),this.executeDrawCallbacks(s,o),ls.end()}executeDrawCallbacks(e,t){const s=Ut;if(s.size>0){Dt.begin(e);const n=[];for(const[e,r]of s.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}Dt.end();for(const e of n)zt(e)}}}const fs="__scene_transition_overlay__";class gs{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class ms{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,ae,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),$t(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=ts.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){ts.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,ae)){const s=this.app_.world.get(e,ae);s.persistent=t,this.app_.world.insert(e,ae,s)}}}class ys{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_)return void console.warn(`[SceneManager] Transition already in progress, ignoring switchTo("${e}")`);"fade"!==(t?.transition??"none")?(this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)):await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??I.sceneTransitionDuration,r=t.color??{...I.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},$t(fs,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),s="fade-out"===this.transition_.phase?t:1-t;Dt.setLayer(9999),Dt.setDepth(9999),Dt.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:s})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,s=this.activeScene_;(async()=>{s&&s!==e&&await this.unload(s,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,zt(fs)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,zt(fs),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new gs(t);this.scenes_.set(e,s);const n=new ms(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(ft)?this.app_.getResource(ft):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(ft)&&(t.assetServer=this.app_.getResource(ft));const n=await ut(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,ae,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=_s(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new gs(t);this.scenes_.set(e,s);const n=new ms(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(ft)?this.app_.getResource(ft):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(ft)&&(t.assetServer=this.app_.getResource(ft));const n=await ut(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,ae,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=_s(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const r=t?.keepPersistent??!0;for(const e of s.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,ae)){if(this.app_.world.get(e,ae).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())zt(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{ts.removePass(e)}catch{}s.postProcessPasses.length=0,this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(t&&"running"===t.status){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Q)){const s=this.app_.world.get(e,Q);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,Q,s)}}}wake(e){const t=this.scenes_.get(e);if(t&&"sleeping"===t.status){t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Q)){const s=this.app_.world.get(e,Q),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,Q,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{ts.setEnabled(s,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,s]of this.scenes_)"running"===s.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const xs=fe(null,"SceneManager");function _s(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(xs).getSceneStatus(t)&&s._fn(...n)}}}const ws=Me([me(xs),ge(_e)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),vs={name:"SceneManager",build(e){const t=new ys(e);e.insertResource(xs,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(xs),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(exports.Schedule.Startup,s),e.addSystemToSchedule(exports.Schedule.Last,ws)}};class bs{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=a(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(exports.Schedule.Last);else{this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),this.step_pending_&&(this.step_pending_=!1)}requestAnimationFrame(this.mainLoop)},this.world_=new ze,this.resources_=new xe;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new bs}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return We(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(xs).register(e),this}setInitialScene(e){return this.getResource(xs).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Ce(this.world_,this.resources_),this.resources_.insert(_e,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1,Ot();const e=[us,as,Zt,Gt,qe,It];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,o=i=>{if(n.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}r.delete(i),n.add(i),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(_e);t.delta=e,t.elapsed+=e,t.frameCount++}}const Ss=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ps(e,t,s,n,r){const o=e*t/s,i=e;switch(n){case q.FixedWidth:return o;case q.FixedHeight:return i;case q.Expand:return Math.max(o,i);case q.Shrink:return Math.min(o,i);case q.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function Ts(e,t,s,n,r,o){if(0===s||0===n)return[];const i=e.registry_getCameraEntities(t);if(0===i.length)return[];const a=o&&r?i.filter(e=>{const t=r.tryGet(e,ae);return!t||""===t.scene||o.has(t.scene)}):i;if(0===a.length)return[];const l=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),c=[];for(const e of a){const r=t.getCamera(e),o=t.getLocalTransform(e),i={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=i.w*s/(i.h*n);let d,u=0,h=0;if(r.projectionType===Y.Orthographic){if(h=r.orthoSize,l){h=Ps(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}u=h*a,d=Es(-u,u,-h,h,-r.farPlane,r.farPlane)}else d=As(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const p=Is(o.position.x,o.position.y,o.position.z);c.push({entity:e,viewProjection:new Float32Array(Bs(d,p)),viewportRect:i,clearFlags:r.clearFlags,priority:r.priority,halfW:u,halfH:h,cameraX:o.position.x,cameraY:o.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const Ms=new Float32Array(16);function Es(e,t,s,n,r,o){const i=Ms;i.fill(0);const a=t-e,l=n-s,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(n+s)/l,i[14]=-(o+r)/c,i[15]=1,i}const Cs=new Float32Array(16);function As(e,t,s,n){const r=Cs;r.fill(0);const o=1/Math.tan(e/2),i=s-n;return r[0]=o/t,r[5]=o,r[10]=(n+s)/i,r[11]=-1,r[14]=2*n*s/i,r}const Rs=new Float32Array(16);function Is(e,t,s){const n=Rs;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=-e,n[13]=-t,n[14]=-s,n[15]=1,n}const Fs=new Float32Array(16);function Bs(e,t){const s=Fs;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}var Ds,ks,Ls;exports.TextAlign=void 0,(Ds=exports.TextAlign||(exports.TextAlign={}))[Ds.Left=0]="Left",Ds[Ds.Center=1]="Center",Ds[Ds.Right=2]="Right",exports.TextVerticalAlign=void 0,(ks=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[ks.Top=0]="Top",ks[ks.Middle=1]="Middle",ks[ks.Bottom=2]="Bottom",exports.TextOverflow=void 0,(Ls=exports.TextOverflow||(exports.TextOverflow={}))[Ls.Visible=0]="Visible",Ls[Ls.Clip=1]="Clip",Ls[Ls.Ellipsis=2]="Ellipsis";const Ws=U("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2}),Us=U("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class $s{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(I.textCanvasSize,I.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),d=Math.ceil(.2*e.fontSize),u=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=r?Math.ceil(o):u+2*d,f=r?Math.ceil(i):h+2*d;if(r&&e.overflow===exports.TextOverflow.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(n.width<p||n.height<f){const e=Math.max(n.width,this.nextPowerOf2(p)),t=Math.max(n.height,this.nextPowerOf2(f));n.width=e,n.height=t}const g=Math.round(255*e.color.r),m=Math.round(255*e.color.g),y=Math.round(255*e.color.b),x=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${g}, ${m}, ${y}, ${x})`,r&&e.overflow===exports.TextOverflow.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const _=l.length*c;let w;if(r)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=d;break;case exports.TextVerticalAlign.Middle:w=(f-_)/2;break;case exports.TextVerticalAlign.Bottom:w=f-_-d;break;default:w=d}else w=d;let v=w;for(const t of l){let n;switch(e.align){case exports.TextAlign.Left:n=d;break;case exports.TextAlign.Center:n=p/2;break;case exports.TextAlign.Right:n=p-d;break;default:n=d}s.fillText(t,n,v),v+=c}r&&e.overflow===exports.TextOverflow.Clip&&s.restore();const b=s.getImageData(0,0,p,f),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),T=this.module._malloc(S.length);this.module.HEAPU8.set(S,T);const M=P.createTexture(p,f,T,S.length,1,!0);return this.module._free(T),{textureHandle:M,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function zs(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function Os(e,t,s){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(s?s.size.x:0)||e.containerHeight!==(s?s.size.y:0)}class Hs{build(e){X("Text",Ws);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new $s(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Ws));for(const e of r.keys())n.valid(e)&&n.has(e,Ws)||r.delete(e);const e=n.getEntitiesWithComponents([Ws]);for(const t of e){const e=n.get(t,Ws),o=n.has(t,Us)?n.get(t,Us):null,i=r.get(t);if(i&&!Os(i,e,o))continue;n.has(t,Q)||n.insert(t,Q,{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=s.renderForEntity(t,e,o),l=n.get(t,Q);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,n.insert(t,Q,l),r.set(t,zs(e,o))}}))}}const js=new Hs,Xs=U("UIMask",{enabled:!0,mode:"scissor"});function Ns(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,o-n)}}function Vs(e,t,s,n,r,o,i,a,l,c,d){const u=e-s*r,h=e+s*(1-r),p=t-n*o,f=t+n*(1-o);function g(e,t){const s=i[0]*e+i[4]*t+i[12],n=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(s/r)+.5)*c,l+(.5*(n/r)+.5)*d]}const[m,y]=g(u,p),[x,_]=g(h,f),w=Math.min(m,x),v=Math.max(m,x),b=Math.min(y,_),S=Math.max(y,_);return{x:Math.round(w),y:Math.round(b),w:Math.round(v-w),h:Math.round(S-b)}}function Ys(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],d=e[7],u=e[8],h=e[9],p=e[10],f=e[11],g=e[12],m=e[13],y=e[14],x=e[15],_=n*l-r*a,w=n*c-o*a,v=n*d-i*a,b=r*c-o*l,S=r*d-i*l,P=o*d-i*c,T=u*m-h*g,M=u*y-p*g,E=u*x-f*g,C=h*y-p*m,A=h*x-f*m,R=p*x-f*y;let I=_*R-w*A+v*C+b*E-S*M+P*T;return 0===I||(I=1/I,s[0]=(l*R-c*A+d*C)*I,s[1]=(o*A-r*R-i*C)*I,s[2]=(m*P-y*S+x*b)*I,s[3]=(p*S-h*P-f*b)*I,s[4]=(c*E-a*R-d*M)*I,s[5]=(n*R-o*E+i*M)*I,s[6]=(y*v-g*P-x*w)*I,s[7]=(u*P-p*v+f*w)*I,s[8]=(a*A-l*E+d*T)*I,s[9]=(r*E-n*A-i*T)*I,s[10]=(g*S-m*v+x*_)*I,s[11]=(h*v-u*S-f*_)*I,s[12]=(l*M-a*C-c*T)*I,s[13]=(n*C-r*M+o*T)*I,s[14]=(m*w-g*b-y*_)*I,s[15]=(u*b-h*w+p*_)*I),s}function Gs(e,t,s,n,r,o,i){const a=(e-n)/o*2-1,l=(t-r)/i*2-1,c=s[0]*a+s[4]*l+s[12],d=s[1]*a+s[5]*l+s[13],u=s[3]*a+s[7]*l+s[15];return{x:c/u,y:d/u}}function qs(e,t,s,n,r,o,i,a,l,c){const d=2*Math.atan2(l,c),u=Math.sin(-d),h=Math.cos(-d),p=e-s,f=t-n,g=p*h-f*u+s,m=p*u+f*h+n;return g>=s-r*i&&g<=s+r*(1-i)&&m>=n-o*a&&m<=n+o*(1-a)}function Js(e,t,s,n,r,o,i){if(!e.has(t,Us)||!e.has(t,K))return null;const a=e.get(t,Us),l=e.get(t,K),c=a.size.x*l.scale.x,d=a.size.y*l.scale.y;return Vs(l.position.x,l.position.y,c,d,a.pivot.x,a.pivot.y,s,n,r,o,i)}function Ks(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Xs]);if(0===l.length)return;const c=[],d=[],u=new Set,h=new Set;for(const e of l){const s=t.get(e,Xs);s.enabled&&(u.add(e),"stencil"===s.mode?(d.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,r,o,i,a,l,c){const d=[];for(const e of n){let s=!0,n=e;for(;t.has(n,se);){const e=t.get(n,se);if(r.has(e.entity)){if("scissor"===t.get(e.entity,Xs).mode){s=!1;break}}n=e.entity}s&&d.push(e)}function u(n,d){const h=e.getChildEntities(s,n);for(const s of h){let n=d;if(r.has(s)){if("scissor"===t.get(s,Xs).mode){const e=Js(t,s,o,i,a,l,c);e&&(n=Ns(d,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),u(s,n)}}for(const e of d){const s=Js(t,e,o,i,a,l,c);s&&u(e,s)}}(e,t,s,c,u,n,r,o,i,a),d.length>0&&function(e,t,s,n,r){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0,n=e;for(;t.has(n,se);){const e=t.get(n,se);if(r.has(e.entity)){s=!1;break}n=e.entity}s&&o.push(e)}let i=1;function a(t,n){e.renderer_setEntityStencilMask(t,n);const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){a(t,i++)}else e.renderer_setEntityStencilTest(t,n),l(t,n)}function l(t,n){const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){a(t,i++)}else e.renderer_setEntityStencilTest(t,n),l(t,n)}for(const e of o){a(e,i++)}}(e,t,s,d,h)}catch(t){e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class Qs{build(e){if(X("UIMask",Xs),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Ks(e.wasmModule,e.world))}}const Zs=new Qs,en=U("Interactable",{enabled:!0,blockRaycast:!0}),tn=U("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var sn;exports.ButtonState=void 0,(sn=exports.ButtonState||(exports.ButtonState={}))[sn.Normal=0]="Normal",sn[sn.Hovered=1]="Hovered",sn[sn.Pressed=2]="Pressed",sn[sn.Disabled=3]="Disabled";const nn=U("Button",{state:exports.ButtonState.Normal,transition:null});class rn{constructor(){this.events_=[]}emit(e,t,s){const n=s??e;this.events_.push({entity:e,type:t,target:n,currentTarget:e})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const on=fe(new rn,"UIEvents"),an=$("ScreenSpace");function ln(e,t,s,n,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,d=o.bottom+e.y*a,u=o.bottom+t.y*a;let h,p,f,g;if(e.x===t.x){const e=l+s.x,t=.5*r.x;h=e-t,f=e+t}else h=l+s.x,f=c+n.x;if(e.y===t.y){const e=d+s.y,t=.5*r.y;p=e-t,g=e+t}else p=d+s.y,g=u+n.y;return{centerX:.5*(h+f),centerY:.5*(p+g),width:f-h,height:g-p,rect:{left:h,bottom:p,right:f,top:g}}}function cn(e){return{anchorMinX:e.anchorMin.x,anchorMinY:e.anchorMin.y,anchorMaxX:e.anchorMax.x,anchorMaxY:e.anchorMax.y,offsetMinX:e.offsetMin.x,offsetMinY:e.offsetMin.y,offsetMaxX:e.offsetMax.x,offsetMaxY:e.offsetMax.y,sizeX:e.size.x,sizeY:e.size.y}}function dn(e,t){return e.anchorMinX!==t.anchorMin.x||e.anchorMinY!==t.anchorMin.y||e.anchorMaxX!==t.anchorMax.x||e.anchorMaxY!==t.anchorMax.y||e.offsetMinX!==t.offsetMin.x||e.offsetMinY!==t.offsetMin.y||e.offsetMaxX!==t.offsetMax.x||e.offsetMaxY!==t.offsetMax.y||e.sizeX!==t.size.x||e.sizeY!==t.size.y}function un(e,t){let s=t;for(;;){if(e.has(s,an))return s;if(!e.has(s,se))return null;const t=e.get(s,se);if(!e.valid(t.entity))return null;s=t.entity}}function hn(e,t,s,n,r,o){if(!e.has(t,Us))return;const i=e.get(t,Us),a=ln(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,s);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,J);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-n,l.position.y=a.centerY-r),e.insert(t,J,l),!e.has(t,ne))return;const c=e.get(t,ne);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&hn(e,t,a.rect,a.centerX,a.centerY,!1)}class pn{build(e){X("UIRect",Us);const t=e.world,s=new Map;let n=NaN,r=NaN,o=NaN,i=NaN;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([ge(Oe)],e=>{if(!e.valid)return;const a={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},l=.5*(a.left+a.right),c=.5*(a.bottom+a.top),d=n!==e.worldLeft||r!==e.worldBottom||o!==e.worldRight||i!==e.worldTop;n=e.worldLeft,r=e.worldBottom,o=e.worldRight,i=e.worldTop;const u=new Set;if(d){const e=t.getEntitiesWithComponents([an,Us,J]);for(const t of e)u.add(t)}const h=t.getEntitiesWithComponents([Us]);for(const e of h){const n=t.get(e,Us),r=s.get(e);if(!r||dn(r,n)){const s=un(t,e);null!==s&&u.add(s)}}for(const e of s.keys())if(!t.valid(e)||!t.has(e,Us)){s.delete(e);const n=un(t,e);null!==n&&u.add(n)}for(const e of u)hn(t,e,a,l,c,!0);for(const e of h){const n=t.get(e,Us);s.set(e,cn(n))}},{name:"UILayoutSystem"}))}}const fn=new pn,gn=new Float32Array(16),mn=new Float32Array(16);let yn=!0,xn=1;function _n(e,t,s,n){t.emit(s,n,s);let r=s;for(;e.has(r,se);){const o=e.get(r,se).entity;if(!e.valid(o))break;if(!e.has(o,en)){r=o;continue}const i=e.get(o,en);if(i.enabled&&t.emit(o,n,s),i.blockRaycast)break;r=o}}class wn{build(e){X("Interactable",en),X("Button",nn);const t=e.world,s=new rn;e.insertResource(on,s);let n=null,r=null;xn="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([ge(Re),ge(Oe)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([tn]);for(const e of i){const s=t.get(e,tn);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a=e.mouseX*xn,l=o.screenH-e.mouseY*xn;!function(e){let t=!1;for(let s=0;s<16;s++)if(mn[s]!==e[s]){t=!0;break}t&&(mn.set(e),yn=!0)}(o.viewProjection),yn&&(Ys(o.viewProjection,gn),yn=!1);const c=Gs(a,l,gn,o.vpX,o.vpY,o.vpW,o.vpH),d=t.getEntitiesWithComponents([en,Us,K]);let u=null,h=-1/0;for(const e of d){t.has(e,tn)||t.insert(e,tn);if(!t.get(e,en).enabled)continue;const s=t.get(e,K),n=t.get(e,Us),r=n.size.x*s.scale.x,o=n.size.y*s.scale.y;if(qs(c.x,c.y,s.position.x,s.position.y,r,o,n.pivot.x,n.pivot.y,s.rotation.z,s.rotation.w)){let s=0;t.has(e,Q)&&(s=t.get(e,Q).layer),s>=h&&(h=s,u=e)}}if(n!==u){if(null!==n&&t.valid(n)&&t.has(n,tn)){t.get(n,tn).hovered=!1,s.emit(n,"hover_exit")}if(null!==u){t.get(u,tn).hovered=!0,s.emit(u,"hover_enter")}n=u}if(e.isMouseButtonPressed(0)&&null!==u){const e=t.get(u,tn);e.pressed=!0,e.justPressed=!0,r=u,_n(t,s,u,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,tn)){const e=t.get(r,tn);e.pressed=!1,e.justReleased=!0,_n(t,s,r,"release"),r===n&&_n(t,s,r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(exports.Schedule.Update,Me([],()=>{const e=t.getEntitiesWithComponents([nn]);for(const s of e){if(t.has(s,en)||t.insert(s,en,{enabled:!0}),!t.has(s,tn))continue;const e=t.get(s,tn),n=t.get(s,nn),r=t.get(s,en),o=n.state;if(r.enabled?e.pressed?n.state=exports.ButtonState.Pressed:e.hovered?n.state=exports.ButtonState.Hovered:n.state=exports.ButtonState.Normal:n.state=exports.ButtonState.Disabled,o!==n.state&&n.transition&&t.has(s,Q)){const e=t.get(s,Q),r=n.transition;switch(n.state){case exports.ButtonState.Normal:e.color={...r.normalColor};break;case exports.ButtonState.Hovered:e.color={...r.hoveredColor};break;case exports.ButtonState.Pressed:e.color={...r.pressedColor};break;case exports.ButtonState.Disabled:e.color={...r.disabledColor}}t.insert(s,Q,e)}}},{name:"ButtonSystem"}))}}const vn=new wn,bn=U("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class Sn{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){X("TextInput",bn);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=i(I.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let a=null,l=!1,c=!0,d=0,u=0;const h=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!h)return;const p=h,f=()=>{l||null===a||_()},g=()=>{l=!0},m=()=>{l=!1,_()},y=t=>{if(null===a)return;if("Escape"===t.key)return void v();const n=s.get(a,bn);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(on).emit(a,"submit"),void v()}let r=n.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,n.cursorPos-1):"ArrowRight"===t.key?r=Math.min(n.value.length,n.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=n.value.length),r!==n.cursorPos&&(n.cursorPos=r,p.selectionStart=r,p.selectionEnd=r,n.dirty=!0,b())},x=()=>{if(null!==a&&s.valid(a)&&s.has(a,bn)){const e=s.get(a,bn);e.focused=!1,e.dirty=!0}a=null};function _(){if(null===a||!s.valid(a))return;const t=s.get(a,bn);if(t.readOnly)return;let n=p.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),p.value=n),n!==t.value){t.value=n;e.getResource(on).emit(a,"change")}t.cursorPos=p.selectionStart??n.length,t.dirty=!0,b()}function w(e){if(a===e)return;v();const t=s.get(e,bn);t.readOnly||(a=e,t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),b())}function v(){if(null!==a&&s.valid(a)&&s.has(a,bn)){const e=s.get(a,bn);e.focused=!1,e.dirty=!0}a=null,p.blur()}function b(){c=!0,d=0}function S(e,i,a,l){(r.width<a||r.height<l)&&(r.width=Tn(Math.max(r.width,a)),r.height=Tn(Math.max(r.height,l))),o.clearRect(0,0,r.width,r.height);const d=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*d.r)}, ${Math.round(255*d.g)}, ${Math.round(255*d.b)}, ${d.a})`,o.fillRect(0,0,a,l),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,l),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const u=0===i.value.length,h=u?i.placeholder:i.password?"●".repeat(i.value.length):i.value,p=u?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*p.r)}, ${Math.round(255*p.g)}, ${Math.round(255*p.b)}, ${p.a})`;const f=Math.ceil(1.2*i.fontSize),g=i.padding;if(i.multiline){const e=Pn(o,h,a-2*g);let t=g;for(const s of e)o.fillText(s,g,t),t+=f}else{const e=(l-i.fontSize)/2;o.fillText(h,g,e)}if(i.focused&&c){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,s,n;if(i.multiline){const e=Pn(o,i.value.substring(0,i.cursorPos),a-2*g),r=e.length>0?e[e.length-1]:"";t=g+o.measureText(r).width,s=g+(e.length-1)*f,n=f}else t=g+o.measureText(e).width,s=(l-i.fontSize)/2,n=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,s,2,n)}o.restore();const m=o.getImageData(0,0,a,l),y=new Uint8Array(m.data.buffer),x=t.getResourceManager(),_=t._malloc(y.length);t.HEAPU8.set(y,_);const w=n.get(e);void 0!==w&&x.releaseTexture(w);const v=x.createTexture(a,l,_,y.length,1,!0);n.set(e,v),t._free(_);const b=s.get(e,Q);b.texture=v,b.size.x=a,b.size.y=l,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},s.insert(e,Q,b)}p.addEventListener("input",f),p.addEventListener("compositionstart",g),p.addEventListener("compositionend",m),p.addEventListener("keydown",y),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",f),p.removeEventListener("compositionstart",g),p.removeEventListener("compositionend",m),p.removeEventListener("keydown",y),p.removeEventListener("blur",x),p.remove()},e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([ge(on)],e=>{const t=s.getEntitiesWithComponents([bn,en]);for(const e of t){if(!s.has(e,tn))continue;if(s.get(e,tn).justPressed)return void w(e)}if(null!==a){const e=s.getEntitiesWithComponents([en]);for(const t of e){if(s.has(t,bn))continue;if(!s.has(t,tn))continue;if(s.get(t,tn).justPressed)return void v()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==a&&(d+=r,d>=.5&&(d-=.5,c=!c,null!==a&&s.valid(a)&&s.has(a,bn)))){s.get(a,bn).dirty=!0}const o=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,bn)||(o.releaseTexture(t),n.delete(e));const i=s.getEntitiesWithComponents([bn,Us]);for(const e of i){const t=s.get(e,bn);if(!t.dirty)continue;const n=s.get(e,Us),r=Math.ceil(n.size.x),o=Math.ceil(n.size.y);r<=0||o<=0||(s.has(e,Q)||s.insert(e,Q,{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),S(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Pn(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const o of t){const t=n+o;e.measureText(t).width>s&&n?(r.push(n),n=o):n=t}n&&r.push(n)}return r.length>0?r:[""]}function Tn(e){let t=1;for(;t<e;)t*=2;return t}const Mn=new Sn,En={Simple:0,Sliced:1,Tiled:2,Filled:3},Cn={Horizontal:0,Vertical:1},An={Left:0,Right:1,Bottom:2,Top:3},Rn=U("Image",{texture:F,color:{r:1,g:1,b:1,a:1},imageType:En.Simple,fillMethod:Cn.Horizontal,fillOrigin:An.Left,fillAmount:1,preserveAspect:!1,layer:0,material:0});const In=new class{build(e){X("Image",Rn);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([],()=>{const e=t.getEntitiesWithComponents([Rn]);for(const s of e){const e=t.get(s,Rn);t.has(s,Q)||t.insert(s,Q,{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const n=t.get(s,Q);if(n.texture=e.texture,n.color.r=e.color.r,n.color.g=e.color.g,n.color.b=e.color.b,n.color.a=e.color.a,n.layer=e.layer,n.material=e.material,t.has(s,Us)){const e=t.get(s,Us);n.size.x=e.size.x,n.size.y=e.size.y}if(n.uvOffset.x=0,n.uvOffset.y=0,n.uvScale.x=1,n.uvScale.y=1,e.imageType===En.Filled){const t=Math.max(0,Math.min(1,e.fillAmount));e.fillMethod===Cn.Horizontal?e.fillOrigin===An.Left?(n.uvScale.x=t,n.size.x*=t):(n.uvOffset.x=1-t,n.uvScale.x=t,n.size.x*=t):e.fillOrigin===An.Bottom?(n.uvScale.y=t,n.size.y*=t):(n.uvOffset.y=1-t,n.uvScale.y=t,n.size.y*=t)}t.insert(s,Q,n)}},{name:"ImageSystem"}))}},Fn=U("Toggle",{isOn:!0,graphicEntity:0,transition:null});const Bn=new class{build(e){X("Toggle",Fn);const t=e.world;e.addSystemToSchedule(exports.Schedule.Update,Me([ge(on)],e=>{const s=t.getEntitiesWithComponents([Fn]);for(const n of s){if(t.has(n,en)||t.insert(n,en,{enabled:!0}),!t.has(n,tn))continue;const s=t.get(n,tn),r=t.get(n,Fn),o=t.get(n,en);if(s.justPressed&&o.enabled&&(r.isOn=!r.isOn,e.emit(n,"change")),r.graphicEntity&&t.valid(r.graphicEntity)){const e=r.graphicEntity;if(t.has(e,Q)){const s=t.get(e,Q);s.color.a=r.isOn?1:0,t.insert(e,Q,s)}}if(r.transition&&t.has(n,Q)){const e=t.get(n,Q),i=r.transition;o.enabled?s.pressed?e.color={...i.pressedColor}:s.hovered?e.color={...i.hoveredColor}:e.color={...i.normalColor}:e.color={...i.disabledColor},t.insert(n,Q,e)}}},{name:"ToggleSystem"}))}};var Dn;exports.ProgressBarDirection=void 0,(Dn=exports.ProgressBarDirection||(exports.ProgressBarDirection={}))[Dn.LeftToRight=0]="LeftToRight",Dn[Dn.RightToLeft=1]="RightToLeft",Dn[Dn.BottomToTop=2]="BottomToTop",Dn[Dn.TopToBottom=3]="TopToBottom";const kn=U("ProgressBar",{value:0,fillEntity:0,direction:exports.ProgressBarDirection.LeftToRight});const Ln=new class{build(e){X("ProgressBar",kn);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([],()=>{const e=t.getEntitiesWithComponents([kn,Us]);for(const s of e){const e=t.get(s,kn);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=e.fillEntity;if(!t.has(n,Us))continue;const r=t.get(n,Us),o=Math.max(0,Math.min(1,e.value));switch(e.direction){case exports.ProgressBarDirection.LeftToRight:r.anchorMin={x:0,y:0},r.anchorMax={x:o,y:1};break;case exports.ProgressBarDirection.RightToLeft:r.anchorMin={x:1-o,y:0},r.anchorMax={x:1,y:1};break;case exports.ProgressBarDirection.BottomToTop:r.anchorMin={x:0,y:0},r.anchorMax={x:1,y:o};break;case exports.ProgressBarDirection.TopToBottom:r.anchorMin={x:0,y:1-o},r.anchorMax={x:1,y:1}}r.offsetMin={x:0,y:0},r.offsetMax={x:0,y:0},t.insert(n,Us,r)}},{name:"ProgressBarSystem"}))}},Wn=U("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Un=U("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}}),$n=new Float32Array(16),zn=new Float32Array(16);let On=!0;function Hn(e,t,s){const n=e.mouseX*s,r=t.screenH-e.mouseY*s;return function(e){let t=!1;for(let s=0;s<16;s++)if(zn[s]!==e[s]){t=!0;break}t&&(zn.set(e),On=!0)}(t.viewProjection),On&&(Ys(t.viewProjection,$n),On=!1),Gs(n,r,$n,t.vpX,t.vpY,t.vpW,t.vpH)}const jn=new class{build(e){X("Draggable",Wn),X("DragState",Un);const t=e.world,s=e.getResource(on);let n=null,r={x:0,y:0},o=null;const i="undefined"!=typeof window&&window.devicePixelRatio||1;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([ge(Re),ge(Oe)],(e,a)=>{if(!a.valid)return;const l=Hn(e,a,i);if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Wn,tn]);let s=null;for(const n of e){if(!t.get(n,Wn).enabled)continue;t.get(n,tn).hovered&&(s=n)}if(null!==s){n=s,r={x:l.x,y:l.y},t.has(s,Un)||t.insert(s,Un);const e=t.get(s,Un),o=t.get(s,K);e.startWorldPos={x:o.position.x,y:o.position.y},e.currentWorldPos={x:o.position.x,y:o.position.y},e.pointerStartWorld={x:l.x,y:l.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==n&&!e.isMouseButtonDown(0)){if(t.valid(n)&&t.has(n,Un)){t.get(n,Un).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=l.x-r.x,i=l.y-r.y,c=Math.sqrt(e*e+i*i),d=t.get(n,Wn);if(c*(a.vpW/(a.worldRight-a.worldLeft))>=d.dragThreshold){o=n,n=null;t.get(o,Un).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Un))return void(o=null);const n=t.get(o,Un),r=t.get(o,Wn),i=l.x-n.pointerStartWorld.x,a=l.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+i,d=n.startWorldPos.y+a;const u=function(e,t,s,n){let r=e.lockX?t.startWorldPos.x:s,o=e.lockY?t.startWorldPos.y:n;return null!==e.constraintMin&&(r=Math.max(r,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(r=Math.min(r,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:r,y:o}}(r,n,c,d);c=u.x,d=u.y;const h=n.currentWorldPos.x,p=n.currentWorldPos.y;if(n.deltaWorld={x:c-h,y:d-p},n.currentWorldPos={x:c,y:d},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:d-n.startWorldPos.y},t.has(o,J)){const e=function(e,t,s,n){if(!e.has(t,se))return{x:s,y:n};const r=e.get(t,se).entity;if(!e.valid(r)||!e.has(r,K))return{x:s,y:n};const o=e.get(r,K),i=0!==o.scale.x?o.scale.x:1,a=0!==o.scale.y?o.scale.y:1,l=2*Math.atan2(o.rotation.z,o.rotation.w),c=Math.sin(-l),d=Math.cos(-l);return{x:(s*d-n*c)/i,y:(s*c+n*d)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,J);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,J,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},Xn=U("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135});const Nn=new class{build(e){X("ScrollView",Xn);const t=e.world,s=new Map,n=new Float32Array(16),r="undefined"!=typeof window&&window.devicePixelRatio||1;let o=0;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([ge(Re),ge(Oe)],(e,i)=>{const a=performance.now()/1e3,l=o>0?Math.min(a-o,.05):0;if(o=a,!i.valid)return;const c=e.mouseX*r,d=i.screenH-e.mouseY*r;Ys(i.viewProjection,n);const u=Gs(c,d,n,i.vpX,i.vpY,i.vpW,i.vpH),h=t.getEntitiesWithComponents([Xn,Us]);for(const n of h){t.has(n,en)||t.insert(n,en,{enabled:!0,blockRaycast:!0}),t.has(n,Xs)||t.insert(n,Xs,{enabled:!0,mode:"scissor"});const r=t.get(n,Xn),o=t.get(n,Us);let i=s.get(n);i||(i={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0},s.set(n,i));const a=t.has(n,tn)?t.get(n,tn):null;if(a?.justPressed&&(i.isDragging=!0,i.lastWorldX=u.x,i.lastWorldY=u.y,i.velocityX=0,i.velocityY=0),i.isDragging&&e.isMouseButtonDown(0)){const e=u.x-i.lastWorldX,t=u.y-i.lastWorldY;r.horizontalEnabled&&(r.scrollX-=e,i.velocityX=l>0?-e/l:0),r.verticalEnabled&&(r.scrollY-=t,i.velocityY=l>0?-t/l:0),i.lastWorldX=u.x,i.lastWorldY=u.y}if(i.isDragging&&e.isMouseButtonReleased(0)&&(i.isDragging=!1),a?.hovered){const t=e.getScrollDelta();r.verticalEnabled&&0!==t.y&&(r.scrollY+=.1*t.y,i.velocityY=0),r.horizontalEnabled&&0!==t.x&&(r.scrollX+=.1*t.x,i.velocityX=0)}if(!i.isDragging&&r.inertia&&l>0){const e=Math.pow(r.decelerationRate,l);r.horizontalEnabled&&Math.abs(i.velocityX)>.1?(r.scrollX+=i.velocityX*l,i.velocityX*=e):i.velocityX=0,r.verticalEnabled&&Math.abs(i.velocityY)>.1?(r.scrollY+=i.velocityY*l,i.velocityY*=e):i.velocityY=0}const c=o.size.x,d=o.size.y,h=Math.max(0,r.contentWidth-c),p=Math.max(0,r.contentHeight-d);if(r.scrollX=Math.max(0,Math.min(r.scrollX,h)),r.scrollY=Math.max(0,Math.min(r.scrollY,p)),0!==r.contentEntity&&t.valid(r.contentEntity)){const e=r.contentEntity;if(t.has(e,J)){const s=t.get(e,J);s.position.x=-r.scrollX,s.position.y=r.scrollY,t.insert(e,J,s)}}}},{name:"ScrollViewSystem"}))}};var Vn;exports.SliderDirection=void 0,(Vn=exports.SliderDirection||(exports.SliderDirection={}))[Vn.LeftToRight=0]="LeftToRight",Vn[Vn.RightToLeft=1]="RightToLeft",Vn[Vn.BottomToTop=2]="BottomToTop",Vn[Vn.TopToBottom=3]="TopToBottom";const Yn=U("Slider",{value:0,minValue:0,maxValue:1,direction:exports.SliderDirection.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});const Gn=new class{build(e){X("Slider",Yn);const t=e.world,s=new Float32Array(16),n="undefined"!=typeof window&&window.devicePixelRatio||1;let r=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([ge(Re),ge(Oe)],(e,o)=>{if(!o.valid)return;const i=e.mouseX*n,a=o.screenH-e.mouseY*n;Ys(o.viewProjection,s);const l=Gs(i,a,s,o.vpX,o.vpY,o.vpW,o.vpH),c=t.getEntitiesWithComponents([Yn,Us,K]);for(const s of c){t.has(s,en)||t.insert(s,en,{enabled:!0,blockRaycast:!0});const n=t.get(s,Yn),o=t.get(s,Us),i=t.get(s,K),a=t.has(s,tn)?t.get(s,tn):null;if(a?.justPressed&&(r=s),r===s&&e.isMouseButtonDown(0)){const e=o.size.x*i.scale.x,t=o.size.y*i.scale.y,s=i.position.x-o.pivot.x*e,r=i.position.y-o.pivot.y*t;let a;switch(n.direction){case exports.SliderDirection.LeftToRight:a=e>0?(l.x-s)/e:0;break;case exports.SliderDirection.RightToLeft:a=e>0?1-(l.x-s)/e:0;break;case exports.SliderDirection.BottomToTop:a=t>0?(l.y-r)/t:0;break;case exports.SliderDirection.TopToBottom:a=t>0?1-(l.y-r)/t:0}a=Math.max(0,Math.min(1,a));let c=n.minValue+a*(n.maxValue-n.minValue);n.wholeNumbers&&(c=Math.round(c)),n.value=Math.max(n.minValue,Math.min(n.maxValue,c))}r===s&&e.isMouseButtonReleased(0)&&(r=null);const c=n.maxValue-n.minValue,d=c>0?(n.value-n.minValue)/c:0;if(0!==n.fillEntity&&t.valid(n.fillEntity)){const e=n.fillEntity;if(t.has(e,Us)){const s=t.get(e,Us);switch(n.direction){case exports.SliderDirection.LeftToRight:s.anchorMin={x:0,y:0},s.anchorMax={x:d,y:1};break;case exports.SliderDirection.RightToLeft:s.anchorMin={x:1-d,y:0},s.anchorMax={x:1,y:1};break;case exports.SliderDirection.BottomToTop:s.anchorMin={x:0,y:0},s.anchorMax={x:1,y:d};break;case exports.SliderDirection.TopToBottom:s.anchorMin={x:0,y:1-d},s.anchorMax={x:1,y:1}}t.insert(e,Us,s)}}if(0!==n.handleEntity&&t.valid(n.handleEntity)){const e=n.handleEntity;if(t.has(e,Us)){const s=t.get(e,Us);switch(n.direction){case exports.SliderDirection.LeftToRight:s.anchorMin={x:d,y:0},s.anchorMax={x:d,y:1};break;case exports.SliderDirection.RightToLeft:s.anchorMin={x:1-d,y:0},s.anchorMax={x:1-d,y:1};break;case exports.SliderDirection.BottomToTop:s.anchorMin={x:0,y:d},s.anchorMax={x:1,y:d};break;case exports.SliderDirection.TopToBottom:s.anchorMin={x:0,y:1-d},s.anchorMax={x:1,y:1-d}}t.insert(e,Us,s)}}}},{name:"SliderSystem"}))}},qn=U("Focusable",{tabIndex:0,isFocused:!1});class Jn{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Kn=fe(new Jn,"FocusManager");const Qn=new class{build(e){X("Focusable",qn);const t=e.world,s=new Jn;e.insertResource(Kn,s),e.addSystemToSchedule(exports.Schedule.Update,Me([ge(Re),ge(on)],(e,n)=>{const r=t.getEntitiesWithComponents([qn]);for(const e of r){if(!t.has(e,tn))continue;t.get(e,tn).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const n=function(){const e=[];for(const s of r){const n=t.get(s,qn);e.push({entity:s,tabIndex:n.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===n.length)return;const i=null!==s.focusedEntity?n.findIndex(e=>e===s.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===i?a?n.length-1:0:a?(i-1+n.length)%n.length:(i+1)%n.length,o(n[l])}function o(e){const r=s.focusedEntity;if(r===e)return;if(null!==r&&t.valid(r)&&t.has(r,qn)){t.get(r,qn).isFocused=!1,n.emit(r,"hover_exit",r)}s.focus(e);t.get(e,qn).isFocused=!0,n.emit(e,"hover_enter",e)}},{name:"FocusSystem"}))}},Zn=U("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});const er=new class{build(e){X("SafeArea",Zn);const t=e.world;let s={top:0,bottom:0,left:0,right:0},n=0;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([],()=>{n++%60==0&&(s=function(){if("undefined"==typeof document)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}());const e=t.getEntitiesWithComponents([Zn,Us]);for(const n of e){const e=t.get(n,Zn),r=t.get(n,Us);let o=!1;const i=e.applyTop?s.top:0,a=e.applyBottom?s.bottom:0,l=e.applyLeft?s.left:0,c=e.applyRight?s.right:0;r.offsetMin.x===l&&r.offsetMin.y===a||(r.offsetMin={x:l,y:a},o=!0),r.offsetMax.x===-c&&r.offsetMax.y===-i||(r.offsetMax={x:-c,y:-i},o=!0),o&&t.insert(n,Us,r)}},{name:"SafeAreaSystem"}))}},tr=U("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2}),sr=new Map;const nr=new class{build(e){X("ListView",tr);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([ge(Re)],e=>{const s=t.getEntitiesWithComponents([tr,Us]);for(const n of s){t.has(n,en)||t.insert(n,en,{enabled:!0,blockRaycast:!0}),t.has(n,Xs)||t.insert(n,Xs,{enabled:!0,mode:"scissor"});let s=sr.get(n);s||(s={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},sr.set(n,s));const r=t.get(n,tr),o=t.get(n,Us),i=o.size.y,a=t.has(n,tn)?t.get(n,tn):null;if(a?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}const l=Math.max(0,r.itemCount*r.itemHeight-i);r.scrollY=Math.max(0,Math.min(r.scrollY,l));const c=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),d=Math.min(r.itemCount,Math.ceil((r.scrollY+i)/r.itemHeight)+r.overscan);for(const[e,n]of s.itemEntities)(e<c||e>=d)&&(t.valid(n)&&t.despawn(n),s.itemEntities.delete(e));for(let e=c;e<d;e++){let i=s.itemEntities.get(e);if(i&&t.valid(i)||(i=t.spawn(),t.insert(i,ie,{value:`ListItem_${e}`}),t.insert(i,Us,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o.size.x,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(i,n),s.itemEntities.set(e,i),s.renderer&&s.renderer(e,i)),t.has(i,J)){const s=t.get(i,J);s.position.y=-(e*r.itemHeight-r.scrollY),t.insert(i,J,s)}}s.visibleStart=c,s.visibleEnd=d}},{name:"ListViewSystem"}))}},rr=U("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const or=new class{build(e){X("Dropdown",rr);const t=e.world;e.addSystemToSchedule(exports.Schedule.Update,Me([ge(Re),ge(on)],(e,s)=>{const n=t.getEntitiesWithComponents([rr]);for(const o of n){t.has(o,en)||t.insert(o,en,{enabled:!0,blockRaycast:!0});const n=t.get(o,rr),i=t.has(o,tn)?t.get(o,tn):null;if(i?.justPressed&&(n.isOpen=!n.isOpen,r(n.listEntity,n.isOpen),s.emit(o,"change",o)),n.isOpen&&e.isMouseButtonPressed(0)&&!i?.hovered){0!==n.listEntity&&t.valid(n.listEntity)&&t.has(n.listEntity,tn)&&t.get(n.listEntity,tn).hovered||(n.isOpen=!1,r(n.listEntity,!1))}}function r(e,s){if(0===e)return;const n=e;if(!t.valid(n)||!t.has(n,J))return;const r=t.get(n,J),o=s?1:0;r.scale={x:o,y:o,z:o},t.insert(n,J,r)}},{name:"DropdownSystem"}))}};async function ir(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const ar=fe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),lr=fe(null,"PhysicsAPI");function cr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function dr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class ur{constructor(e,t={},s){this.wasmUrl_=e,this.factory_=s,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(ar,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=ir(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([ee]);for(const s of t){const t=e.world.get(s,ee);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,Me([ge(_e)],a=>{const l=i.getEntitiesWithComponents([le,J,K]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,le),l=i.get(r,K);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=cr(l.rotation);n._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),hr(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===he.Kinematic){const e=cr(l.rotation);n._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<n;r++){const n=o+4*r,i=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const d=e.world.get(i,J);if(!d)continue;let u=a,h=l,p=c;if(e.world.has(i,se)){const t=e.world.get(i,se);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,K)){const s=e.world.get(t.entity,K),n=cr(s.rotation),r=a-s.position.x,o=l-s.position.y,i=Math.cos(-n),d=Math.sin(-n);u=(r*i-o*d)/(0!==s.scale.x?s.scale.x:1),h=(r*d+o*i)/(0!==s.scale.y?s.scale.y:1),p=c-n}}d.position.x=u,d.position.y=h;const f=dr(p);d.rotation.w=f.w,d.rotation.x=f.x,d.rotation.y=f.y,d.rotation.z=f.z,e.world.insert(i,J,d)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<i;s++){const n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],d=t._physics_getSensorExitCount();if(d>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<d;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(ar,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(lr,pr._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function hr(e,t,s){const n=e.world;if(n.has(s,ce)){const e=n.get(s,ce);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,de)){const e=n.get(s,de);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,ue)){const e=n.get(s,ue);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class pr{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(pr.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function fr(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),o}function gr(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function mr(e,t,s,n){const r=e.scale.x*t*(s?-1:1),o=e.scale.y*t*(n?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,d=e.rotation.w,u=a+a,h=l+l,p=c+c,f=a*u,g=a*h,m=a*p,y=l*h,x=l*p,_=c*p,w=d*u,v=d*h,b=d*p;return new Float32Array([(1-(y+_))*r,(g+b)*r,(m-v)*r,0,(g-b)*o,(1-(f+_))*o,(x+w)*o,0,(m+v)*i,(x-w)*i,(1-(f+y))*i,0,e.position.x,e.position.y,e.position.z,1])}async function yr(e,t,s,n,r,o,i,a,l){const c=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==n[r])continue;try{n[r]=fr(e,await s.loadPixels(r))}catch{n[r]=0}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,c);let d={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),d=await async function(e,t,s,n,r){const o={};for(const i of n.entities)for(const n of i.components){if("SpineAnimation"!==n.type||!n.data)continue;const i=n.data.skeletonPath,a=n.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const n=await r.readText(a),d="binary"===g(l)?.contentType;let u,h;if(d){const e=await r.readBinary(i);h=e.length,u=t._malloc(h),t.HEAPU8.set(e,u)}else{const e=await r.readText(i),s=(new TextEncoder).encode(e);h=s.length,u=t._malloc(h+1),t.HEAPU8.set(s,u),t.HEAPU8[u+h]=0}const p=s.loadSkeleton(u,h,n,n.length,d);if(t._free(u),p<0)continue;o[i]=p;const f=gr(n),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=m+"/"+f[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),i=fr(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,s,n)),o){new ur("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const h=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,o;const i=g(r);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await s.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await s.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(r),o=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const l=o?`${o}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),d=fr(e,c,!1),u=e.getResourceManager();n[r]=u.loadBitmapFont(t,d,c.width,c.height)}catch{n[r]=0}}return n}(t,s,n),p=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=n[o];i||(i=Ke.createShader(e.vertexSource,e.fragmentSource),n[o]=i),s[r]=Ke.createFromAsset(e,i)}catch{s[r]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=ct(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,c,h,p);const f=dt(e.world,s);if(l&&e.hasResource(xs))for(const t of f.values())e.world.insert(t,ae,{scene:l,persistent:!1});if(r&&u){const n=function(e,t,s,n){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=s[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=n.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,s,d,f);!function(e,t,s,n,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,oe)?c.get(o,oe):null,d=!1!==a?.playing,u=a?.timeScale??1;d&&n.update(i,l*u);let h=0;if(c.has(o,K)){const e=mr(c.get(o,K),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=n.getMeshBatchCount(i);for(let e=0;e<p;e++){const r=n.getMeshBatchVertexCount(i,e),o=n.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=s._malloc(a),d=s._malloc(l),u=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(i,e,c,d,u,p);const f=s.HEAPU32[u>>2],g=s.HEAPU32[p>>2],m=new Float32Array(s.HEAPF32.buffer,c,8*r),y=new Uint16Array(s.HEAPU8.buffer,d,o),x=t._malloc(a),_=t._malloc(l);t.HEAPF32.set(m,x>>2),new Uint16Array(t.HEAPU8.buffer,_,o).set(y),t.renderer_submitTriangles(x,r,_,o,f,g,h),t._free(x),t._free(_),s._free(c),s._free(d),s._free(u),s._free(p)}h&&t._free(h)}})}(e,t,r,u,n)}if(a){const t=e.getResource(ft);t&&t.setAddressableManifest(a)}}class xr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,r=e.data.atlasPath;n&&("binary"===g(n)?.contentType?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of n){const t=g(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||o.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const _r="__preview__";const wr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=ls.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:ls.getTargetTexture(s),width:e.width,height:e.height}},release(e){ls.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(ls.releaseRenderTarget(e._handle),wr.create({width:t,height:s,depth:!0})),begin(e,t){ls.begin(t,e._handle)},end(){ls.end()},getDepthTexture:e=>ls.getTargetDepthTexture(e._handle)};let vr=!1;var br;exports.LogLevel=void 0,(br=exports.LogLevel||(exports.LogLevel={}))[br.Debug=0]="Debug",br[br.Info=1]="Info",br[br.Warn=2]="Warn",br[br.Error=3]="Error";class Sr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${exports.LogLevel[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case exports.LogLevel.Debug:console.debug(t,s);break;case exports.LogLevel.Info:console.log(t,s);break;case exports.LogLevel.Warn:console.warn(t,s);break;case exports.LogLevel.Error:console.error(t,s)}}}class Pr{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new Sr)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,s){this.log(exports.LogLevel.Debug,e,t,s)}info(e,t,s){this.log(exports.LogLevel.Info,e,t,s)}warn(e,t,s){this.log(exports.LogLevel.Warn,e,t,s)}error(e,t,s){this.log(exports.LogLevel.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Tr=new Pr;const Mr=[js,Zs,fn,In,Ln,vn,jn,Nn,Gn,Bn,Mn,Qn,er,nr,or];E||(E=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await l(s,n);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return c(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?s[n++]=r:r<2048?(s[n++]=192|r>>6,s[n++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,s[n++]=240|r>>18,s[n++]=128|r>>12&63,s[n++]=128|r>>6&63,s[n++]=128|63&r):(s[n++]=224|r>>12,s[n++]=128|r>>6&63,s[n++]=128|63&r)}return s.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=C,exports.App=bs,exports.AssetPlugin=gt,exports.AssetRefCounter=class{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let s=this.textureRefs_.get(e);s||(s=new Set,this.textureRefs_.set(e,s)),s.add(t)}removeTextureRef(e,t){const s=this.textureRefs_.get(e);s&&(s.delete(t),0===s.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let s=this.fontRefs_.get(e);s||(s=new Set,this.fontRefs_.set(e,s)),s.add(t)}removeFontRef(e,t){const s=this.fontRefs_.get(e);s&&(s.delete(t),0===s.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let s=this.materialRefs_.get(e);s||(s=new Set,this.materialRefs_.set(e,s)),s.add(t)}removeMaterialRef(e,t){const s=this.materialRefs_.get(e);s&&(s.delete(t),0===s.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,s]of this.textureRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllFontRefs(){const e=[];for(const[t,s]of this.fontRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllMaterialRefs(){const e=[];for(const[t,s]of this.materialRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}},exports.AssetServer=pt,exports.Assets=ft,exports.AsyncCache=it,exports.BitmapText=re,exports.BodyType=he,exports.BoxCollider=ce,exports.Button=nn,exports.Camera=Z,exports.Canvas=ee,exports.CapsuleCollider=ue,exports.Children=ne,exports.CircleCollider=de,exports.ClearFlags=G,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=Se,exports.DEFAULT_DESIGN_HEIGHT=R,exports.DEFAULT_DESIGN_WIDTH=A,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_TEXT_CANVAS_SIZE=512,exports.DragState=Un,exports.Draggable=Wn,exports.Draw=Dt,exports.Dropdown=rr,exports.EntityCommands=be,exports.FillMethod=Cn,exports.FillOrigin=An,exports.FocusManager=Kn,exports.FocusManagerState=Jn,exports.Focusable=qn,exports.GLDebug=hs,exports.Geometry=Jt,exports.INVALID_ENTITY=0,exports.INVALID_FONT=B,exports.INVALID_TEXTURE=F,exports.Image=Rn,exports.ImageType=En,exports.Input=Re,exports.InputPlugin=Ie,exports.InputState=Ae,exports.Interactable=en,exports.ListView=tr,exports.LocalTransform=J,exports.Logger=Pr,exports.Material=Ke,exports.MaterialLoader=at,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ie,exports.Parent=se,exports.Physics=pr,exports.PhysicsEvents=ar,exports.PhysicsPlugin=ur,exports.PostProcess=ts,exports.PrefabServer=vt,exports.Prefabs=bt,exports.PrefabsPlugin=St,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(xs);t.register({name:_r,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(_r),this.loadPromise_=t.load(_r).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await s(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new xr(this.baseUrl_);await n.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await yr(this.app_,this.app_.wasmModule,t,n,r,null,void 0,null,_r)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([Z]);for(const n of s){if(e.get(n,Z).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1.7777777777777777;const n=e.getEntitiesWithComponents([ee]);for(const r of n){const n=e.get(r,ee);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(xs).getScene(_r),o=r?r.spawn():e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(o,J,i);const a={isActive:!0,projectionType:Y.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:G.ColorAndDepth};e.insert(o,Z,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(xs);await e.switchTo(_r),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}},exports.ProgressBar=kn,exports.ProjectionType=Y,exports.Query=function(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{we(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)},exports.QueryInstance=ve,exports.RenderPipeline=ps,exports.RenderTexture=wr,exports.Renderer=ls,exports.Res=ge,exports.ResMut=me,exports.RigidBody=le,exports.RuntimeConfig=I,exports.SafeArea=Zn,exports.ScaleMode=q,exports.SceneManager=xs,exports.SceneManagerState=ys,exports.SceneOwner=ae,exports.ScreenSpace=an,exports.ScrollView=Xn,exports.ShaderSources=ot,exports.Slider=Yn,exports.SpineAnimation=oe,exports.Sprite=Q,exports.SystemRunner=Ce,exports.Text=Ws,exports.TextInput=bn,exports.TextInputPlugin=Sn,exports.TextPlugin=Hs,exports.TextRenderer=$s,exports.Time=_e,exports.Toggle=Fn,exports.UICameraInfo=Oe,exports.UIEventQueue=rn,exports.UIEvents=on,exports.UIInteraction=tn,exports.UIInteractionPlugin=wn,exports.UILayoutPlugin=pn,exports.UIMask=Xs,exports.UIMaskPlugin=Qs,exports.UIRect=Us,exports.Velocity=te,exports.WebAssetProvider=xr,exports.World=ze,exports.WorldTransform=K,exports.addStartupSystem=function(e){Ee().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){Ee().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){Ee().push({schedule:e,system:t})},exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=I.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=I.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=I.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=I.canvasMatchWidthOrHeight)},exports.assetPlugin=mt,exports.clearDrawCallbacks=Ot,exports.clearUserComponents=function(){W().clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeUIRectLayout=ln,exports.createMaskProcessor=Ks,exports.createRuntimeSceneConfig=function(e,t,s){return{name:e,data:t,async setup(){await yr(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}},exports.createWebApp=function(e,t){return function(e,t){const s=bs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Rt(e),Ge(e),Yt(e),Qt(e),is(e),ds(e);const r=new ps;s.setPipeline(r);let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function l(t,r,o){o||(o=Ts(e,n,t,r));const i=s.getResource(Oe);if(o.length>0){const e=o[0],s=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(s.x*t),i.vpY=Math.round((1-s.y-s.h)*r),i.vpW=Math.round(s.w*t),i.vpH=Math.round(s.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}s.insertResource(Oe,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();l(e,t)}},d={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=i();if(0===t||0===c)return;const d=e.registry_getCanvasEntity(n);if(d>=0){const e=n.getCanvas(d).backgroundColor;ls.setClearColor(e.x,e.y,e.z,e.w)}const u=(a()-o)/1e3;let h;if(ls.resize(t,c),ts.isInitialized()&&ts.getPassCount()>0&&!ts.isBypassed()&&ts.resize(t,c),s.hasResource(xs)){const e=s.getResource(xs).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const p=Ts(e,n,t,c,s.world,h);if(l(t,c,p),0===p.length)r.render({registry:{_cpp:n},viewProjection:Ss,width:t,height:c,elapsed:u});else{for(const e of p){const s=e.viewportRect,o=Math.round(s.x*t),i=Math.round((1-s.y-s.h)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:l},clearFlags:e.clearFlags,elapsed:u})}ls.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(exports.Schedule.First,c),s.addSystemToSchedule(exports.Schedule.Last,d),s.addPlugin(mt),s.addPlugin(Pt),s.addPlugin(Fe),s.addPlugin(vs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Mr,...t})},exports.debug=function(e,t,s){Tr.debug(e,t,s)},exports.defineComponent=U,exports.defineResource=fe,exports.defineSystem=Me,exports.defineTag=$,exports.error=function(e,t,s){Tr.error(e,t,s)},exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([ie]);for(const n of s){const s=e.get(n,ie);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}},exports.getAddressableType=function(e){return g(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of d)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return p},exports.getAssetMimeType=function(e){return u[e.toLowerCase()]},exports.getAssetTypeEntry=g,exports.getComponent=N,exports.getComponentAssetFields=function(e){const t=lt.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s},exports.getComponentDefaults=function(e){const t=N(e);return t?D(t._default):null},exports.getCustomExtensions=y,exports.getEditorType=function(e){return g(e)?.editorType??"unknown"},exports.getLogger=function(){return Tr},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=z,exports.getWeChatPackOptions=function(){return y().map(e=>({type:"suffix",value:e}))},exports.info=function(e,t,s){Tr.info(e,t,s)},exports.initDrawAPI=Rt,exports.initGLDebugAPI=ds,exports.initGeometryAPI=Yt,exports.initMaterialAPI=Ge,exports.initPostProcessAPI=Qt,exports.initRendererAPI=is,exports.inputPlugin=Fe,exports.instantiatePrefab=yt,exports.intersectRects=Ns,exports.invertMatrix4=Ys,exports.isBuiltinComponent=H,exports.isCustomExtension=x,exports.isEditor=function(){return vr},exports.isKnownAssetExtension=m,exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!vr},exports.isTextureRef=je,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=ht,exports.loadPhysicsModule=ir,exports.loadRuntimeScene=yr,exports.loadSceneData=dt,exports.loadSceneWithAssets=ut,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&m(f(e)))},exports.platformFetch=s,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,s){return t().instantiateWasm(e,s)},exports.platformReadFile=n,exports.platformReadTextFile=r,exports.pointInOBB=qs,exports.pointInWorldRect=function(e,t,s,n,r,o,i,a){return e>=s-r*i&&e<=s+r*(1-i)&&t>=n-o*a&&t<=n+o*(1-a)},exports.prefabsPlugin=Pt,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerComponent=X,exports.registerComponentAssetFields=function(e,t){lt.set(e,t)},exports.registerDrawCallback=$t,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(ft);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=rt,exports.sceneManagerPlugin=vs,exports.screenToWorld=Gs,exports.setEditorMode=function(e){vr=e},exports.setListViewRenderer=function(e,t){const s=sr.get(e);s&&(s.renderer=t)},exports.setLogLevel=function(e){Tr.setMinLevel(e)},exports.setWasmErrorHandler=We,exports.shutdownDrawAPI=It,exports.shutdownGLDebugAPI=us,exports.shutdownGeometryAPI=Gt,exports.shutdownMaterialAPI=qe,exports.shutdownPostProcessAPI=Zt,exports.shutdownRendererAPI=as,exports.textInputPlugin=Mn,exports.textPlugin=js,exports.transitionTo=async function(e,t,s){const n=e.getResource(xs);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=vn,exports.uiLayoutPlugin=fn,exports.uiMaskPlugin=Zs,exports.uiPlugins=Mr,exports.unregisterComponent=function(e){W().delete(e)},exports.unregisterDrawCallback=zt,exports.updateCameraAspectRatio=function(e,t){const s=e.getEntitiesWithComponents([Z]);for(const n of s){const s=e.get(n,Z);s&&(s.aspectRatio=t,e.insert(n,Z,s))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),exports.vec4=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),exports.warn=function(e,t,s){Tr.warn(e,t,s)},exports.worldRectToScreen=Vs,exports.wrapSceneSystem=_s,exports.wxFileExists=P,exports.wxFileExistsSync=function(e){const t=w();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=M,exports.wxLoadImage=T,exports.wxLoadImagePixels=async function(e){return M(await T(e))},exports.wxReadFile=b,exports.wxReadTextFile=S,exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{w().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};
+"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function s(e,s){return t().fetch(e,s)}async function n(e){return t().readFile(e)}async function r(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,s){return t().createCanvas(e,s)}function a(){return t().now()}function l(e,t){return new Promise((s,n)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function c(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const s=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(s,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${s}": ${t}`)}}const d=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],u={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},h=new Map,p=new Set;for(const e of d)for(const t of e.extensions)h.set(t,e),p.add(t);function f(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function g(e){return h.get(f(e))}function m(e){return p.has(e.toLowerCase())}function y(){const e=[];for(const t of d)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function x(e){const t=g(e);return t?.wechatPackInclude??!1}let _=null;function w(){return _||(_=wx.getFileSystemManager()),_}function v(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(x(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return s.includes("no such file")||s.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function b(e){return new Promise((t,s)=>{w().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(v(e,t.errMsg)))}})})}function S(e,t="utf-8"){return new Promise((s,n)=>{w().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(v(e,t.errMsg)))}})})}function P(e){return new Promise(t=>{w().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function T(e){return new Promise((t,s)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function M(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}let E=!1;const C=new class{constructor(){this.name="wechat"}async fetch(e,t){return l(e,t)}async readFile(e){return b(e)}async readTextFile(e){return S(e)}async fileExists(e){return P(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return c(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const s=wx.createCanvas();return s.width=e,s.height=t,s}now(){return Date.now()}bindInputEvents(e,t){const{pixelRatio:s}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX*s,n.clientY*s)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX*s,n.clientY*s)}),wx.onTouchEnd(t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)})}},A=1920,R=1080,I={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};const F=4294967295,B=4294967295;function D(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(D);const t={};for(const s in e)t[s]=D(e[s]);return t}let k=0;function L(e,t){const s=++k;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...D(t),...e}:D(t)}}function W(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function U(e,t){const s=W(),n=s.get(e);if(n)return n;const r=L(e,t);return s.set(e,r),O(e,t,!1),r}function $(e){const t=W(),s=t.get(e);if(s)return s;const n=L(e,{});return t.set(e,n),O(e,{},!0),n}function z(e){return W().get(e)}function O(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function H(e){return!0===e._builtin}const j=new Map;function X(e,t){j.set(e,t)}function N(e){return j.get(e)??z(e)}function V(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return j.set(e,s),s}const Y={Perspective:0,Orthographic:1},G={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},q={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},J=V("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),K=V("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Q=V("Sprite",{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),Z=V("Camera",{projectionType:Y.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:G.ColorAndDepth}),ee=V("Canvas",{designResolution:{x:A,y:R},pixelsPerUnit:100,scaleMode:q.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),te=V("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),se=V("Parent",{entity:0}),ne=V("Children",{entities:[]}),re=V("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:B,enabled:!0}),oe=V("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),ie={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},ae=U("SceneOwner",{scene:"",persistent:!1});X("Name",ie);const le=V("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ce=V("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),de=V("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ue=V("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),he={Static:0,Kinematic:1,Dynamic:2};let pe=0;function fe(e,t){const s=++pe;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function ge(e){return{_type:"res",_resource:e}}function me(e){return{_type:"res_mut",_resource:e}}class ye{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class xe{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new ye(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const _e=fe({delta:0,elapsed:0,frameCount:0},"Time");function we(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}class ve{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>we(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=s.length,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let d=null;this.world_.beginIteration();try{for(const u of n){if(null!==d&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(d,t.component,t.data)}if(i){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(u,t[s])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,s[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];d=u}yield a}}finally{if(this.world_.endIteration(),null!==d&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(d,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class be{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let s;return s=H(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Se{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new be(this,null);return this.spawned_.push(e),e}entity(e){return new be(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Pe;exports.Schedule=void 0,(Pe=exports.Schedule||(exports.Schedule={}))[Pe.Startup=0]="Startup",Pe[Pe.First=1]="First",Pe[Pe.PreUpdate=2]="PreUpdate",Pe[Pe.Update=3]="Update",Pe[Pe.PostUpdate=4]="PostUpdate",Pe[Pe.Last=5]="Last",Pe[Pe.FixedPreUpdate=10]="FixedPreUpdate",Pe[Pe.FixedUpdate=11]="FixedUpdate",Pe[Pe.FixedPostUpdate=12]="FixedPostUpdate";let Te=0;function Me(e,t,s){const n=++Te;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Ee(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class Ce{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Se&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new ve(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Se(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ae{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const Re=fe(new Ae,"Input");class Ie{constructor(e){this.target_=e??null}build(e){const s=new Ae;e.insertResource(Re,s),t().bindInputEvents({onKeyDown(e){s.keysDown.has(e)||s.keysPressed.add(e),s.keysDown.add(e)},onKeyUp(e){s.keysDown.delete(e),s.keysReleased.add(e)},onPointerMove(e,t){s.mouseX=e,s.mouseY=t},onPointerDown(e,t,n){s.mouseX=t,s.mouseY=n,s.mouseButtons.add(e),s.mouseButtonsPressed.add(e)},onPointerUp(e){s.mouseButtons.delete(e),s.mouseButtonsReleased.add(e)},onWheel(e,t){s.scrollDeltaX+=e,s.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.Last,Me([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Fe=new Ie;function Be(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=De(t[e]),o=De(r);"null"!==s&&"undefined"!==s&&(s!==o&&null!=r&&n.push({field:e,expected:s,actual:o,value:r}))}return n}function De(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ke(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}let Le=null;function We(e){Le=e}function Ue(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Le&&Le(e,t)}function $e(e){const t={};for(const s of Object.keys(e)){const n=e[s];if(null==n||"object"!=typeof n||Array.isArray(n))t[s]=n;else{const e=n;t[s]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:$e(e)}}return t}class ze{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw Ue(e,"spawn"),e}else e=this.entities_.size+1;return this.entities_.add(e),e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){Ue(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t)this.tsStorage_.get(s)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){Ue(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Ue(t,`removeParent(entity=${e})`)}}insert(e,t,s){return H(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return H(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return H(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(H(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return Ue(s,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");H(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const s=this.cppRegistry_;return t={add:s[`add${e}`].bind(s),get:s[`get${e}`].bind(s),has:s[`has${e}`].bind(s),remove:s[`remove${e}`].bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Be(t._name,t._default,n);if(e.length>0)throw new Error(ke(t._name,e))}const r={...t._default,...n};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,$e(r))}catch(s){Ue(s,`insertBuiltin(${t._name}, entity=${e})`)}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return this.getBuiltinMethods(t._cppName).get(e)}catch(s){return Ue(s,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(s){return Ue(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Ue(s,`removeBuiltin(${t._name}, entity=${e})`)}}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const r=Be(t._name,t._default,e);if(r.length>0)throw new Error(ke(t._name,r));n=e}const r=t.create(n);this.getStorage(t).set(e,r),this.worldVersion_++;let o=this.entityComponents_.get(e);return o||(o=[],this.entityComponents_.set(e,o)),-1===o.indexOf(t._id)&&o.push(t._id),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getComponentTypes(e){const t=[];for(const[s,n]of this.builtinMethodCache_)try{n.has(e)&&t.push(s)}catch{}if(this.cppRegistry_)for(const[s,n]of j)if(H(n)&&!t.includes(s))try{this.getBuiltinMethods(n._cppName).has(e)&&t.push(s)}catch{}const s=this.entityComponents_.get(e);if(s){const e="undefined"!=typeof window?window.__esengine_componentRegistry:void 0;if(e)for(const n of s)for(const[s,r]of e)if(r._id===n){t.push(s);break}}return t}getEntitiesWithComponents(e,t=[],s=[]){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();let n=e.map(e=>e._name).sort().join(",");t.length>0&&(n+="|+"+t.map(e=>e._name).sort().join(",")),s.length>0&&(n+="|-"+s.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(n);if(r&&r.version===this.worldVersion_)return r.result;let o=null,i=1/0;for(const t of e)if(!H(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<i&&(i=s,o=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const l=o?o.keys():this.entities_;for(const t of l){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&a.push(t)}return this.queryCache_.set(n,{version:this.worldVersion_,result:a}),a}}const Oe=fe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var He;function je(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(He=exports.BlendMode||(exports.BlendMode={}))[He.Normal=0]="Normal",He[He.Additive=1]="Additive",He[He.Multiply=2]="Multiply",He[He.Screen=3]="Screen",He[He.PremultipliedAlpha=4]="PremultipliedAlpha";let Xe=null,Ne=null,Ve=1;const Ye=new Map;function Ge(e){Xe=e,Ne=e.getResourceManager(),rt()}function qe(){0!==Ze&&Xe&&(Xe._free(Ze),Ze=0),Ye.clear(),Ve=1,Qe=!1,tt.clear(),st=null,Ne=null,Xe=null}function Je(){if(!Ne)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ne}const Ke={createShader:(e,t)=>Je().createShader(e,t),releaseShader(e){e>0&&Je().releaseShader(e)},create(e){const t=Ve++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))s.uniforms.set(t,n);return Ye.set(t,s),t},get:e=>Ye.get(e),setUniform(e,t,s){const n=Ye.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ye.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ye.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ye.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=Ye.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ye.get(e);return t?.shader??0},release(e){Ye.delete(e)},isValid:e=>Ye.has(e),releaseAll(){Ye.clear()},createFromAsset(e,t){const s={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)s[t]=n;else if("object"==typeof n&&null!==n){const e=n;"a"in e?s[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(s[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:s,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ye.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Ve++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ye.set(s,n),s},toAssetData(e,t){const s=Ye.get(e);if(!s)return null;const n={};for(const[e,t]of s.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:s.blendMode,depthTest:s.depthTest,properties:n}},getUniforms(e){const t=Ye.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Qe=!1,Ze=0;const et=4096,tt=new Map;let st=null;function nt(e){const t=(0===Ze&&Xe&&(Ze=Xe._malloc(et)),Ze);if(0===t||!Xe)return{ptr:0,count:0};let s=0,n=0;const r=Xe.HEAPU8,o=Xe.HEAPU32,i=Xe.HEAPF32;for(const[a,l]of e){if(s+128>et)break;let e=tt.get(a);e||(st||(st=new TextEncoder),e=st.encode(a),tt.set(a,e));const c=e.length,d=4*Math.ceil(c/4);o[t+s>>2]=c,s+=4,r.set(e,t+s),s+=d;let u=0,h=[0,0,0,0];if("number"==typeof l)u=0,h[0]=l;else if(Array.isArray(l)){u=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(u=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(u=2,h=[l.x,l.y,l.z,0]):"y"in l&&(u=1,h=[l.x,l.y,0,0]);o[t+s>>2]=u,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function rt(){if(!Xe||Qe)return;Xe.materialDataProvider=(e,t,s,n,r)=>{const o=Ye.get(e);if(!o)return Xe.HEAPU32[t>>2]=0,Xe.HEAPU32[s>>2]=0,Xe.HEAPU32[n>>2]=0,void(Xe.HEAPU32[r>>2]=0);Xe.HEAPU32[t>>2]=o.shader,Xe.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=nt(o.uniforms);Xe.HEAPU32[n>>2]=i,Xe.HEAPU32[r>>2]=a},Qe=!0}const ot={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class it{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{o.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class at{constructor(e,t=""){this.cache_=new it,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ke.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ke.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await o(t))throw new Error(`Material file not found: ${t}`);const s=await r(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const i=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(i);return{handle:Ke.createFromAsset(n,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const lt=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}]]);function ct(e){return lt.get(e)?.fields??[]}function dt(e,t){const s=new Map;for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,ie,{value:n.name}),!1!==n.visible)for(const s of n.components)ht(e,t,s,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}async function ut(e,t,s){const n=new Map,r=s?.assetServer,o=s?.assetBaseUrl,i=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=lt.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,d=new Map,u=new Map,h=[];for(const e of r)h.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)h.push((async()=>{try{const n=await t.loadMaterial(e,s);d.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),d.set(e,0)}})());for(const e of i)h.push((async()=>{try{const n=await t.loadBitmapFont(e,s);u.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),u.set(e,0)}})());for(const e of a)h.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(h);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=lt.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":s[e.field]=c.get(t)??0;break;case"material":s[e.field]=d.get(t)??0;break;case"font":s[e.field]=u.get(t)??0}}}}(t,r,o,i);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,ie,{value:s.name}),!1!==s.visible)for(const n of s.components)ht(e,t,n,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function ht(e,t,s,n){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=N(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}class pt{constructor(e){this.textureCache_=new it,this.shaderCache_=new it,this.jsonCache_=new it,this.textCache_=new it,this.binaryCache_=new it,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new it,this.prefabCache_=new it,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.module_=e,this.canvas_=i(I.textCanvasSize,I.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new at(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),Ke.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),d="binary"===g(e)?.contentType,u=d?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(u,o,d);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=l.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=g(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${n}`:n,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return ut(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,s,a,o.length,1,n);return this.module_._free(a),{handle:l,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Ke.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await o(t))throw new Error(`Shader file not found: ${e}`);const n=await r(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:a}=this.parseEsShader(n);if(!i||!a)throw new Error(`Invalid shader format: ${e}`);return Ke.createShader(i,a)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return r(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return n(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const r=await s(e);if(!r.ok)throw new Error(`Failed to fetch binary: ${e} (${r.status})`);return r.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const ft=fe(null,"Assets");class gt{build(e){const t=e.wasmModule;t?e.insertResource(ft,new pt(t)):console.warn("AssetPlugin: No WASM module available")}}const mt=new gt;async function yt(e,t,s){const{entities:n,rootId:r}=await _t(t,s?.overrides??[],s,void 0,new Set),o={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await ut(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=i.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:i}}const xt=10;async function _t(e,t,s,n,r,o=0){if(o>xt)throw new Error(`Prefab nesting depth exceeded ${xt}. Check for deep or circular nesting in: ${e.name}`);const i=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,a++)}const l=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await _t(e,n.nestedPrefab.overrides,s,a,r,o+1);i.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?i.get(n.parent)??null:null),l.push(...t.entities);continue}const c=i.get(n.prefabEntityId),d=n.prefabEntityId===e.rootEntityId,u={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:d?null:null!==n.parent?i.get(n.parent)??null:null,children:n.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};wt(u,t),l.push(u)}const c=i.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function wt(e,t){for(const s of t)if(s.prefabEntityId===e.prefabEntityId)switch(s.type){case"property":if(s.componentType&&void 0!==s.propertyName){const t=e.components.find(e=>e.type===s.componentType);t&&(t.data[s.propertyName]=s.value)}break;case"name":"string"==typeof s.value&&(e.name=s.value);break;case"visibility":"boolean"==typeof s.value&&(e.visible=s.value);break;case"component_added":if(s.componentData){e.components.some(e=>e.type===s.componentData.type)||e.components.push({type:s.componentData.type,data:JSON.parse(JSON.stringify(s.componentData.data))})}break;case"component_removed":s.componentType&&(e.components=e.components.filter(e=>e.type!==s.componentType))}}class vt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return yt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const bt=fe(null,"Prefabs");class St{constructor(){this.name="PrefabsPlugin",this.dependencies=[ft]}build(e){const t=e.getResource(ft);e.insertResource(bt,new vt(e.world,t))}}const Pt=new St;let Tt=null,Mt=0,Et=0,Ct=0;const At=new Float32Array(256);function Rt(e){Tt=e,Mt=Tt._malloc(64),Et=Tt._malloc(64),Ct=Tt._malloc(1024)}function It(){Tt&&(Mt&&(Tt._free(Mt),Mt=0),Et&&(Tt._free(Et),Et=0),Ct&&(Tt._free(Ct),Ct=0)),Tt=null}function Ft(){if(!Tt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Tt}const Bt={r:1,g:1,b:1,a:1},Dt={begin(e){const t=Ft();try{t.HEAPF32.set(e,Mt/4),t.draw_begin(Mt)}catch(e){Ue(e,"Draw.begin")}},end(){try{Ft().draw_end()}catch(e){Ue(e,"Draw.end")}},line(e,t,s,n=1){try{Ft().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ue(e,"Draw.line")}},rect(e,t,s,n=!0){try{Ft().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ue(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{Ft().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ue(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,r=32){try{Ft().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Ue(e,"Draw.circle")}},circleOutline(e,t,s,n=1,r=32){try{Ft().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Ue(e,"Draw.circleOutline")}},texture(e,t,s,n=Bt){try{Ft().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Ue(e,"Draw.texture")}},textureRotated(e,t,s,n,r=Bt){try{Ft().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)}catch(e){Ue(e,"Draw.textureRotated")}},setLayer(e){Ft().draw_setLayer(e)},setDepth(e){Ft().draw_setDepth(e)},getDrawCallCount:()=>Tt?Tt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Tt?Tt.draw_getPrimitiveCount():0,setBlendMode(e){Ft().draw_setBlendMode(e)},setDepthTest(e){Ft().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=Ft();n.HEAPF32.set(s,Et/4),n.draw_mesh(e,t,Et)}catch(s){Ue(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=Ft(),r=Ke.get(t);if(!r)return;if(Dt.setBlendMode(r.blendMode),Dt.setDepthTest(r.depthTest),0===r.uniforms.size)return void Dt.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,Et/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=Wt(t);if(!(n<0)){if(je(s))At[o++]=10,At[o++]=n,At[o++]=s.slot??e++,At[o++]=s.textureId;else if("number"==typeof s)At[o++]=1,At[o++]=n,At[o++]=s;else if(Array.isArray(s)){At[o++]=s.length,At[o++]=n;for(let e=0;e<s.length;e++)At[o++]=s[e]}else"w"in s?(At[o++]=4,At[o++]=n,At[o++]=s.x,At[o++]=s.y,At[o++]=s.z,At[o++]=s.w):"z"in s?(At[o++]=3,At[o++]=n,At[o++]=s.x,At[o++]=s.y,At[o++]=s.z):(At[o++]=2,At[o++]=n,At[o++]=s.x,At[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(At.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void n.draw_mesh(e,r.shader,Et);n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),Ct/4),n.draw_meshWithUniforms(e,r.shader,Et,Ct,o)}catch(s){Ue(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},kt={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17},Lt=new Set;function Wt(e){const t=kt[e];return void 0!==t?t:(Lt.has(e)||(Lt.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(kt).join(", ")}`)),-1)}const Ut=new Map;function $t(e,t,s){Ut.set(e,{fn:t,scene:s??""})}function zt(e){Ut.delete(e)}function Ot(){Ut.clear()}var Ht;exports.DataType=void 0,(Ht=exports.DataType||(exports.DataType={}))[Ht.Float=1]="Float",Ht[Ht.Float2=2]="Float2",Ht[Ht.Float3=3]="Float3",Ht[Ht.Float4=4]="Float4",Ht[Ht.Int=5]="Int",Ht[Ht.Int2=6]="Int2",Ht[Ht.Int3=7]="Int3",Ht[Ht.Int4=8]="Int4";let jt=null,Xt=0,Nt=0,Vt=0;function Yt(e){jt=e,Xt=jt._malloc(262144),Nt=jt._malloc(65536),Vt=jt._malloc(256)}function Gt(){jt&&(Xt&&jt._free(Xt),Nt&&jt._free(Nt),Vt&&jt._free(Vt),Xt=0,Nt=0,Vt=0),jt=null}function qt(){if(!jt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return jt}const Jt={create(e){const t=qt(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,Xt/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Vt,r).set(o),t.geometry_init(s,Xt,n,Vt,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Nt,n).set(e.indices),t.geometry_setIndices16(s,Nt,n)}else{new Uint32Array(t.HEAPU8.buffer,Nt,n).set(e.indices),t.geometry_setIndices32(s,Nt,n)}}return s},updateVertices(e,t,s=0){const n=qt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,Xt/4),n.geometry_updateVertices(e,Xt,r,s)},release(e){e>0&&qt().geometry_release(e)},isValid:e=>!(!jt||e<=0)&&jt.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Jt.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;s.push(o,i,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Jt.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),s=Math.min(s,o.y),n=Math.max(n,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-s)/(r-s);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return Jt.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(i)})}};let Kt=null;function Qt(e){Kt=e}function Zt(){Kt&&ts.isInitialized()&&ts.shutdown(),Kt=null}function es(){if(!Kt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Kt}const ts={init(e,t){try{return es().postprocess_init(e,t)}catch(s){return Ue(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{es().postprocess_shutdown()}catch(e){Ue(e,"PostProcess.shutdown")}},resize(e,t){try{es().postprocess_resize(e,t)}catch(s){Ue(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return es().postprocess_addPass(e,t)}catch(t){return Ue(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{es().postprocess_removePass(e)}catch(t){Ue(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{es().postprocess_setPassEnabled(e,t)}catch(t){Ue(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return es().postprocess_isPassEnabled(e)}catch(t){return Ue(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{es().postprocess_setUniformFloat(e,t,s)}catch(s){Ue(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{es().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){Ue(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{es().postprocess_begin()}catch(e){Ue(e,"PostProcess.begin")}},end(){try{es().postprocess_end()}catch(e){Ue(e,"PostProcess.end")}},getPassCount(){try{return es().postprocess_getPassCount()}catch(e){return Ue(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Kt)return!1;try{return Kt.postprocess_isInitialized()}catch(e){return Ue(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{es().postprocess_setBypass(e)}catch(e){Ue(e,"PostProcess.setBypass")}},isBypassed(){if(!Kt)return!0;try{return Kt.postprocess_isBypassed()}catch(e){return Ue(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Ke.createShader(ss,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>Ke.createShader(ss,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Ke.createShader(ss,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Ke.createShader(ss,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},ss="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var ns;exports.RenderStage=void 0,(ns=exports.RenderStage||(exports.RenderStage={}))[ns.Background=0]="Background",ns[ns.Opaque=1]="Opaque",ns[ns.Transparent=2]="Transparent",ns[ns.Overlay=3]="Overlay";let rs=null,os=0;function is(e){rs=e,os=rs._malloc(64)}function as(){rs&&os&&(rs._free(os),os=0),rs=null}const ls={init(e,t){rs?.renderer_init(e,t)},resize(e,t){rs?.renderer_resize(e,t)},begin(e,t){if(rs&&os)try{rs.HEAPF32.set(e,os/4),rs.renderer_begin(os,t??0)}catch(e){Ue(e,"Renderer.begin")}},flush(){try{rs?.renderer_flush()}catch(e){Ue(e,"Renderer.flush")}},end(){try{rs?.renderer_end()}catch(e){Ue(e,"Renderer.end")}},submitSprites(e){if(rs)try{rs.renderer_submitSprites(e._cpp)}catch(e){Ue(e,"Renderer.submitSprites")}},submitBitmapText(e){if(rs)try{rs.renderer_submitBitmapText(e._cpp)}catch(e){Ue(e,"Renderer.submitBitmapText")}},submitSpine(e){if(rs)try{rs.renderer_submitSpine?.(e._cpp)}catch(e){Ue(e,"Renderer.submitSpine")}},setStage(e){rs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>rs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){rs?.renderer_releaseTarget(e)},getTargetTexture:e=>rs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>rs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){rs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){rs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){rs?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){rs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>rs?rs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>rs?{drawCalls:rs.renderer_getDrawCalls(),triangles:rs.renderer_getTriangles(),sprites:rs.renderer_getSprites(),text:rs.renderer_getText(),spine:rs.renderer_getSpine?.()??0,meshes:rs.renderer_getMeshes(),culled:rs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let cs=null;function ds(e){cs=e}function us(){cs=null}const hs={enable(){cs?.gl_enableErrorCheck(!0)},disable(){cs?.gl_enableErrorCheck(!1)},check:e=>cs?.gl_checkErrors(e)??0,diagnose(){cs?.renderer_diagnose()}};class ps{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:o}=e;n===this.lastWidth_&&r===this.lastHeight_||(ls.resize(n,r),ts.isInitialized()&&ts.getPassCount()>0&&ts.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),ls.setViewport(0,0,n,r),ls.clearBuffers(3),ls.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),ls.submitSprites(t),ls.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):ls.submitSpine(t),ls.flush(),this.executeDrawCallbacks(s,o),ls.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;ls.setViewport(n.x,n.y,n.w,n.h),ls.setScissor(n.x,n.y,n.w,n.h,!0),ls.clearBuffers(r),ls.setScissor(0,0,0,0,!1),ls.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),ls.submitSprites(t),ls.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):ls.submitSpine(t),ls.flush(),this.executeDrawCallbacks(s,o),ls.end()}executeDrawCallbacks(e,t){const s=Ut;if(s.size>0){Dt.begin(e);const n=[];for(const[e,r]of s.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}Dt.end();for(const e of n)zt(e)}}}const fs="__scene_transition_overlay__";class gs{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class ms{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,ae,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),$t(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=ts.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){ts.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,ae)){const s=this.app_.world.get(e,ae);s.persistent=t,this.app_.world.insert(e,ae,s)}}}class ys{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_)return void console.warn(`[SceneManager] Transition already in progress, ignoring switchTo("${e}")`);"fade"!==(t?.transition??"none")?(this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)):await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??I.sceneTransitionDuration,r=t.color??{...I.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},$t(fs,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),s="fade-out"===this.transition_.phase?t:1-t;Dt.setLayer(9999),Dt.setDepth(9999),Dt.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:s})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,s=this.activeScene_;(async()=>{s&&s!==e&&await this.unload(s,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,zt(fs)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,zt(fs),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new gs(t);this.scenes_.set(e,s);const n=new ms(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(ft)?this.app_.getResource(ft):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(ft)&&(t.assetServer=this.app_.getResource(ft));const n=await ut(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,ae,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=_s(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new gs(t);this.scenes_.set(e,s);const n=new ms(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(ft)?this.app_.getResource(ft):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(ft)&&(t.assetServer=this.app_.getResource(ft));const n=await ut(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,ae,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=_s(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const r=t?.keepPersistent??!0;for(const e of s.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,ae)){if(this.app_.world.get(e,ae).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())zt(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{ts.removePass(e)}catch{}s.postProcessPasses.length=0,this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(t&&"running"===t.status){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Q)){const s=this.app_.world.get(e,Q);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,Q,s)}}}wake(e){const t=this.scenes_.get(e);if(t&&"sleeping"===t.status){t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Q)){const s=this.app_.world.get(e,Q),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,Q,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{ts.setEnabled(s,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,s]of this.scenes_)"running"===s.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const xs=fe(null,"SceneManager");function _s(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(xs).getSceneStatus(t)&&s._fn(...n)}}}const ws=Me([me(xs),ge(_e)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),vs={name:"SceneManager",build(e){const t=new ys(e);e.insertResource(xs,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(xs),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(exports.Schedule.Startup,s),e.addSystemToSchedule(exports.Schedule.Last,ws)}};class bs{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=a(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(exports.Schedule.Last);else{this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),this.step_pending_&&(this.step_pending_=!1)}requestAnimationFrame(this.mainLoop)},this.world_=new ze,this.resources_=new xe;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new bs}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return We(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(xs).register(e),this}setInitialScene(e){return this.getResource(xs).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Ce(this.world_,this.resources_),this.resources_.insert(_e,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1,Ot();const e=[us,as,Zt,Gt,qe,It];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,o=i=>{if(n.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}r.delete(i),n.add(i),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(_e);t.delta=e,t.elapsed+=e,t.frameCount++}}const Ss=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ps(e,t,s,n,r){const o=e*t/s,i=e;switch(n){case q.FixedWidth:return o;case q.FixedHeight:return i;case q.Expand:return Math.max(o,i);case q.Shrink:return Math.min(o,i);case q.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function Ts(e,t,s,n,r,o){if(0===s||0===n)return[];const i=e.registry_getCameraEntities(t);if(0===i.length)return[];const a=o&&r?i.filter(e=>{const t=r.tryGet(e,ae);return!t||""===t.scene||o.has(t.scene)}):i;if(0===a.length)return[];const l=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),c=[];for(const e of a){const r=t.getCamera(e),o=t.getLocalTransform(e),i={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=i.w*s/(i.h*n);let d,u=0,h=0;if(r.projectionType===Y.Orthographic){if(h=r.orthoSize,l){h=Ps(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}u=h*a,d=Es(-u,u,-h,h,-r.farPlane,r.farPlane)}else d=As(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const p=Is(o.position.x,o.position.y,o.position.z);c.push({entity:e,viewProjection:new Float32Array(Bs(d,p)),viewportRect:i,clearFlags:r.clearFlags,priority:r.priority,halfW:u,halfH:h,cameraX:o.position.x,cameraY:o.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const Ms=new Float32Array(16);function Es(e,t,s,n,r,o){const i=Ms;i.fill(0);const a=t-e,l=n-s,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(n+s)/l,i[14]=-(o+r)/c,i[15]=1,i}const Cs=new Float32Array(16);function As(e,t,s,n){const r=Cs;r.fill(0);const o=1/Math.tan(e/2),i=s-n;return r[0]=o/t,r[5]=o,r[10]=(n+s)/i,r[11]=-1,r[14]=2*n*s/i,r}const Rs=new Float32Array(16);function Is(e,t,s){const n=Rs;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=-e,n[13]=-t,n[14]=-s,n[15]=1,n}const Fs=new Float32Array(16);function Bs(e,t){const s=Fs;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}var Ds,ks,Ls;exports.TextAlign=void 0,(Ds=exports.TextAlign||(exports.TextAlign={}))[Ds.Left=0]="Left",Ds[Ds.Center=1]="Center",Ds[Ds.Right=2]="Right",exports.TextVerticalAlign=void 0,(ks=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[ks.Top=0]="Top",ks[ks.Middle=1]="Middle",ks[ks.Bottom=2]="Bottom",exports.TextOverflow=void 0,(Ls=exports.TextOverflow||(exports.TextOverflow={}))[Ls.Visible=0]="Visible",Ls[Ls.Clip=1]="Clip",Ls[Ls.Ellipsis=2]="Ellipsis";const Ws=U("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2}),Us=U("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class $s{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(I.textCanvasSize,I.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),d=Math.ceil(.2*e.fontSize),u=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=r?Math.ceil(o):u+2*d,f=r?Math.ceil(i):h+2*d;if(r&&e.overflow===exports.TextOverflow.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(n.width<p||n.height<f){const e=Math.max(n.width,this.nextPowerOf2(p)),t=Math.max(n.height,this.nextPowerOf2(f));n.width=e,n.height=t}const g=Math.round(255*e.color.r),m=Math.round(255*e.color.g),y=Math.round(255*e.color.b),x=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${g}, ${m}, ${y}, ${x})`,r&&e.overflow===exports.TextOverflow.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const _=l.length*c;let w;if(r)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=d;break;case exports.TextVerticalAlign.Middle:w=(f-_)/2;break;case exports.TextVerticalAlign.Bottom:w=f-_-d;break;default:w=d}else w=d;let v=w;for(const t of l){let n;switch(e.align){case exports.TextAlign.Left:n=d;break;case exports.TextAlign.Center:n=p/2;break;case exports.TextAlign.Right:n=p-d;break;default:n=d}s.fillText(t,n,v),v+=c}r&&e.overflow===exports.TextOverflow.Clip&&s.restore();const b=s.getImageData(0,0,p,f),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),T=this.module._malloc(S.length);this.module.HEAPU8.set(S,T);const M=P.createTexture(p,f,T,S.length,1,!0);return this.module._free(T),{textureHandle:M,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function zs(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function Os(e,t,s){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(s?s.size.x:0)||e.containerHeight!==(s?s.size.y:0)}class Hs{build(e){X("Text",Ws);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new $s(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Ws));for(const e of r.keys())n.valid(e)&&n.has(e,Ws)||r.delete(e);const e=n.getEntitiesWithComponents([Ws]);for(const t of e){const e=n.get(t,Ws),o=n.has(t,Us)?n.get(t,Us):null,i=r.get(t);if(i&&!Os(i,e,o))continue;n.has(t,Q)||n.insert(t,Q,{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=s.renderForEntity(t,e,o),l=n.get(t,Q);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,n.insert(t,Q,l),r.set(t,zs(e,o))}}))}}const js=new Hs,Xs=U("UIMask",{enabled:!0,mode:"scissor"});function Ns(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,o-n)}}function Vs(e,t,s,n,r,o,i,a,l,c,d){const u=e-s*r,h=e+s*(1-r),p=t-n*o,f=t+n*(1-o);function g(e,t){const s=i[0]*e+i[4]*t+i[12],n=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(s/r)+.5)*c,l+(.5*(n/r)+.5)*d]}const[m,y]=g(u,p),[x,_]=g(h,f),w=Math.min(m,x),v=Math.max(m,x),b=Math.min(y,_),S=Math.max(y,_);return{x:Math.round(w),y:Math.round(b),w:Math.round(v-w),h:Math.round(S-b)}}function Ys(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],d=e[7],u=e[8],h=e[9],p=e[10],f=e[11],g=e[12],m=e[13],y=e[14],x=e[15],_=n*l-r*a,w=n*c-o*a,v=n*d-i*a,b=r*c-o*l,S=r*d-i*l,P=o*d-i*c,T=u*m-h*g,M=u*y-p*g,E=u*x-f*g,C=h*y-p*m,A=h*x-f*m,R=p*x-f*y;let I=_*R-w*A+v*C+b*E-S*M+P*T;return 0===I||(I=1/I,s[0]=(l*R-c*A+d*C)*I,s[1]=(o*A-r*R-i*C)*I,s[2]=(m*P-y*S+x*b)*I,s[3]=(p*S-h*P-f*b)*I,s[4]=(c*E-a*R-d*M)*I,s[5]=(n*R-o*E+i*M)*I,s[6]=(y*v-g*P-x*w)*I,s[7]=(u*P-p*v+f*w)*I,s[8]=(a*A-l*E+d*T)*I,s[9]=(r*E-n*A-i*T)*I,s[10]=(g*S-m*v+x*_)*I,s[11]=(h*v-u*S-f*_)*I,s[12]=(l*M-a*C-c*T)*I,s[13]=(n*C-r*M+o*T)*I,s[14]=(m*w-g*b-y*_)*I,s[15]=(u*b-h*w+p*_)*I),s}function Gs(e,t,s,n,r,o,i){const a=(e-n)/o*2-1,l=(t-r)/i*2-1,c=s[0]*a+s[4]*l+s[12],d=s[1]*a+s[5]*l+s[13],u=s[3]*a+s[7]*l+s[15];return{x:c/u,y:d/u}}function qs(e,t,s,n,r,o,i,a,l,c){const d=2*Math.atan2(l,c),u=Math.sin(-d),h=Math.cos(-d),p=e-s,f=t-n,g=p*h-f*u+s,m=p*u+f*h+n;return g>=s-r*i&&g<=s+r*(1-i)&&m>=n-o*a&&m<=n+o*(1-a)}function Js(e,t,s,n,r,o,i){if(!e.has(t,Us)||!e.has(t,K))return null;const a=e.get(t,Us),l=e.get(t,K),c=a.size.x*l.scale.x,d=a.size.y*l.scale.y;return Vs(l.position.x,l.position.y,c,d,a.pivot.x,a.pivot.y,s,n,r,o,i)}function Ks(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Xs]);if(0===l.length)return;const c=[],d=[],u=new Set,h=new Set;for(const e of l){const s=t.get(e,Xs);s.enabled&&(u.add(e),"stencil"===s.mode?(d.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,r,o,i,a,l,c){const d=[];for(const e of n){let s=!0,n=e;for(;t.has(n,se);){const e=t.get(n,se);if(r.has(e.entity)){if("scissor"===t.get(e.entity,Xs).mode){s=!1;break}}n=e.entity}s&&d.push(e)}function u(n,d){const h=e.getChildEntities(s,n);for(const s of h){let n=d;if(r.has(s)){if("scissor"===t.get(s,Xs).mode){const e=Js(t,s,o,i,a,l,c);e&&(n=Ns(d,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),u(s,n)}}for(const e of d){const s=Js(t,e,o,i,a,l,c);s&&u(e,s)}}(e,t,s,c,u,n,r,o,i,a),d.length>0&&function(e,t,s,n,r){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0,n=e;for(;t.has(n,se);){const e=t.get(n,se);if(r.has(e.entity)){s=!1;break}n=e.entity}s&&o.push(e)}let i=1;function a(t,n){e.renderer_setEntityStencilMask(t,n);const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){a(t,i++)}else e.renderer_setEntityStencilTest(t,n),l(t,n)}function l(t,n){const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){a(t,i++)}else e.renderer_setEntityStencilTest(t,n),l(t,n)}for(const e of o){a(e,i++)}}(e,t,s,d,h)}catch(t){e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class Qs{build(e){if(X("UIMask",Xs),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Ks(e.wasmModule,e.world))}}const Zs=new Qs,en=U("Interactable",{enabled:!0,blockRaycast:!0}),tn=U("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var sn;exports.ButtonState=void 0,(sn=exports.ButtonState||(exports.ButtonState={}))[sn.Normal=0]="Normal",sn[sn.Hovered=1]="Hovered",sn[sn.Pressed=2]="Pressed",sn[sn.Disabled=3]="Disabled";const nn=U("Button",{state:exports.ButtonState.Normal,transition:null,enabled:!0});class rn{constructor(){this.events_=[]}emit(e,t,s){const n=s??e;this.events_.push({entity:e,type:t,target:n,currentTarget:e})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const on=fe(new rn,"UIEvents"),an=$("ScreenSpace");function ln(e,t,s,n,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,d=o.bottom+e.y*a,u=o.bottom+t.y*a;let h,p,f,g;if(e.x===t.x){const e=l+s.x,t=.5*r.x;h=e-t,f=e+t}else h=l+s.x,f=c+n.x;if(e.y===t.y){const e=d+s.y,t=.5*r.y;p=e-t,g=e+t}else p=d+s.y,g=u+n.y;return{centerX:.5*(h+f),centerY:.5*(p+g),width:f-h,height:g-p,rect:{left:h,bottom:p,right:f,top:g}}}function cn(e){return{anchorMinX:e.anchorMin.x,anchorMinY:e.anchorMin.y,anchorMaxX:e.anchorMax.x,anchorMaxY:e.anchorMax.y,offsetMinX:e.offsetMin.x,offsetMinY:e.offsetMin.y,offsetMaxX:e.offsetMax.x,offsetMaxY:e.offsetMax.y,sizeX:e.size.x,sizeY:e.size.y}}function dn(e,t){return e.anchorMinX!==t.anchorMin.x||e.anchorMinY!==t.anchorMin.y||e.anchorMaxX!==t.anchorMax.x||e.anchorMaxY!==t.anchorMax.y||e.offsetMinX!==t.offsetMin.x||e.offsetMinY!==t.offsetMin.y||e.offsetMaxX!==t.offsetMax.x||e.offsetMaxY!==t.offsetMax.y||e.sizeX!==t.size.x||e.sizeY!==t.size.y}function un(e,t){let s=t;for(;;){if(e.has(s,an))return s;if(!e.has(s,se))return null;const t=e.get(s,se);if(!e.valid(t.entity))return null;s=t.entity}}function hn(e,t,s,n,r,o){if(!e.has(t,Us))return;const i=e.get(t,Us),a=ln(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,s);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,J);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-n,l.position.y=a.centerY-r),e.insert(t,J,l),!e.has(t,ne))return;const c=e.get(t,ne);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&hn(e,t,a.rect,a.centerX,a.centerY,!1)}class pn{build(e){X("UIRect",Us);const t=e.world,s=new Map;let n=NaN,r=NaN,o=NaN,i=NaN;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([ge(Oe)],e=>{if(!e.valid)return;const a={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},l=.5*(a.left+a.right),c=.5*(a.bottom+a.top),d=n!==e.worldLeft||r!==e.worldBottom||o!==e.worldRight||i!==e.worldTop;n=e.worldLeft,r=e.worldBottom,o=e.worldRight,i=e.worldTop;const u=new Set;if(d){const e=t.getEntitiesWithComponents([an,Us,J]);for(const t of e)u.add(t)}const h=t.getEntitiesWithComponents([Us]);for(const e of h){const n=t.get(e,Us),r=s.get(e);if(!r||dn(r,n)){const s=un(t,e);null!==s&&u.add(s)}}for(const e of s.keys())if(!t.valid(e)||!t.has(e,Us)){s.delete(e);const n=un(t,e);null!==n&&u.add(n)}for(const e of u)hn(t,e,a,l,c,!0);for(const e of h){const n=t.get(e,Us);s.set(e,cn(n))}},{name:"UILayoutSystem"}))}}const fn=new pn,gn=new Float32Array(16),mn=new Float32Array(16);let yn=!0,xn=1;function _n(e,t,s,n){t.emit(s,n,s);let r=s;for(;e.has(r,se);){const o=e.get(r,se).entity;if(!e.valid(o))break;if(!e.has(o,en)){r=o;continue}const i=e.get(o,en);if(i.enabled&&t.emit(o,n,s),i.blockRaycast)break;r=o}}class wn{build(e){X("Interactable",en),X("Button",nn);const t=e.world,s=new rn;e.insertResource(on,s);let n=null,r=null;xn="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([ge(Re),ge(Oe)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([tn]);for(const e of i){const s=t.get(e,tn);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a=e.mouseX*xn,l=o.screenH-e.mouseY*xn;!function(e){let t=!1;for(let s=0;s<16;s++)if(mn[s]!==e[s]){t=!0;break}t&&(mn.set(e),yn=!0)}(o.viewProjection),yn&&(Ys(o.viewProjection,gn),yn=!1);const c=Gs(a,l,gn,o.vpX,o.vpY,o.vpW,o.vpH),d=t.getEntitiesWithComponents([en,Us,K]);let u=null,h=-1/0;for(const e of d){t.has(e,tn)||t.insert(e,tn);if(!t.get(e,en).enabled)continue;const s=t.get(e,K),n=t.get(e,Us),r=n.size.x*s.scale.x,o=n.size.y*s.scale.y;if(qs(c.x,c.y,s.position.x,s.position.y,r,o,n.pivot.x,n.pivot.y,s.rotation.z,s.rotation.w)){let s=0;t.has(e,Q)&&(s=t.get(e,Q).layer),s>=h&&(h=s,u=e)}}if(n!==u){if(null!==n&&t.valid(n)&&t.has(n,tn)){t.get(n,tn).hovered=!1,s.emit(n,"hover_exit")}if(null!==u){t.get(u,tn).hovered=!0,s.emit(u,"hover_enter")}n=u}if(e.isMouseButtonPressed(0)&&null!==u){const e=t.get(u,tn);e.pressed=!0,e.justPressed=!0,r=u,_n(t,s,u,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,tn)){const e=t.get(r,tn);e.pressed=!1,e.justReleased=!0,_n(t,s,r,"release"),r===n&&_n(t,s,r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(exports.Schedule.Update,Me([],()=>{const e=t.getEntitiesWithComponents([nn]);for(const s of e){if(t.has(s,en)||t.insert(s,en,{enabled:!0}),!t.has(s,tn))continue;const e=t.get(s,tn),n=t.get(s,nn),r=t.get(s,en),o=n.state;if(r.enabled?e.pressed?n.state=exports.ButtonState.Pressed:e.hovered?n.state=exports.ButtonState.Hovered:n.state=exports.ButtonState.Normal:n.state=exports.ButtonState.Disabled,o!==n.state&&n.transition&&t.has(s,Q)){const e=t.get(s,Q),r=n.transition;switch(n.state){case exports.ButtonState.Normal:e.color={...r.normalColor};break;case exports.ButtonState.Hovered:e.color={...r.hoveredColor};break;case exports.ButtonState.Pressed:e.color={...r.pressedColor};break;case exports.ButtonState.Disabled:e.color={...r.disabledColor}}t.insert(s,Q,e)}}},{name:"ButtonSystem"}))}}const vn=new wn,bn=U("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class Sn{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){X("TextInput",bn);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=i(I.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let a=null,l=!1,c=!0,d=0,u=0;const h=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!h)return;const p=h,f=()=>{l||null===a||_()},g=()=>{l=!0},m=()=>{l=!1,_()},y=t=>{if(null===a)return;if("Escape"===t.key)return void v();const n=s.get(a,bn);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(on).emit(a,"submit"),void v()}let r=n.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,n.cursorPos-1):"ArrowRight"===t.key?r=Math.min(n.value.length,n.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=n.value.length),r!==n.cursorPos&&(n.cursorPos=r,p.selectionStart=r,p.selectionEnd=r,n.dirty=!0,b())},x=()=>{if(null!==a&&s.valid(a)&&s.has(a,bn)){const e=s.get(a,bn);e.focused=!1,e.dirty=!0}a=null};function _(){if(null===a||!s.valid(a))return;const t=s.get(a,bn);if(t.readOnly)return;let n=p.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),p.value=n),n!==t.value){t.value=n;e.getResource(on).emit(a,"change")}t.cursorPos=p.selectionStart??n.length,t.dirty=!0,b()}function w(e){if(a===e)return;v();const t=s.get(e,bn);t.readOnly||(a=e,t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),b())}function v(){if(null!==a&&s.valid(a)&&s.has(a,bn)){const e=s.get(a,bn);e.focused=!1,e.dirty=!0}a=null,p.blur()}function b(){c=!0,d=0}function S(e,i,a,l){(r.width<a||r.height<l)&&(r.width=Tn(Math.max(r.width,a)),r.height=Tn(Math.max(r.height,l))),o.clearRect(0,0,r.width,r.height);const d=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*d.r)}, ${Math.round(255*d.g)}, ${Math.round(255*d.b)}, ${d.a})`,o.fillRect(0,0,a,l),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,l),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const u=0===i.value.length,h=u?i.placeholder:i.password?"●".repeat(i.value.length):i.value,p=u?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*p.r)}, ${Math.round(255*p.g)}, ${Math.round(255*p.b)}, ${p.a})`;const f=Math.ceil(1.2*i.fontSize),g=i.padding;if(i.multiline){const e=Pn(o,h,a-2*g);let t=g;for(const s of e)o.fillText(s,g,t),t+=f}else{const e=(l-i.fontSize)/2;o.fillText(h,g,e)}if(i.focused&&c){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,s,n;if(i.multiline){const e=Pn(o,i.value.substring(0,i.cursorPos),a-2*g),r=e.length>0?e[e.length-1]:"";t=g+o.measureText(r).width,s=g+(e.length-1)*f,n=f}else t=g+o.measureText(e).width,s=(l-i.fontSize)/2,n=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,s,2,n)}o.restore();const m=o.getImageData(0,0,a,l),y=new Uint8Array(m.data.buffer),x=t.getResourceManager(),_=t._malloc(y.length);t.HEAPU8.set(y,_);const w=n.get(e);void 0!==w&&x.releaseTexture(w);const v=x.createTexture(a,l,_,y.length,1,!0);n.set(e,v),t._free(_);const b=s.get(e,Q);b.texture=v,b.size.x=a,b.size.y=l,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},s.insert(e,Q,b)}p.addEventListener("input",f),p.addEventListener("compositionstart",g),p.addEventListener("compositionend",m),p.addEventListener("keydown",y),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",f),p.removeEventListener("compositionstart",g),p.removeEventListener("compositionend",m),p.removeEventListener("keydown",y),p.removeEventListener("blur",x),p.remove()},e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([ge(on)],e=>{const t=s.getEntitiesWithComponents([bn,en]);for(const e of t){if(!s.has(e,tn))continue;if(s.get(e,tn).justPressed)return void w(e)}if(null!==a){const e=s.getEntitiesWithComponents([en]);for(const t of e){if(s.has(t,bn))continue;if(!s.has(t,tn))continue;if(s.get(t,tn).justPressed)return void v()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==a&&(d+=r,d>=.5&&(d-=.5,c=!c,null!==a&&s.valid(a)&&s.has(a,bn)))){s.get(a,bn).dirty=!0}const o=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,bn)||(o.releaseTexture(t),n.delete(e));const i=s.getEntitiesWithComponents([bn,Us]);for(const e of i){const t=s.get(e,bn);if(!t.dirty)continue;const n=s.get(e,Us),r=Math.ceil(n.size.x),o=Math.ceil(n.size.y);r<=0||o<=0||(s.has(e,Q)||s.insert(e,Q,{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),S(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Pn(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const o of t){const t=n+o;e.measureText(t).width>s&&n?(r.push(n),n=o):n=t}n&&r.push(n)}return r.length>0?r:[""]}function Tn(e){let t=1;for(;t<e;)t*=2;return t}const Mn=new Sn,En={Simple:0,Sliced:1,Tiled:2,Filled:3},Cn={Horizontal:0,Vertical:1},An={Left:0,Right:1,Bottom:2,Top:3},Rn=U("Image",{texture:F,color:{r:1,g:1,b:1,a:1},imageType:En.Simple,fillMethod:Cn.Horizontal,fillOrigin:An.Left,fillAmount:1,preserveAspect:!1,layer:0,material:0,enabled:!0});const In=new class{build(e){X("Image",Rn);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([],()=>{const e=t.getEntitiesWithComponents([Rn]);for(const s of e){const e=t.get(s,Rn);t.has(s,Q)||t.insert(s,Q,{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const n=t.get(s,Q);if(n.texture=e.texture,n.color.r=e.color.r,n.color.g=e.color.g,n.color.b=e.color.b,n.color.a=e.color.a,n.layer=e.layer,n.material=e.material,t.has(s,Us)){const e=t.get(s,Us);n.size.x=e.size.x,n.size.y=e.size.y}if(n.uvOffset.x=0,n.uvOffset.y=0,n.uvScale.x=1,n.uvScale.y=1,e.imageType===En.Filled){const t=Math.max(0,Math.min(1,e.fillAmount));e.fillMethod===Cn.Horizontal?e.fillOrigin===An.Left?(n.uvScale.x=t,n.size.x*=t):(n.uvOffset.x=1-t,n.uvScale.x=t,n.size.x*=t):e.fillOrigin===An.Bottom?(n.uvScale.y=t,n.size.y*=t):(n.uvOffset.y=1-t,n.uvScale.y=t,n.size.y*=t)}t.insert(s,Q,n)}},{name:"ImageSystem"}))}},Fn=U("Toggle",{isOn:!0,graphicEntity:0,transition:null,enabled:!0});const Bn=new class{build(e){X("Toggle",Fn);const t=e.world;e.addSystemToSchedule(exports.Schedule.Update,Me([ge(on)],e=>{const s=t.getEntitiesWithComponents([Fn]);for(const n of s){if(t.has(n,en)||t.insert(n,en,{enabled:!0}),!t.has(n,tn))continue;const s=t.get(n,tn),r=t.get(n,Fn),o=t.get(n,en);if(s.justPressed&&o.enabled&&(r.isOn=!r.isOn,e.emit(n,"change")),r.graphicEntity&&t.valid(r.graphicEntity)){const e=r.graphicEntity;if(t.has(e,Q)){const s=t.get(e,Q);s.color.a=r.isOn?1:0,t.insert(e,Q,s)}}if(r.transition&&t.has(n,Q)){const e=t.get(n,Q),i=r.transition;o.enabled?s.pressed?e.color={...i.pressedColor}:s.hovered?e.color={...i.hoveredColor}:e.color={...i.normalColor}:e.color={...i.disabledColor},t.insert(n,Q,e)}}},{name:"ToggleSystem"}))}};var Dn;exports.ProgressBarDirection=void 0,(Dn=exports.ProgressBarDirection||(exports.ProgressBarDirection={}))[Dn.LeftToRight=0]="LeftToRight",Dn[Dn.RightToLeft=1]="RightToLeft",Dn[Dn.BottomToTop=2]="BottomToTop",Dn[Dn.TopToBottom=3]="TopToBottom";const kn=U("ProgressBar",{value:0,fillEntity:0,direction:exports.ProgressBarDirection.LeftToRight});const Ln=new class{build(e){X("ProgressBar",kn);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([],()=>{const e=t.getEntitiesWithComponents([kn,Us]);for(const s of e){const e=t.get(s,kn);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=e.fillEntity;if(!t.has(n,Us))continue;const r=t.get(n,Us),o=Math.max(0,Math.min(1,e.value));switch(e.direction){case exports.ProgressBarDirection.LeftToRight:r.anchorMin={x:0,y:0},r.anchorMax={x:o,y:1};break;case exports.ProgressBarDirection.RightToLeft:r.anchorMin={x:1-o,y:0},r.anchorMax={x:1,y:1};break;case exports.ProgressBarDirection.BottomToTop:r.anchorMin={x:0,y:0},r.anchorMax={x:1,y:o};break;case exports.ProgressBarDirection.TopToBottom:r.anchorMin={x:0,y:1-o},r.anchorMax={x:1,y:1}}r.offsetMin={x:0,y:0},r.offsetMax={x:0,y:0},t.insert(n,Us,r)}},{name:"ProgressBarSystem"}))}},Wn=U("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Un=U("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}}),$n=new Float32Array(16),zn=new Float32Array(16);let On=!0;function Hn(e,t,s){const n=e.mouseX*s,r=t.screenH-e.mouseY*s;return function(e){let t=!1;for(let s=0;s<16;s++)if(zn[s]!==e[s]){t=!0;break}t&&(zn.set(e),On=!0)}(t.viewProjection),On&&(Ys(t.viewProjection,$n),On=!1),Gs(n,r,$n,t.vpX,t.vpY,t.vpW,t.vpH)}const jn=new class{build(e){X("Draggable",Wn),X("DragState",Un);const t=e.world,s=e.getResource(on);let n=null,r={x:0,y:0},o=null;const i="undefined"!=typeof window&&window.devicePixelRatio||1;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([ge(Re),ge(Oe)],(e,a)=>{if(!a.valid)return;const l=Hn(e,a,i);if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Wn,tn]);let s=null;for(const n of e){if(!t.get(n,Wn).enabled)continue;t.get(n,tn).hovered&&(s=n)}if(null!==s){n=s,r={x:l.x,y:l.y},t.has(s,Un)||t.insert(s,Un);const e=t.get(s,Un),o=t.get(s,K);e.startWorldPos={x:o.position.x,y:o.position.y},e.currentWorldPos={x:o.position.x,y:o.position.y},e.pointerStartWorld={x:l.x,y:l.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==n&&!e.isMouseButtonDown(0)){if(t.valid(n)&&t.has(n,Un)){t.get(n,Un).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=l.x-r.x,i=l.y-r.y,c=Math.sqrt(e*e+i*i),d=t.get(n,Wn);if(c*(a.vpW/(a.worldRight-a.worldLeft))>=d.dragThreshold){o=n,n=null;t.get(o,Un).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Un))return void(o=null);const n=t.get(o,Un),r=t.get(o,Wn),i=l.x-n.pointerStartWorld.x,a=l.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+i,d=n.startWorldPos.y+a;const u=function(e,t,s,n){let r=e.lockX?t.startWorldPos.x:s,o=e.lockY?t.startWorldPos.y:n;return null!==e.constraintMin&&(r=Math.max(r,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(r=Math.min(r,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:r,y:o}}(r,n,c,d);c=u.x,d=u.y;const h=n.currentWorldPos.x,p=n.currentWorldPos.y;if(n.deltaWorld={x:c-h,y:d-p},n.currentWorldPos={x:c,y:d},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:d-n.startWorldPos.y},t.has(o,J)){const e=function(e,t,s,n){if(!e.has(t,se))return{x:s,y:n};const r=e.get(t,se).entity;if(!e.valid(r)||!e.has(r,K))return{x:s,y:n};const o=e.get(r,K),i=0!==o.scale.x?o.scale.x:1,a=0!==o.scale.y?o.scale.y:1,l=2*Math.atan2(o.rotation.z,o.rotation.w),c=Math.sin(-l),d=Math.cos(-l);return{x:(s*d-n*c)/i,y:(s*c+n*d)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,J);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,J,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},Xn=U("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135});const Nn=new class{build(e){X("ScrollView",Xn);const t=e.world,s=new Map,n=new Float32Array(16),r="undefined"!=typeof window&&window.devicePixelRatio||1;let o=0;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([ge(Re),ge(Oe)],(e,i)=>{const a=performance.now()/1e3,l=o>0?Math.min(a-o,.05):0;if(o=a,!i.valid)return;const c=e.mouseX*r,d=i.screenH-e.mouseY*r;Ys(i.viewProjection,n);const u=Gs(c,d,n,i.vpX,i.vpY,i.vpW,i.vpH),h=t.getEntitiesWithComponents([Xn,Us]);for(const n of h){t.has(n,en)||t.insert(n,en,{enabled:!0,blockRaycast:!0}),t.has(n,Xs)||t.insert(n,Xs,{enabled:!0,mode:"scissor"});const r=t.get(n,Xn),o=t.get(n,Us);let i=s.get(n);i||(i={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0},s.set(n,i));const a=t.has(n,tn)?t.get(n,tn):null;if(a?.justPressed&&(i.isDragging=!0,i.lastWorldX=u.x,i.lastWorldY=u.y,i.velocityX=0,i.velocityY=0),i.isDragging&&e.isMouseButtonDown(0)){const e=u.x-i.lastWorldX,t=u.y-i.lastWorldY;r.horizontalEnabled&&(r.scrollX-=e,i.velocityX=l>0?-e/l:0),r.verticalEnabled&&(r.scrollY-=t,i.velocityY=l>0?-t/l:0),i.lastWorldX=u.x,i.lastWorldY=u.y}if(i.isDragging&&e.isMouseButtonReleased(0)&&(i.isDragging=!1),a?.hovered){const t=e.getScrollDelta();r.verticalEnabled&&0!==t.y&&(r.scrollY+=.1*t.y,i.velocityY=0),r.horizontalEnabled&&0!==t.x&&(r.scrollX+=.1*t.x,i.velocityX=0)}if(!i.isDragging&&r.inertia&&l>0){const e=Math.pow(r.decelerationRate,l);r.horizontalEnabled&&Math.abs(i.velocityX)>.1?(r.scrollX+=i.velocityX*l,i.velocityX*=e):i.velocityX=0,r.verticalEnabled&&Math.abs(i.velocityY)>.1?(r.scrollY+=i.velocityY*l,i.velocityY*=e):i.velocityY=0}const c=o.size.x,d=o.size.y,h=Math.max(0,r.contentWidth-c),p=Math.max(0,r.contentHeight-d);if(r.scrollX=Math.max(0,Math.min(r.scrollX,h)),r.scrollY=Math.max(0,Math.min(r.scrollY,p)),0!==r.contentEntity&&t.valid(r.contentEntity)){const e=r.contentEntity;if(t.has(e,J)){const s=t.get(e,J);s.position.x=-r.scrollX,s.position.y=r.scrollY,t.insert(e,J,s)}}}},{name:"ScrollViewSystem"}))}};var Vn;exports.SliderDirection=void 0,(Vn=exports.SliderDirection||(exports.SliderDirection={}))[Vn.LeftToRight=0]="LeftToRight",Vn[Vn.RightToLeft=1]="RightToLeft",Vn[Vn.BottomToTop=2]="BottomToTop",Vn[Vn.TopToBottom=3]="TopToBottom";const Yn=U("Slider",{value:0,minValue:0,maxValue:1,direction:exports.SliderDirection.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1,enabled:!0});const Gn=new class{build(e){X("Slider",Yn);const t=e.world,s=new Float32Array(16),n="undefined"!=typeof window&&window.devicePixelRatio||1;let r=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([ge(Re),ge(Oe)],(e,o)=>{if(!o.valid)return;const i=e.mouseX*n,a=o.screenH-e.mouseY*n;Ys(o.viewProjection,s);const l=Gs(i,a,s,o.vpX,o.vpY,o.vpW,o.vpH),c=t.getEntitiesWithComponents([Yn,Us,K]);for(const s of c){t.has(s,en)||t.insert(s,en,{enabled:!0,blockRaycast:!0});const n=t.get(s,Yn),o=t.get(s,Us),i=t.get(s,K),a=t.has(s,tn)?t.get(s,tn):null;if(a?.justPressed&&(r=s),r===s&&e.isMouseButtonDown(0)){const e=o.size.x*i.scale.x,t=o.size.y*i.scale.y,s=i.position.x-o.pivot.x*e,r=i.position.y-o.pivot.y*t;let a;switch(n.direction){case exports.SliderDirection.LeftToRight:a=e>0?(l.x-s)/e:0;break;case exports.SliderDirection.RightToLeft:a=e>0?1-(l.x-s)/e:0;break;case exports.SliderDirection.BottomToTop:a=t>0?(l.y-r)/t:0;break;case exports.SliderDirection.TopToBottom:a=t>0?1-(l.y-r)/t:0}a=Math.max(0,Math.min(1,a));let c=n.minValue+a*(n.maxValue-n.minValue);n.wholeNumbers&&(c=Math.round(c)),n.value=Math.max(n.minValue,Math.min(n.maxValue,c))}r===s&&e.isMouseButtonReleased(0)&&(r=null);const c=n.maxValue-n.minValue,d=c>0?(n.value-n.minValue)/c:0;if(0!==n.fillEntity&&t.valid(n.fillEntity)){const e=n.fillEntity;if(t.has(e,Us)){const s=t.get(e,Us);switch(n.direction){case exports.SliderDirection.LeftToRight:s.anchorMin={x:0,y:0},s.anchorMax={x:d,y:1};break;case exports.SliderDirection.RightToLeft:s.anchorMin={x:1-d,y:0},s.anchorMax={x:1,y:1};break;case exports.SliderDirection.BottomToTop:s.anchorMin={x:0,y:0},s.anchorMax={x:1,y:d};break;case exports.SliderDirection.TopToBottom:s.anchorMin={x:0,y:1-d},s.anchorMax={x:1,y:1}}t.insert(e,Us,s)}}if(0!==n.handleEntity&&t.valid(n.handleEntity)){const e=n.handleEntity;if(t.has(e,Us)){const s=t.get(e,Us);switch(n.direction){case exports.SliderDirection.LeftToRight:s.anchorMin={x:d,y:0},s.anchorMax={x:d,y:1};break;case exports.SliderDirection.RightToLeft:s.anchorMin={x:1-d,y:0},s.anchorMax={x:1-d,y:1};break;case exports.SliderDirection.BottomToTop:s.anchorMin={x:0,y:d},s.anchorMax={x:1,y:d};break;case exports.SliderDirection.TopToBottom:s.anchorMin={x:0,y:1-d},s.anchorMax={x:1,y:1-d}}t.insert(e,Us,s)}}}},{name:"SliderSystem"}))}},qn=U("Focusable",{tabIndex:0,isFocused:!1});class Jn{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Kn=fe(new Jn,"FocusManager");const Qn=new class{build(e){X("Focusable",qn);const t=e.world,s=new Jn;e.insertResource(Kn,s),e.addSystemToSchedule(exports.Schedule.Update,Me([ge(Re),ge(on)],(e,n)=>{const r=t.getEntitiesWithComponents([qn]);for(const e of r){if(!t.has(e,tn))continue;t.get(e,tn).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const n=function(){const e=[];for(const s of r){const n=t.get(s,qn);e.push({entity:s,tabIndex:n.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===n.length)return;const i=null!==s.focusedEntity?n.findIndex(e=>e===s.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===i?a?n.length-1:0:a?(i-1+n.length)%n.length:(i+1)%n.length,o(n[l])}function o(e){const r=s.focusedEntity;if(r===e)return;if(null!==r&&t.valid(r)&&t.has(r,qn)){t.get(r,qn).isFocused=!1,n.emit(r,"hover_exit",r)}s.focus(e);t.get(e,qn).isFocused=!0,n.emit(e,"hover_enter",e)}},{name:"FocusSystem"}))}},Zn=U("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});const er=new class{build(e){X("SafeArea",Zn);const t=e.world;let s={top:0,bottom:0,left:0,right:0},n=0;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([],()=>{n++%60==0&&(s=function(){if("undefined"==typeof document)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}());const e=t.getEntitiesWithComponents([Zn,Us]);for(const n of e){const e=t.get(n,Zn),r=t.get(n,Us);let o=!1;const i=e.applyTop?s.top:0,a=e.applyBottom?s.bottom:0,l=e.applyLeft?s.left:0,c=e.applyRight?s.right:0;r.offsetMin.x===l&&r.offsetMin.y===a||(r.offsetMin={x:l,y:a},o=!0),r.offsetMax.x===-c&&r.offsetMax.y===-i||(r.offsetMax={x:-c,y:-i},o=!0),o&&t.insert(n,Us,r)}},{name:"SafeAreaSystem"}))}},tr=U("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2}),sr=new Map;const nr=new class{build(e){X("ListView",tr);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([ge(Re)],e=>{const s=t.getEntitiesWithComponents([tr,Us]);for(const n of s){t.has(n,en)||t.insert(n,en,{enabled:!0,blockRaycast:!0}),t.has(n,Xs)||t.insert(n,Xs,{enabled:!0,mode:"scissor"});let s=sr.get(n);s||(s={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},sr.set(n,s));const r=t.get(n,tr),o=t.get(n,Us),i=o.size.y,a=t.has(n,tn)?t.get(n,tn):null;if(a?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}const l=Math.max(0,r.itemCount*r.itemHeight-i);r.scrollY=Math.max(0,Math.min(r.scrollY,l));const c=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),d=Math.min(r.itemCount,Math.ceil((r.scrollY+i)/r.itemHeight)+r.overscan);for(const[e,n]of s.itemEntities)(e<c||e>=d)&&(t.valid(n)&&t.despawn(n),s.itemEntities.delete(e));for(let e=c;e<d;e++){let i=s.itemEntities.get(e);if(i&&t.valid(i)||(i=t.spawn(),t.insert(i,ie,{value:`ListItem_${e}`}),t.insert(i,Us,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o.size.x,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(i,n),s.itemEntities.set(e,i),s.renderer&&s.renderer(e,i)),t.has(i,J)){const s=t.get(i,J);s.position.y=-(e*r.itemHeight-r.scrollY),t.insert(i,J,s)}}s.visibleStart=c,s.visibleEnd=d}},{name:"ListViewSystem"}))}},rr=U("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const or=new class{build(e){X("Dropdown",rr);const t=e.world;e.addSystemToSchedule(exports.Schedule.Update,Me([ge(Re),ge(on)],(e,s)=>{const n=t.getEntitiesWithComponents([rr]);for(const o of n){t.has(o,en)||t.insert(o,en,{enabled:!0,blockRaycast:!0});const n=t.get(o,rr),i=t.has(o,tn)?t.get(o,tn):null;if(i?.justPressed&&(n.isOpen=!n.isOpen,r(n.listEntity,n.isOpen),s.emit(o,"change",o)),n.isOpen&&e.isMouseButtonPressed(0)&&!i?.hovered){0!==n.listEntity&&t.valid(n.listEntity)&&t.has(n.listEntity,tn)&&t.get(n.listEntity,tn).hovered||(n.isOpen=!1,r(n.listEntity,!1))}}function r(e,s){if(0===e)return;const n=e;if(!t.valid(n)||!t.has(n,J))return;const r=t.get(n,J),o=s?1:0;r.scale={x:o,y:o,z:o},t.insert(n,J,r)}},{name:"DropdownSystem"}))}};async function ir(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const ar=fe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),lr=fe(null,"PhysicsAPI");function cr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function dr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class ur{constructor(e,t={},s){this.wasmUrl_=e,this.factory_=s,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(ar,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=ir(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([ee]);for(const s of t){const t=e.world.get(s,ee);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,Me([ge(_e)],a=>{const l=i.getEntitiesWithComponents([le,J,K]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,le),l=i.get(r,K);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=cr(l.rotation);n._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),hr(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===he.Kinematic){const e=cr(l.rotation);n._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<n;r++){const n=o+4*r,i=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const d=e.world.get(i,J);if(!d)continue;let u=a,h=l,p=c;if(e.world.has(i,se)){const t=e.world.get(i,se);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,K)){const s=e.world.get(t.entity,K),n=cr(s.rotation),r=a-s.position.x,o=l-s.position.y,i=Math.cos(-n),d=Math.sin(-n);u=(r*i-o*d)/(0!==s.scale.x?s.scale.x:1),h=(r*d+o*i)/(0!==s.scale.y?s.scale.y:1),p=c-n}}d.position.x=u,d.position.y=h;const f=dr(p);d.rotation.w=f.w,d.rotation.x=f.x,d.rotation.y=f.y,d.rotation.z=f.z,e.world.insert(i,J,d)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<i;s++){const n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],d=t._physics_getSensorExitCount();if(d>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<d;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(ar,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(lr,pr._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function hr(e,t,s){const n=e.world;if(n.has(s,ce)){const e=n.get(s,ce);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,de)){const e=n.get(s,de);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,ue)){const e=n.get(s,ue);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class pr{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(pr.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function fr(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),o}function gr(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function mr(e,t,s,n){const r=e.scale.x*t*(s?-1:1),o=e.scale.y*t*(n?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,d=e.rotation.w,u=a+a,h=l+l,p=c+c,f=a*u,g=a*h,m=a*p,y=l*h,x=l*p,_=c*p,w=d*u,v=d*h,b=d*p;return new Float32Array([(1-(y+_))*r,(g+b)*r,(m-v)*r,0,(g-b)*o,(1-(f+_))*o,(x+w)*o,0,(m+v)*i,(x-w)*i,(1-(f+y))*i,0,e.position.x,e.position.y,e.position.z,1])}async function yr(e,t,s,n,r,o,i,a,l){const c=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==n[r])continue;try{n[r]=fr(e,await s.loadPixels(r))}catch{n[r]=0}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,c);let d={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),d=await async function(e,t,s,n,r){const o={};for(const i of n.entities)for(const n of i.components){if("SpineAnimation"!==n.type||!n.data)continue;const i=n.data.skeletonPath,a=n.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const n=await r.readText(a),d="binary"===g(l)?.contentType;let u,h;if(d){const e=await r.readBinary(i);h=e.length,u=t._malloc(h),t.HEAPU8.set(e,u)}else{const e=await r.readText(i),s=(new TextEncoder).encode(e);h=s.length,u=t._malloc(h+1),t.HEAPU8.set(s,u),t.HEAPU8[u+h]=0}const p=s.loadSkeleton(u,h,n,n.length,d);if(t._free(u),p<0)continue;o[i]=p;const f=gr(n),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=m+"/"+f[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),i=fr(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,s,n)),o){new ur("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const h=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,o;const i=g(r);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await s.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await s.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(r),o=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const l=o?`${o}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),d=fr(e,c,!1),u=e.getResourceManager();n[r]=u.loadBitmapFont(t,d,c.width,c.height)}catch{n[r]=0}}return n}(t,s,n),p=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=n[o];i||(i=Ke.createShader(e.vertexSource,e.fragmentSource),n[o]=i),s[r]=Ke.createFromAsset(e,i)}catch{s[r]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=ct(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,c,h,p);const f=dt(e.world,s);if(l&&e.hasResource(xs))for(const t of f.values())e.world.insert(t,ae,{scene:l,persistent:!1});if(r&&u){const n=function(e,t,s,n){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=s[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=n.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,s,d,f);!function(e,t,s,n,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,oe)?c.get(o,oe):null,d=!1!==a?.playing,u=a?.timeScale??1;d&&n.update(i,l*u);let h=0;if(c.has(o,K)){const e=mr(c.get(o,K),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=n.getMeshBatchCount(i);for(let e=0;e<p;e++){const r=n.getMeshBatchVertexCount(i,e),o=n.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=s._malloc(a),d=s._malloc(l),u=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(i,e,c,d,u,p);const f=s.HEAPU32[u>>2],g=s.HEAPU32[p>>2],m=new Float32Array(s.HEAPF32.buffer,c,8*r),y=new Uint16Array(s.HEAPU8.buffer,d,o),x=t._malloc(a),_=t._malloc(l);t.HEAPF32.set(m,x>>2),new Uint16Array(t.HEAPU8.buffer,_,o).set(y),t.renderer_submitTriangles(x,r,_,o,f,g,h),t._free(x),t._free(_),s._free(c),s._free(d),s._free(u),s._free(p)}h&&t._free(h)}})}(e,t,r,u,n)}if(a){const t=e.getResource(ft);t&&t.setAddressableManifest(a)}}class xr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,r=e.data.atlasPath;n&&("binary"===g(n)?.contentType?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of n){const t=g(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||o.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const _r="__preview__";const wr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=ls.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:ls.getTargetTexture(s),width:e.width,height:e.height}},release(e){ls.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(ls.releaseRenderTarget(e._handle),wr.create({width:t,height:s,depth:!0})),begin(e,t){ls.begin(t,e._handle)},end(){ls.end()},getDepthTexture:e=>ls.getTargetDepthTexture(e._handle)};let vr=!1;var br;exports.LogLevel=void 0,(br=exports.LogLevel||(exports.LogLevel={}))[br.Debug=0]="Debug",br[br.Info=1]="Info",br[br.Warn=2]="Warn",br[br.Error=3]="Error";class Sr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${exports.LogLevel[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case exports.LogLevel.Debug:console.debug(t,s);break;case exports.LogLevel.Info:console.log(t,s);break;case exports.LogLevel.Warn:console.warn(t,s);break;case exports.LogLevel.Error:console.error(t,s)}}}class Pr{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new Sr)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,s){this.log(exports.LogLevel.Debug,e,t,s)}info(e,t,s){this.log(exports.LogLevel.Info,e,t,s)}warn(e,t,s){this.log(exports.LogLevel.Warn,e,t,s)}error(e,t,s){this.log(exports.LogLevel.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Tr=new Pr;const Mr=[js,Zs,fn,In,Ln,vn,jn,Nn,Gn,Bn,Mn,Qn,er,nr,or];E||(E=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await l(s,n);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return c(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?s[n++]=r:r<2048?(s[n++]=192|r>>6,s[n++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,s[n++]=240|r>>18,s[n++]=128|r>>12&63,s[n++]=128|r>>6&63,s[n++]=128|63&r):(s[n++]=224|r>>12,s[n++]=128|r>>6&63,s[n++]=128|63&r)}return s.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=C,exports.App=bs,exports.AssetPlugin=gt,exports.AssetRefCounter=class{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let s=this.textureRefs_.get(e);s||(s=new Set,this.textureRefs_.set(e,s)),s.add(t)}removeTextureRef(e,t){const s=this.textureRefs_.get(e);s&&(s.delete(t),0===s.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let s=this.fontRefs_.get(e);s||(s=new Set,this.fontRefs_.set(e,s)),s.add(t)}removeFontRef(e,t){const s=this.fontRefs_.get(e);s&&(s.delete(t),0===s.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let s=this.materialRefs_.get(e);s||(s=new Set,this.materialRefs_.set(e,s)),s.add(t)}removeMaterialRef(e,t){const s=this.materialRefs_.get(e);s&&(s.delete(t),0===s.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,s]of this.textureRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllFontRefs(){const e=[];for(const[t,s]of this.fontRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllMaterialRefs(){const e=[];for(const[t,s]of this.materialRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}},exports.AssetServer=pt,exports.Assets=ft,exports.AsyncCache=it,exports.BitmapText=re,exports.BodyType=he,exports.BoxCollider=ce,exports.Button=nn,exports.Camera=Z,exports.Canvas=ee,exports.CapsuleCollider=ue,exports.Children=ne,exports.CircleCollider=de,exports.ClearFlags=G,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=Se,exports.DEFAULT_DESIGN_HEIGHT=R,exports.DEFAULT_DESIGN_WIDTH=A,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_TEXT_CANVAS_SIZE=512,exports.DragState=Un,exports.Draggable=Wn,exports.Draw=Dt,exports.Dropdown=rr,exports.EntityCommands=be,exports.FillMethod=Cn,exports.FillOrigin=An,exports.FocusManager=Kn,exports.FocusManagerState=Jn,exports.Focusable=qn,exports.GLDebug=hs,exports.Geometry=Jt,exports.INVALID_ENTITY=0,exports.INVALID_FONT=B,exports.INVALID_TEXTURE=F,exports.Image=Rn,exports.ImageType=En,exports.Input=Re,exports.InputPlugin=Ie,exports.InputState=Ae,exports.Interactable=en,exports.ListView=tr,exports.LocalTransform=J,exports.Logger=Pr,exports.Material=Ke,exports.MaterialLoader=at,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ie,exports.Parent=se,exports.Physics=pr,exports.PhysicsEvents=ar,exports.PhysicsPlugin=ur,exports.PostProcess=ts,exports.PrefabServer=vt,exports.Prefabs=bt,exports.PrefabsPlugin=St,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(xs);t.register({name:_r,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(_r),this.loadPromise_=t.load(_r).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await s(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new xr(this.baseUrl_);await n.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await yr(this.app_,this.app_.wasmModule,t,n,r,null,void 0,null,_r)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([Z]);for(const n of s){if(e.get(n,Z).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1.7777777777777777;const n=e.getEntitiesWithComponents([ee]);for(const r of n){const n=e.get(r,ee);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(xs).getScene(_r),o=r?r.spawn():e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(o,J,i);const a={isActive:!0,projectionType:Y.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:G.ColorAndDepth};e.insert(o,Z,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(xs);await e.switchTo(_r),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}},exports.ProgressBar=kn,exports.ProjectionType=Y,exports.Query=function(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{we(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)},exports.QueryInstance=ve,exports.RenderPipeline=ps,exports.RenderTexture=wr,exports.Renderer=ls,exports.Res=ge,exports.ResMut=me,exports.RigidBody=le,exports.RuntimeConfig=I,exports.SafeArea=Zn,exports.ScaleMode=q,exports.SceneManager=xs,exports.SceneManagerState=ys,exports.SceneOwner=ae,exports.ScreenSpace=an,exports.ScrollView=Xn,exports.ShaderSources=ot,exports.Slider=Yn,exports.SpineAnimation=oe,exports.Sprite=Q,exports.SystemRunner=Ce,exports.Text=Ws,exports.TextInput=bn,exports.TextInputPlugin=Sn,exports.TextPlugin=Hs,exports.TextRenderer=$s,exports.Time=_e,exports.Toggle=Fn,exports.UICameraInfo=Oe,exports.UIEventQueue=rn,exports.UIEvents=on,exports.UIInteraction=tn,exports.UIInteractionPlugin=wn,exports.UILayoutPlugin=pn,exports.UIMask=Xs,exports.UIMaskPlugin=Qs,exports.UIRect=Us,exports.Velocity=te,exports.WebAssetProvider=xr,exports.World=ze,exports.WorldTransform=K,exports.addStartupSystem=function(e){Ee().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){Ee().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){Ee().push({schedule:e,system:t})},exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=I.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=I.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=I.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=I.canvasMatchWidthOrHeight)},exports.assetPlugin=mt,exports.clearDrawCallbacks=Ot,exports.clearUserComponents=function(){W().clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeUIRectLayout=ln,exports.createMaskProcessor=Ks,exports.createRuntimeSceneConfig=function(e,t,s){return{name:e,data:t,async setup(){await yr(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}},exports.createWebApp=function(e,t){return function(e,t){const s=bs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Rt(e),Ge(e),Yt(e),Qt(e),is(e),ds(e);const r=new ps;s.setPipeline(r);let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function l(t,r,o){o||(o=Ts(e,n,t,r));const i=s.getResource(Oe);if(o.length>0){const e=o[0],s=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(s.x*t),i.vpY=Math.round((1-s.y-s.h)*r),i.vpW=Math.round(s.w*t),i.vpH=Math.round(s.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}s.insertResource(Oe,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();l(e,t)}},d={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=i();if(0===t||0===c)return;const d=e.registry_getCanvasEntity(n);if(d>=0){const e=n.getCanvas(d).backgroundColor;ls.setClearColor(e.x,e.y,e.z,e.w)}const u=(a()-o)/1e3;let h;if(ls.resize(t,c),ts.isInitialized()&&ts.getPassCount()>0&&!ts.isBypassed()&&ts.resize(t,c),s.hasResource(xs)){const e=s.getResource(xs).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const p=Ts(e,n,t,c,s.world,h);if(l(t,c,p),0===p.length)r.render({registry:{_cpp:n},viewProjection:Ss,width:t,height:c,elapsed:u});else{for(const e of p){const s=e.viewportRect,o=Math.round(s.x*t),i=Math.round((1-s.y-s.h)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:l},clearFlags:e.clearFlags,elapsed:u})}ls.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(exports.Schedule.First,c),s.addSystemToSchedule(exports.Schedule.Last,d),s.addPlugin(mt),s.addPlugin(Pt),s.addPlugin(Fe),s.addPlugin(vs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Mr,...t})},exports.debug=function(e,t,s){Tr.debug(e,t,s)},exports.defineComponent=U,exports.defineResource=fe,exports.defineSystem=Me,exports.defineTag=$,exports.error=function(e,t,s){Tr.error(e,t,s)},exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([ie]);for(const n of s){const s=e.get(n,ie);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}},exports.getAddressableType=function(e){return g(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of d)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return p},exports.getAssetMimeType=function(e){return u[e.toLowerCase()]},exports.getAssetTypeEntry=g,exports.getComponent=N,exports.getComponentAssetFields=function(e){const t=lt.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s},exports.getComponentDefaults=function(e){const t=N(e);return t?D(t._default):null},exports.getCustomExtensions=y,exports.getEditorType=function(e){return g(e)?.editorType??"unknown"},exports.getLogger=function(){return Tr},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=z,exports.getWeChatPackOptions=function(){return y().map(e=>({type:"suffix",value:e}))},exports.info=function(e,t,s){Tr.info(e,t,s)},exports.initDrawAPI=Rt,exports.initGLDebugAPI=ds,exports.initGeometryAPI=Yt,exports.initMaterialAPI=Ge,exports.initPostProcessAPI=Qt,exports.initRendererAPI=is,exports.inputPlugin=Fe,exports.instantiatePrefab=yt,exports.intersectRects=Ns,exports.invertMatrix4=Ys,exports.isBuiltinComponent=H,exports.isCustomExtension=x,exports.isEditor=function(){return vr},exports.isKnownAssetExtension=m,exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!vr},exports.isTextureRef=je,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=ht,exports.loadPhysicsModule=ir,exports.loadRuntimeScene=yr,exports.loadSceneData=dt,exports.loadSceneWithAssets=ut,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&m(f(e)))},exports.platformFetch=s,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,s){return t().instantiateWasm(e,s)},exports.platformReadFile=n,exports.platformReadTextFile=r,exports.pointInOBB=qs,exports.pointInWorldRect=function(e,t,s,n,r,o,i,a){return e>=s-r*i&&e<=s+r*(1-i)&&t>=n-o*a&&t<=n+o*(1-a)},exports.prefabsPlugin=Pt,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerComponent=X,exports.registerComponentAssetFields=function(e,t){lt.set(e,t)},exports.registerDrawCallback=$t,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(ft);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=rt,exports.sceneManagerPlugin=vs,exports.screenToWorld=Gs,exports.setEditorMode=function(e){vr=e},exports.setListViewRenderer=function(e,t){const s=sr.get(e);s&&(s.renderer=t)},exports.setLogLevel=function(e){Tr.setMinLevel(e)},exports.setWasmErrorHandler=We,exports.shutdownDrawAPI=It,exports.shutdownGLDebugAPI=us,exports.shutdownGeometryAPI=Gt,exports.shutdownMaterialAPI=qe,exports.shutdownPostProcessAPI=Zt,exports.shutdownRendererAPI=as,exports.textInputPlugin=Mn,exports.textPlugin=js,exports.transitionTo=async function(e,t,s){const n=e.getResource(xs);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=vn,exports.uiLayoutPlugin=fn,exports.uiMaskPlugin=Zs,exports.uiPlugins=Mr,exports.unregisterComponent=function(e){W().delete(e)},exports.unregisterDrawCallback=zt,exports.updateCameraAspectRatio=function(e,t){const s=e.getEntitiesWithComponents([Z]);for(const n of s){const s=e.get(n,Z);s&&(s.aspectRatio=t,e.insert(n,Z,s))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),exports.vec4=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),exports.warn=function(e,t,s){Tr.warn(e,t,s)},exports.worldRectToScreen=Vs,exports.wrapSceneSystem=_s,exports.wxFileExists=P,exports.wxFileExistsSync=function(e){const t=w();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=M,exports.wxLoadImage=T,exports.wxLoadImagePixels=async function(e){return M(await T(e))},exports.wxReadFile=b,exports.wxReadTextFile=S,exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{w().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};
//# 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 5a14e8e4d..40982b3ee 100644
--- a/desktop/public/sdk/cjs/index.wechat.js
+++ b/desktop/public/sdk/cjs/index.wechat.js
@@ -1,2 +1,2 @@
-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function h(e,n){return t().instantiateWasm(e,n)}function d(e,n){return t().createCanvas(e,n)}function u(){return t().now()}function f(e,t){return new Promise((n,s)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];n({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,n="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(n).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function p(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const n=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(n,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${n}": ${t}`)}}const g=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],y={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},m=new Map,_=new Set;for(const e of g)for(const t of e.extensions)m.set(t,e),_.add(t);function w(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function x(e){return m.get(w(e))}function v(e){return x(e)?.editorType??"unknown"}function b(e){return x(e)?.addressableType??null}function S(e){for(const t of g)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function P(e){return _.has(e.toLowerCase())}function M(){return _}function T(e){return"string"==typeof e&&(!!e.includes("/")&&P(w(e)))}function E(){const e=[];for(const t of g)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function C(){return E().map(e=>({type:"suffix",value:e}))}function R(e){return y[e.toLowerCase()]}function A(e){const t=x(e);return t?.wechatPackInclude??!1}let F=null;function I(){return F||(F=wx.getFileSystemManager()),F}function B(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if(A(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return n.includes("no such file")||n.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function k(e){return new Promise((t,n)=>{I().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(B(e,t.errMsg)))}})})}function $(e,t="utf-8"){return new Promise((n,s)=>{I().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(B(e,t.errMsg)))}})})}function W(e){return new Promise(t=>{I().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function D(e){const t=I();try{return t.accessSync(e),!0}catch{return!1}}function U(e,t){return new Promise((n,s)=>{I().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function z(e){return new Promise((t,n)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>n(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function L(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){const n=wx.createCanvas();n.width=e,n.height=t;const s=n.getContext("2d");return{canvas:n,ctx:s}}(t,n);s.clearRect(0,0,t,n),s.drawImage(e,0,0);const r=s.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(r.data.buffer)}}async function O(e){return L(await z(e))}let H=!1;const j=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return k(e)}async readTextFile(e){return $(e)}async fileExists(e){return W(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return p(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const n=wx.createCanvas();return n.width=e,n.height=t,n}now(){return Date.now()}bindInputEvents(e,t){const{pixelRatio:n}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX*n,s.clientY*n)}),wx.onTouchMove(t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX*n,s.clientY*n)}),wx.onTouchEnd(t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)})}},X=1920,Y=1080,N=100,V=512,q={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function G(e){e.Text&&(e.Text._default.fontFamily=q.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=q.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=q.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=q.canvasMatchWidthOrHeight)}const J=0,K=4294967295,Q=4294967295,Z=(e=0,t=0)=>({x:e,y:t}),ee=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),te=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),ne=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),se=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function re(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(re);const t={};for(const n in e)t[n]=re(e[n]);return t}let oe=0;function ie(e,t){const n=++oe;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...re(t),...e}:re(t)}}function ae(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function le(e,t){const n=ae(),s=n.get(e);if(s)return s;const r=ie(e,t);return n.set(e,r),fe(e,t,!1),r}function ce(e){const t=ae(),n=t.get(e);if(n)return n;const s=ie(e,{});return t.set(e,s),fe(e,{},!0),s}function he(e){return ae().get(e)}function de(){ae().clear()}function ue(e){ae().delete(e)}function fe(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function pe(e){return!0===e._builtin}const ge=new Map;function ye(e,t){ge.set(e,t)}function me(e){return ge.get(e)??he(e)}function _e(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return ge.set(e,n),n}const we={Perspective:0,Orthographic:1},xe={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ve={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},be=_e("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Se=_e("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Pe=_e("Sprite",{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),Me=_e("Camera",{projectionType:we.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:xe.ColorAndDepth}),Te=_e("Canvas",{designResolution:{x:X,y:Y},pixelsPerUnit:100,scaleMode:ve.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Ee=_e("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Ce=_e("Parent",{entity:0}),Re=_e("Children",{entities:[]}),Ae=_e("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:Q}),Fe=_e("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),Ie={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},Be=le("SceneOwner",{scene:"",persistent:!1});function ke(e){const t=me(e);return t?re(t._default):null}ye("Name",Ie);const $e=_e("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),We=_e("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),De=_e("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),Ue=_e("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ze={Static:0,Kinematic:1,Dynamic:2};let Le=0;function Oe(e,t){const n=++Le;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function He(e){return{_type:"res",_resource:e}}function je(e){return{_type:"res_mut",_resource:e}}class Xe{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class Ye{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new Xe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Ne=Oe({delta:0,elapsed:0,frameCount:0},"Time");function Ve(e){return{_type:"mut",_component:e}}function qe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Ge(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{qe(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class Je{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>qe(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=n.length,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let h=null;this.world_.beginIteration();try{for(const d of s){if(null!==h&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(h,t.component,t.data)}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(d,t[n])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,n[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];h=d}yield a}}finally{if(this.world_.endIteration(),null!==h&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(h,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function Ke(){return{_type:"commands"}}class Qe{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=pe(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Ze{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Qe(this,null);return this.spawned_.push(e),e}entity(e){return new Qe(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var et;!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(et||(et={}));let tt=0;function nt(e,t,n){const s=++tt;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function st(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function rt(e){st().push({schedule:et.Update,system:e})}function ot(e){st().push({schedule:et.Startup,system:e})}function it(e,t){st().push({schedule:e,system:t})}class at{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Ze&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new Je(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Ze(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class lt{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const ct=Oe(new lt,"Input");class ht{constructor(e){this.target_=e??null}build(e){const n=new lt;e.insertResource(ct,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(et.Last,nt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const dt=new ht;function ut(e,t,n){const s=[];for(const[e,r]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const n=ft(t[e]),o=ft(r);"null"!==n&&"undefined"!==n&&(n!==o&&null!=r&&s.push({field:e,expected:n,actual:o,value:r}))}return s}function ft(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function pt(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let gt=null;function yt(e){gt=e}function mt(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),gt&&gt(e,t)}function _t(e){const t={};for(const n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:_t(e)}}return t}class wt{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw mt(e,"spawn"),e}else e=this.entities_.size+1;return this.entities_.add(e),e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){mt(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t)this.tsStorage_.get(n)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(n){mt(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){mt(t,`removeParent(entity=${e})`)}}insert(e,t,n){return pe(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return pe(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return pe(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(pe(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return mt(n,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");pe(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_;return t={add:n[`add${e}`].bind(n),get:n[`get${e}`].bind(n),has:n[`has${e}`].bind(n),remove:n[`remove${e}`].bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const e=ut(t._name,t._default,s);if(e.length>0)throw new Error(pt(t._name,e))}const r={...t._default,...s};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,_t(r))}catch(n){mt(n,`insertBuiltin(${t._name}, entity=${e})`)}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return this.getBuiltinMethods(t._cppName).get(e)}catch(n){return mt(n,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(n){return mt(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){mt(n,`removeBuiltin(${t._name}, entity=${e})`)}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const r=ut(t._name,t._default,e);if(r.length>0)throw new Error(pt(t._name,r));s=e}const r=t.create(s);this.getStorage(t).set(e,r),this.worldVersion_++;let o=this.entityComponents_.get(e);return o||(o=[],this.entityComponents_.set(e,o)),-1===o.indexOf(t._id)&&o.push(t._id),r}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getComponentTypes(e){const t=[];for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.push(n)}catch{}if(this.cppRegistry_)for(const[n,s]of ge)if(pe(s)&&!t.includes(n))try{this.getBuiltinMethods(s._cppName).has(e)&&t.push(n)}catch{}const n=this.entityComponents_.get(e);if(n){const e="undefined"!=typeof window?window.__esengine_componentRegistry:void 0;if(e)for(const s of n)for(const[n,r]of e)if(r._id===s){t.push(n);break}}return t}getEntitiesWithComponents(e,t=[],n=[]){if(0===e.length&&0===t.length&&0===n.length)return this.getAllEntities();let s=e.map(e=>e._name).sort().join(",");t.length>0&&(s+="|+"+t.map(e=>e._name).sort().join(",")),n.length>0&&(s+="|-"+n.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(s);if(r&&r.version===this.worldVersion_)return r.result;let o=null,i=1/0;for(const t of e)if(!pe(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<i&&(i=n,o=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const l=o?o.keys():this.entities_;for(const t of l){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&a.push(t)}return this.queryCache_.set(s,{version:this.worldVersion_,result:a}),a}}const xt=Oe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var vt;function bt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}!function(e){e[e.Normal=0]="Normal",e[e.Additive=1]="Additive",e[e.Multiply=2]="Multiply",e[e.Screen=3]="Screen",e[e.PremultipliedAlpha=4]="PremultipliedAlpha"}(vt||(vt={}));let St=null,Pt=null,Mt=1;const Tt=new Map;function Et(e){St=e,Pt=e.getResourceManager(),Dt()}function Ct(){0!==It&&St&&(St._free(It),It=0),Tt.clear(),Mt=1,Ft=!1,kt.clear(),$t=null,Pt=null,St=null}function Rt(){if(!Pt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Pt}const At={createShader:(e,t)=>Rt().createShader(e,t),releaseShader(e){e>0&&Rt().releaseShader(e)},create(e){const t=Mt++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??vt.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return Tt.set(t,n),t},get:e=>Tt.get(e),setUniform(e,t,n){const s=Tt.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=Tt.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Tt.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Tt.get(e);return t?.blendMode??vt.Normal},setDepthTest(e,t){const n=Tt.get(e);n&&(n.depthTest=t)},getShader(e){const t=Tt.get(e);return t?.shader??0},release(e){Tt.delete(e)},isValid:e=>Tt.has(e),releaseAll(){Tt.clear()},createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??vt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Tt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Mt++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Tt.set(n,s),n},toAssetData(e,t){const n=Tt.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=Tt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ft=!1,It=0;const Bt=4096,kt=new Map;let $t=null;function Wt(e){const t=(0===It&&St&&(It=St._malloc(Bt)),It);if(0===t||!St)return{ptr:0,count:0};let n=0,s=0;const r=St.HEAPU8,o=St.HEAPU32,i=St.HEAPF32;for(const[a,l]of e){if(n+128>Bt)break;let e=kt.get(a);e||($t||($t=new TextEncoder),e=$t.encode(a),kt.set(a,e));const c=e.length,h=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=h;let d=0,u=[0,0,0,0];if("number"==typeof l)d=0,u[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)u[e]=l[e]}else"w"in l?(d=3,u=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,u=[l.x,l.y,l.z,0]):"y"in l&&(d=1,u=[l.x,l.y,0,0]);o[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=u[e],n+=4;s++}return{ptr:t,count:s}}function Dt(){if(!St||Ft)return;St.materialDataProvider=(e,t,n,s,r)=>{const o=Tt.get(e);if(!o)return St.HEAPU32[t>>2]=0,St.HEAPU32[n>>2]=0,St.HEAPU32[s>>2]=0,void(St.HEAPU32[r>>2]=0);St.HEAPU32[t>>2]=o.shader,St.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Wt(o.uniforms);St.HEAPU32[s>>2]=i,St.HEAPU32[r>>2]=a},Ft=!0}const Ut={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class zt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const s=t(),r=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{o.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Lt{constructor(e,t=""){this.cache_=new zt,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(At.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())At.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(r);return{handle:At.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}const Ot=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}]]);function Ht(e,t){Ot.set(e,t)}function jt(e){const t=Ot.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function Xt(e){return Ot.get(e)?.fields??[]}function Yt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,Ie,{value:s.name}),!1!==s.visible)for(const n of s.components)Vt(e,t,n,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function Nt(e,t,n){const s=new Map,r=n?.assetServer,o=n?.assetBaseUrl,i=new Map;r&&await async function(e,t,n,s){e=JSON.parse(JSON.stringify(e));const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ot.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,h=new Map,d=new Map,u=[];for(const e of r)u.push((async()=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)u.push((async()=>{try{const s=await t.loadMaterial(e,n);h.set(e,s.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),h.set(e,0)}})());for(const e of i)u.push((async()=>{try{const s=await t.loadBitmapFont(e,n);d.set(e,s)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.set(e,0)}})());for(const e of a)u.push((async()=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)})());await Promise.all(u);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ot.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":n[e.field]=c.get(t)??0;break;case"material":n[e.field]=h.get(t)??0;break;case"font":n[e.field]=d.get(t)??0}}}}(t,r,o,i);for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,Ie,{value:n.name}),!1!==n.visible)for(const s of n.components)Vt(e,t,s,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function Vt(e,t,n,s){if("UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=me(n.type);if(r)e.insert(t,r,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function qt(e,t){const n=e.getEntitiesWithComponents([Me]);for(const s of n){const n=e.get(s,Me);n&&(n.aspectRatio=t,e.insert(s,Me,n))}}function Gt(e,t){const n=e.getEntitiesWithComponents([Ie]);for(const s of n){const n=e.get(s,Ie);if(n&&n.value===t)return s}return null}class Jt{constructor(e){this.textureCache_=new zt,this.shaderCache_=new zt,this.jsonCache_=new zt,this.textCache_=new zt,this.binaryCache_=new zt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new zt,this.prefabCache_=new zt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.module_=e,this.canvas_=d(q.textCanvasSize,q.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Lt(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);if(!r)continue;const o=(this.textureRefCounts_.get(s)??1)-1;o<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),At.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),h="binary"===x(e)?.contentType,d=h?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,h);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),r=l.find(e=>e.name===n);if(r){const n=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,r.info.width,r.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=x(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return Nt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const r=s.metadata?.atlas;r&&n.push(this.loadSpine(s.path,r).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??n;return new Promise((n,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return At.createShader(s,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:o}=this.parseEsShader(s);if(!r||!o)throw new Error(`Invalid shader format: ${e}`);return At.createShader(r,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Kt=Oe(null,"Assets");class Qt{build(e){const t=e.wasmModule;t?e.insertResource(Kt,new Jt(t)):console.warn("AssetPlugin: No WASM module available")}}const Zt=new Qt;class en{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function tn(e,t){const n=e.getResource(Kt);n&&n.registerEmbeddedAssets(t)}async function nn(e,t,n){const{entities:s,rootId:r}=await rn(t,n?.overrides??[],n,void 0,new Set),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await Nt(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}const sn=10;async function rn(e,t,n,s,r,o=0){if(o>sn)throw new Error(`Prefab nesting depth exceeded ${sn}. Check for deep or circular nesting in: ${e.name}`);const i=new Map;let a;if(void 0===s){a=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=s;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(r?.has(s.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${s.nestedPrefab.prefabPath}`);continue}r?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await rn(e,s.nestedPrefab.overrides,n,a,r,o+1);i.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?i.get(s.parent)??null:null),l.push(...t.entities);continue}const c=i.get(s.prefabEntityId),h=s.prefabEntityId===e.rootEntityId,d={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:h?null:null!==s.parent?i.get(s.parent)??null:null,children:s.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};on(d,t),l.push(d)}const c=i.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function on(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class an{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,r=await this.assetServer_.loadPrefab(s,t?.baseUrl);return nn(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const ln=Oe(null,"Prefabs");class cn{constructor(){this.name="PrefabsPlugin",this.dependencies=[Kt]}build(e){const t=e.getResource(Kt);e.insertResource(ln,new an(e.world,t))}}const hn=new cn;let dn=null,un=0,fn=0,pn=0;const gn=new Float32Array(256);function yn(e){dn=e,un=dn._malloc(64),fn=dn._malloc(64),pn=dn._malloc(1024)}function mn(){dn&&(un&&(dn._free(un),un=0),fn&&(dn._free(fn),fn=0),pn&&(dn._free(pn),pn=0)),dn=null}function _n(){if(!dn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return dn}const wn={r:1,g:1,b:1,a:1},xn={begin(e){const t=_n();try{t.HEAPF32.set(e,un/4),t.draw_begin(un)}catch(e){mt(e,"Draw.begin")}},end(){try{_n().draw_end()}catch(e){mt(e,"Draw.end")}},line(e,t,n,s=1){try{_n().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){mt(e,"Draw.line")}},rect(e,t,n,s=!0){try{_n().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){mt(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{_n().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){mt(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,r=32){try{_n().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)}catch(e){mt(e,"Draw.circle")}},circleOutline(e,t,n,s=1,r=32){try{_n().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)}catch(e){mt(e,"Draw.circleOutline")}},texture(e,t,n,s=wn){try{_n().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){mt(e,"Draw.texture")}},textureRotated(e,t,n,s,r=wn){try{_n().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)}catch(e){mt(e,"Draw.textureRotated")}},setLayer(e){_n().draw_setLayer(e)},setDepth(e){_n().draw_setDepth(e)},getDrawCallCount:()=>dn?dn.draw_getDrawCallCount():0,getPrimitiveCount:()=>dn?dn.draw_getPrimitiveCount():0,setBlendMode(e){_n().draw_setBlendMode(e)},setDepthTest(e){_n().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=_n();s.HEAPF32.set(n,fn/4),s.draw_mesh(e,t,fn)}catch(n){mt(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=_n(),r=At.get(t);if(!r)return;if(xn.setBlendMode(r.blendMode),xn.setDepthTest(r.depthTest),0===r.uniforms.size)return void xn.drawMesh(e,r.shader,n);let o;if(s.HEAPF32.set(n,fn/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,n]of r.uniforms){const s=Sn(t);if(!(s<0)){if(bt(n))gn[o++]=10,gn[o++]=s,gn[o++]=n.slot??e++,gn[o++]=n.textureId;else if("number"==typeof n)gn[o++]=1,gn[o++]=s,gn[o++]=n;else if(Array.isArray(n)){gn[o++]=n.length,gn[o++]=s;for(let e=0;e<n.length;e++)gn[o++]=n[e]}else"w"in n?(gn[o++]=4,gn[o++]=s,gn[o++]=n.x,gn[o++]=n.y,gn[o++]=n.z,gn[o++]=n.w):"z"in n?(gn[o++]=3,gn[o++]=s,gn[o++]=n.x,gn[o++]=n.y,gn[o++]=n.z):(gn[o++]=2,gn[o++]=s,gn[o++]=n.x,gn[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(gn.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void s.draw_mesh(e,r.shader,fn);s.HEAPF32.set(r.cachedBuffer_.subarray(0,o),pn/4),s.draw_meshWithUniforms(e,r.shader,fn,pn,o)}catch(n){mt(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},vn={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17},bn=new Set;function Sn(e){const t=vn[e];return void 0!==t?t:(bn.has(e)||(bn.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(vn).join(", ")}`)),-1)}const Pn=new Map;function Mn(e,t,n){Pn.set(e,{fn:t,scene:n??""})}function Tn(e){Pn.delete(e)}function En(){Pn.clear()}var Cn;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(Cn||(Cn={}));let Rn=null,An=0,Fn=0,In=0;function Bn(e){Rn=e,An=Rn._malloc(262144),Fn=Rn._malloc(65536),In=Rn._malloc(256)}function kn(){Rn&&(An&&Rn._free(An),Fn&&Rn._free(Fn),In&&Rn._free(In),An=0,Fn=0,In=0),Rn=null}function $n(){if(!Rn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Rn}const Wn={create(e){const t=$n(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,An/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,In,r).set(o),t.geometry_init(n,An,s,In,r,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Fn,s).set(e.indices),t.geometry_setIndices16(n,Fn,s)}else{new Uint32Array(t.HEAPU8.buffer,Fn,s).set(e.indices),t.geometry_setIndices32(n,Fn,s)}}return n},updateVertices(e,t,n=0){const s=$n(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,An/4),s.geometry_updateVertices(e,An,r,n)},release(e){e>0&&$n().geometry_release(e)},isValid:e=>!(!Rn||e<=0)&&Rn.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Wn.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:Cn.Float2},{name:"a_texCoord",type:Cn.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;n.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return Wn.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Cn.Float2},{name:"a_texCoord",type:Cn.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-n);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return Wn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Cn.Float2},{name:"a_texCoord",type:Cn.Float2}],indices:new Uint16Array(i)})}};let Dn=null;function Un(e){Dn=e}function zn(){Dn&&On.isInitialized()&&On.shutdown(),Dn=null}function Ln(){if(!Dn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Dn}const On={init(e,t){try{return Ln().postprocess_init(e,t)}catch(n){return mt(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ln().postprocess_shutdown()}catch(e){mt(e,"PostProcess.shutdown")}},resize(e,t){try{Ln().postprocess_resize(e,t)}catch(n){mt(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Ln().postprocess_addPass(e,t)}catch(t){return mt(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Ln().postprocess_removePass(e)}catch(t){mt(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Ln().postprocess_setPassEnabled(e,t)}catch(t){mt(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Ln().postprocess_isPassEnabled(e)}catch(t){return mt(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{Ln().postprocess_setUniformFloat(e,t,n)}catch(n){mt(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{Ln().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){mt(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Ln().postprocess_begin()}catch(e){mt(e,"PostProcess.begin")}},end(){try{Ln().postprocess_end()}catch(e){mt(e,"PostProcess.end")}},getPassCount(){try{return Ln().postprocess_getPassCount()}catch(e){return mt(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Dn)return!1;try{return Dn.postprocess_isInitialized()}catch(e){return mt(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ln().postprocess_setBypass(e)}catch(e){mt(e,"PostProcess.setBypass")}},isBypassed(){if(!Dn)return!0;try{return Dn.postprocess_isBypassed()}catch(e){return mt(e,"PostProcess.isBypassed"),!0}},createBlur:()=>At.createShader(Hn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>At.createShader(Hn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>At.createShader(Hn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>At.createShader(Hn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},Hn="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var jn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(jn||(jn={}));let Xn=null,Yn=0;function Nn(e){Xn=e,Yn=Xn._malloc(64)}function Vn(){Xn&&Yn&&(Xn._free(Yn),Yn=0),Xn=null}const qn={init(e,t){Xn?.renderer_init(e,t)},resize(e,t){Xn?.renderer_resize(e,t)},begin(e,t){if(Xn&&Yn)try{Xn.HEAPF32.set(e,Yn/4),Xn.renderer_begin(Yn,t??0)}catch(e){mt(e,"Renderer.begin")}},flush(){try{Xn?.renderer_flush()}catch(e){mt(e,"Renderer.flush")}},end(){try{Xn?.renderer_end()}catch(e){mt(e,"Renderer.end")}},submitSprites(e){if(Xn)try{Xn.renderer_submitSprites(e._cpp)}catch(e){mt(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Xn)try{Xn.renderer_submitBitmapText(e._cpp)}catch(e){mt(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Xn)try{Xn.renderer_submitSpine?.(e._cpp)}catch(e){mt(e,"Renderer.submitSpine")}},setStage(e){Xn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Xn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Xn?.renderer_releaseTarget(e)},getTargetTexture:e=>Xn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Xn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Xn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Xn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){Xn?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){Xn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Xn?Xn.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Xn?{drawCalls:Xn.renderer_getDrawCalls(),triangles:Xn.renderer_getTriangles(),sprites:Xn.renderer_getSprites(),text:Xn.renderer_getText(),spine:Xn.renderer_getSpine?.()??0,meshes:Xn.renderer_getMeshes(),culled:Xn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Gn=null;function Jn(e){Gn=e}function Kn(){Gn=null}const Qn={enable(){Gn?.gl_enableErrorCheck(!0)},disable(){Gn?.gl_enableErrorCheck(!1)},check:e=>Gn?.gl_checkErrors(e)??0,diagnose(){Gn?.renderer_diagnose()}};class Zn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(qn.resize(s,r),On.isInitialized()&&On.getPassCount()>0&&On.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),qn.setViewport(0,0,s,r),qn.clearBuffers(3),qn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),qn.submitSprites(t),qn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):qn.submitSpine(t),qn.flush(),this.executeDrawCallbacks(n,o),qn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;qn.setViewport(s.x,s.y,s.w,s.h),qn.setScissor(s.x,s.y,s.w,s.h,!0),qn.clearBuffers(r),qn.setScissor(0,0,0,0,!1),qn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),qn.submitSprites(t),qn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):qn.submitSpine(t),qn.flush(),this.executeDrawCallbacks(n,o),qn.end()}executeDrawCallbacks(e,t){const n=Pn;if(n.size>0){xn.begin(e);const s=[];for(const[e,r]of n.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}xn.end();for(const e of s)Tn(e)}}}const es="__scene_transition_overlay__";class ts{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class ns{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,Be,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),Mn(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=On.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){On.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,Be)){const n=this.app_.world.get(e,Be);n.persistent=t,this.app_.world.insert(e,Be,n)}}}class ss{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_)return void console.warn(`[SceneManager] Transition already in progress, ignoring switchTo("${e}")`);"fade"!==(t?.transition??"none")?(this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)):await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(n=>{const s=t.duration??q.sceneTransitionDuration,r=t.color??{...q.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:r,targetScene:e,options:t,resolve:n},Mn(es,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;xn.setLayer(9999),xn.setDepth(9999),xn.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{n&&n!==e&&await this.unload(n,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,Tn(es)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Tn(es),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new ts(t);this.scenes_.set(e,n);const s=new ns(n,this.app_);this.contexts_.set(e,s);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Kt)?this.app_.getResource(Kt):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Kt)&&(t.assetServer=this.app_.getResource(Kt));const s=await Nt(this.app_.world,r,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,Be,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=os(this.app_,e,s);this.app_.addSystemToSchedule(n,t)}return t.setup&&await t.setup(s),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new ts(t);this.scenes_.set(e,n);const s=new ns(n,this.app_);this.contexts_.set(e,s);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Kt)?this.app_.getResource(Kt):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Kt)&&(t.assetServer=this.app_.getResource(Kt));const s=await Nt(this.app_.world,r,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,Be,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=os(this.app_,e,s);this.app_.addSystemToSchedule(n,t)}return t.setup&&await t.setup(s),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const r=t?.keepPersistent??!0;for(const e of n.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,Be)){if(this.app_.world.get(e,Be).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())Tn(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{On.removePass(e)}catch{}n.postProcessPasses.length=0,this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(t&&"running"===t.status){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Pe)){const n=this.app_.world.get(e,Pe);t.savedAlphas.set(e,n.color.a),n.color={...n.color,a:0},this.app_.world.insert(e,Pe,n)}}}wake(e){const t=this.scenes_.get(e);if(t&&"sleeping"===t.status){t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Pe)){const n=this.app_.world.get(e,Pe),s=t.savedAlphas.get(e)??1;n.color={...n.color,a:s},this.app_.world.insert(e,Pe,n)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{On.setEnabled(n,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,n]of this.scenes_)"running"===n.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const rs=Oe(null,"SceneManager");function os(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(rs).getSceneStatus(t)&&n._fn(...s)}}}const is=nt([je(rs),He(Ne)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),as={name:"SceneManager",build(e){const t=new ss(e);e.insertResource(rs,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(rs),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(et.Startup,n),e.addSystemToSchedule(et.Last,is)}};class ls{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=u(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(et.Last);else{this.runSchedule(et.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(et.FixedPreUpdate),this.runSchedule(et.FixedUpdate),this.runSchedule(et.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(et.PreUpdate),this.runSchedule(et.Update),this.runSchedule(et.PostUpdate),this.runSchedule(et.Last),this.step_pending_&&(this.step_pending_=!1)}requestAnimationFrame(this.mainLoop)},this.world_=new wt,this.resources_=new Ye;for(const e of Object.values(et))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new ls}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(et.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(et.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return yt(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(rs).register(e),this}setInitialScene(e){return this.getResource(rs).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new at(this.world_,this.resources_),this.resources_.insert(Ne,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(et.Startup),this.lastTime_=u(),this.mainLoop())}quit(){this.running_=!1,En();const e=[Kn,Vn,zn,kn,Ct,mn];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const r=t.get(s);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,r=new Set,o=i=>{if(s.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&o(n)}r.delete(i),s.add(i),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));for(const e of n)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(Ne);t.delta=e,t.elapsed+=e,t.frameCount++}}function cs(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const hs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ds(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case ve.FixedWidth:return o;case ve.FixedHeight:return i;case ve.Expand:return Math.max(o,i);case ve.Shrink:return Math.min(o,i);case ve.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function us(e,t,n,s,r,o){if(0===n||0===s)return[];const i=e.registry_getCameraEntities(t);if(0===i.length)return[];const a=o&&r?i.filter(e=>{const t=r.tryGet(e,Be);return!t||""===t.scene||o.has(t.scene)}):i;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const r=t.getCamera(e),o=t.getLocalTransform(e),i={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=i.w*n/(i.h*s);let h,d=0,u=0;if(r.projectionType===we.Orthographic){if(u=r.orthoSize,l){u=ds(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}d=u*a,h=ps(-d,d,-u,u,-r.farPlane,r.farPlane)}else h=ys(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=_s(o.position.x,o.position.y,o.position.z);c.push({entity:e,viewProjection:new Float32Array(xs(h,f)),viewportRect:i,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:u,cameraX:o.position.x,cameraY:o.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const fs=new Float32Array(16);function ps(e,t,n,s,r,o){const i=fs;i.fill(0);const a=t-e,l=s-n,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+n)/l,i[14]=-(o+r)/c,i[15]=1,i}const gs=new Float32Array(16);function ys(e,t,n,s){const r=gs;r.fill(0);const o=1/Math.tan(e/2),i=n-s;return r[0]=o/t,r[5]=o,r[10]=(s+n)/i,r[11]=-1,r[14]=2*s*n/i,r}const ms=new Float32Array(16);function _s(e,t,n){const s=ms;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}const ws=new Float32Array(16);function xs(e,t){const n=ws;for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}var vs,bs,Ss;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(vs||(vs={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(bs||(bs={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Ss||(Ss={}));const Ps=le("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:vs.Left,verticalAlign:bs.Top,wordWrap:!0,overflow:Ss.Visible,lineHeight:1.2}),Ms=le("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class Ts{constructor(e){this.cache=new Map,this.module=e,this.canvas=d(q.textCanvasSize,q.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),h=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),u=Math.ceil(l.length*c),f=r?Math.ceil(o):d+2*h,p=r?Math.ceil(i):u+2*h;if(r&&e.overflow===Ss.Ellipsis&&u>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const g=Math.round(255*e.color.r),y=Math.round(255*e.color.g),m=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${g}, ${y}, ${m}, ${_})`,r&&e.overflow===Ss.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(r)switch(e.verticalAlign){case bs.Top:x=h;break;case bs.Middle:x=(p-w)/2;break;case bs.Bottom:x=p-w-h;break;default:x=h}else x=h;let v=x;for(const t of l){let s;switch(e.align){case vs.Left:s=h;break;case vs.Center:s=f/2;break;case vs.Right:s=f-h;break;default:s=h}n.fillText(t,s,v),v+=c}r&&e.overflow===Ss.Clip&&n.restore();const b=n.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(f,p,M,S.length,1,!0);return this.module._free(M),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const r=this.renderText(t,n);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case vs.Left:return"left";case vs.Center:return"center";case vs.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function Es(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function Cs(e,t,n){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(n?n.size.x:0)||e.containerHeight!==(n?n.size.y:0)}class Rs{build(e){ye("Text",Ps);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Ts(t),s=e.world,r=new Map;e.addSystemToSchedule(et.PreUpdate,nt([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Ps));for(const e of r.keys())s.valid(e)&&s.has(e,Ps)||r.delete(e);const e=s.getEntitiesWithComponents([Ps]);for(const t of e){const e=s.get(t,Ps),o=s.has(t,Ms)?s.get(t,Ms):null,i=r.get(t);if(i&&!Cs(i,e,o))continue;s.has(t,Pe)||s.insert(t,Pe,{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=n.renderForEntity(t,e,o),l=s.get(t,Pe);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,Pe,l),r.set(t,Es(e,o))}}))}}const As=new Rs,Fs=le("UIMask",{enabled:!0,mode:"scissor"});function Is(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,o-s)}}function Bs(e,t,n,s,r,o,i,a,l,c,h){const d=e-n*r,u=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function g(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*h]}const[y,m]=g(d,f),[_,w]=g(u,p),x=Math.min(y,_),v=Math.max(y,_),b=Math.min(m,w),S=Math.max(m,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function ks(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],h=e[7],d=e[8],u=e[9],f=e[10],p=e[11],g=e[12],y=e[13],m=e[14],_=e[15],w=s*l-r*a,x=s*c-o*a,v=s*h-i*a,b=r*c-o*l,S=r*h-i*l,P=o*h-i*c,M=d*y-u*g,T=d*m-f*g,E=d*_-p*g,C=u*m-f*y,R=u*_-p*y,A=f*_-p*m;let F=w*A-x*R+v*C+b*E-S*T+P*M;return 0===F||(F=1/F,n[0]=(l*A-c*R+h*C)*F,n[1]=(o*R-r*A-i*C)*F,n[2]=(y*P-m*S+_*b)*F,n[3]=(f*S-u*P-p*b)*F,n[4]=(c*E-a*A-h*T)*F,n[5]=(s*A-o*E+i*T)*F,n[6]=(m*v-g*P-_*x)*F,n[7]=(d*P-f*v+p*x)*F,n[8]=(a*R-l*E+h*M)*F,n[9]=(r*E-s*R-i*M)*F,n[10]=(g*S-y*v+_*w)*F,n[11]=(u*v-d*S-p*w)*F,n[12]=(l*T-a*C-c*M)*F,n[13]=(s*C-r*T+o*M)*F,n[14]=(y*x-g*b-m*w)*F,n[15]=(d*b-u*x+f*w)*F),n}function $s(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],h=n[1]*a+n[5]*l+n[13],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:h/d}}function Ws(e,t,n,s,r,o,i,a){return e>=n-r*i&&e<=n+r*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function Ds(e,t,n,s,r,o,i,a,l,c){const h=2*Math.atan2(l,c),d=Math.sin(-h),u=Math.cos(-h),f=e-n,p=t-s,g=f*u-p*d+n,y=f*d+p*u+s;return g>=n-r*i&&g<=n+r*(1-i)&&y>=s-o*a&&y<=s+o*(1-a)}function Us(e,t,n,s,r,o,i){if(!e.has(t,Ms)||!e.has(t,Se))return null;const a=e.get(t,Ms),l=e.get(t,Se),c=a.size.x*l.scale.x,h=a.size.y*l.scale.y;return Bs(l.position.x,l.position.y,c,h,a.pivot.x,a.pivot.y,n,s,r,o,i)}function zs(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Fs]);if(0===l.length)return;const c=[],h=[],d=new Set,u=new Set;for(const e of l){const n=t.get(e,Fs);n.enabled&&(d.add(e),"stencil"===n.mode?(h.push(e),u.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,r,o,i,a,l,c){const h=[];for(const e of s){let n=!0,s=e;for(;t.has(s,Ce);){const e=t.get(s,Ce);if(r.has(e.entity)){if("scissor"===t.get(e.entity,Fs).mode){n=!1;break}}s=e.entity}n&&h.push(e)}function d(s,h){const u=e.getChildEntities(n,s);for(const n of u){let s=h;if(r.has(n)){if("scissor"===t.get(n,Fs).mode){const e=Us(t,n,o,i,a,l,c);e&&(s=Is(h,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of h){const n=Us(t,e,o,i,a,l,c);n&&d(e,n)}}(e,t,n,c,d,s,r,o,i,a),h.length>0&&function(e,t,n,s,r){e.renderer_clearStencil();const o=[];for(const e of s){let n=!0,s=e;for(;t.has(s,Ce);){const e=t.get(s,Ce);if(r.has(e.entity)){n=!1;break}s=e.entity}n&&o.push(e)}let i=1;function a(t,s){e.renderer_setEntityStencilMask(t,s);const o=e.getChildEntities(n,t);for(const t of o)if(r.has(t)){a(t,i++)}else e.renderer_setEntityStencilTest(t,s),l(t,s)}function l(t,s){const o=e.getChildEntities(n,t);for(const t of o)if(r.has(t)){a(t,i++)}else e.renderer_setEntityStencilTest(t,s),l(t,s)}for(const e of o){a(e,i++)}}(e,t,n,h,u)}catch(t){e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class Ls{build(e){if(ye("UIMask",Fs),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(zs(e.wasmModule,e.world))}}const Os=new Ls,Hs=le("Interactable",{enabled:!0,blockRaycast:!0}),js=le("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Xs;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Xs||(Xs={}));const Ys=le("Button",{state:Xs.Normal,transition:null});class Ns{constructor(){this.events_=[]}emit(e,t,n){const s=n??e;this.events_.push({entity:e,type:t,target:s,currentTarget:e})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const Vs=Oe(new Ns,"UIEvents"),qs=ce("ScreenSpace");function Gs(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,h=o.bottom+e.y*a,d=o.bottom+t.y*a;let u,f,p,g;if(e.x===t.x){const e=l+n.x,t=.5*r.x;u=e-t,p=e+t}else u=l+n.x,p=c+s.x;if(e.y===t.y){const e=h+n.y,t=.5*r.y;f=e-t,g=e+t}else f=h+n.y,g=d+s.y;return{centerX:.5*(u+p),centerY:.5*(f+g),width:p-u,height:g-f,rect:{left:u,bottom:f,right:p,top:g}}}function Js(e){return{anchorMinX:e.anchorMin.x,anchorMinY:e.anchorMin.y,anchorMaxX:e.anchorMax.x,anchorMaxY:e.anchorMax.y,offsetMinX:e.offsetMin.x,offsetMinY:e.offsetMin.y,offsetMaxX:e.offsetMax.x,offsetMaxY:e.offsetMax.y,sizeX:e.size.x,sizeY:e.size.y}}function Ks(e,t){return e.anchorMinX!==t.anchorMin.x||e.anchorMinY!==t.anchorMin.y||e.anchorMaxX!==t.anchorMax.x||e.anchorMaxY!==t.anchorMax.y||e.offsetMinX!==t.offsetMin.x||e.offsetMinY!==t.offsetMin.y||e.offsetMaxX!==t.offsetMax.x||e.offsetMaxY!==t.offsetMax.y||e.sizeX!==t.size.x||e.sizeY!==t.size.y}function Qs(e,t){let n=t;for(;;){if(e.has(n,qs))return n;if(!e.has(n,Ce))return null;const t=e.get(n,Ce);if(!e.valid(t.entity))return null;n=t.entity}}function Zs(e,t,n,s,r,o){if(!e.has(t,Ms))return;const i=e.get(t,Ms),a=Gs(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,be);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,be,l),!e.has(t,Re))return;const c=e.get(t,Re);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&Zs(e,t,a.rect,a.centerX,a.centerY,!1)}class er{build(e){ye("UIRect",Ms);const t=e.world,n=new Map;let s=NaN,r=NaN,o=NaN,i=NaN;e.addSystemToSchedule(et.PreUpdate,nt([He(xt)],e=>{if(!e.valid)return;const a={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},l=.5*(a.left+a.right),c=.5*(a.bottom+a.top),h=s!==e.worldLeft||r!==e.worldBottom||o!==e.worldRight||i!==e.worldTop;s=e.worldLeft,r=e.worldBottom,o=e.worldRight,i=e.worldTop;const d=new Set;if(h){const e=t.getEntitiesWithComponents([qs,Ms,be]);for(const t of e)d.add(t)}const u=t.getEntitiesWithComponents([Ms]);for(const e of u){const s=t.get(e,Ms),r=n.get(e);if(!r||Ks(r,s)){const n=Qs(t,e);null!==n&&d.add(n)}}for(const e of n.keys())if(!t.valid(e)||!t.has(e,Ms)){n.delete(e);const s=Qs(t,e);null!==s&&d.add(s)}for(const e of d)Zs(t,e,a,l,c,!0);for(const e of u){const s=t.get(e,Ms);n.set(e,Js(s))}},{name:"UILayoutSystem"}))}}const tr=new er,nr=new Float32Array(16),sr=new Float32Array(16);let rr=!0,or=1;function ir(e,t,n,s){t.emit(n,s,n);let r=n;for(;e.has(r,Ce);){const o=e.get(r,Ce).entity;if(!e.valid(o))break;if(!e.has(o,Hs)){r=o;continue}const i=e.get(o,Hs);if(i.enabled&&t.emit(o,s,n),i.blockRaycast)break;r=o}}class ar{build(e){ye("Interactable",Hs),ye("Button",Ys);const t=e.world,n=new Ns;e.insertResource(Vs,n);let s=null,r=null;or="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(et.PreUpdate,nt([He(ct),He(xt)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([js]);for(const e of i){const n=t.get(e,js);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a=e.mouseX*or,l=o.screenH-e.mouseY*or;!function(e){let t=!1;for(let n=0;n<16;n++)if(sr[n]!==e[n]){t=!0;break}t&&(sr.set(e),rr=!0)}(o.viewProjection),rr&&(ks(o.viewProjection,nr),rr=!1);const c=$s(a,l,nr,o.vpX,o.vpY,o.vpW,o.vpH),h=t.getEntitiesWithComponents([Hs,Ms,Se]);let d=null,u=-1/0;for(const e of h){t.has(e,js)||t.insert(e,js);if(!t.get(e,Hs).enabled)continue;const n=t.get(e,Se),s=t.get(e,Ms),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(Ds(c.x,c.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y,n.rotation.z,n.rotation.w)){let n=0;t.has(e,Pe)&&(n=t.get(e,Pe).layer),n>=u&&(u=n,d=e)}}if(s!==d){if(null!==s&&t.valid(s)&&t.has(s,js)){t.get(s,js).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,js).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,js);e.pressed=!0,e.justPressed=!0,r=d,ir(t,n,d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,js)){const e=t.get(r,js);e.pressed=!1,e.justReleased=!0,ir(t,n,r,"release"),r===s&&ir(t,n,r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(et.Update,nt([],()=>{const e=t.getEntitiesWithComponents([Ys]);for(const n of e){if(t.has(n,Hs)||t.insert(n,Hs,{enabled:!0}),!t.has(n,js))continue;const e=t.get(n,js),s=t.get(n,Ys),r=t.get(n,Hs),o=s.state;if(r.enabled?e.pressed?s.state=Xs.Pressed:e.hovered?s.state=Xs.Hovered:s.state=Xs.Normal:s.state=Xs.Disabled,o!==s.state&&s.transition&&t.has(n,Pe)){const e=t.get(n,Pe),r=s.transition;switch(s.state){case Xs.Normal:e.color={...r.normalColor};break;case Xs.Hovered:e.color={...r.hoveredColor};break;case Xs.Pressed:e.color={...r.pressedColor};break;case Xs.Disabled:e.color={...r.disabledColor}}t.insert(n,Pe,e)}}},{name:"ButtonSystem"}))}}const lr=new ar,cr=le("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class hr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){ye("TextInput",cr);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=d(q.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,h=0;const u=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!u)return;const f=u,p=()=>{a||null===i||w()},g=()=>{a=!0},y=()=>{a=!1,w()},m=t=>{if(null===i)return;if("Escape"===t.key)return void v();const s=n.get(i,cr);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(Vs).emit(i,"submit"),void v()}let r=s.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?r=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=s.value.length),r!==s.cursorPos&&(s.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,s.dirty=!0,b())},_=()=>{if(null!==i&&n.valid(i)&&n.has(i,cr)){const e=n.get(i,cr);e.focused=!1,e.dirty=!0}i=null};function w(){if(null===i||!n.valid(i))return;const t=n.get(i,cr);if(t.readOnly)return;let s=f.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),f.value=s),s!==t.value){t.value=s;e.getResource(Vs).emit(i,"change")}t.cursorPos=f.selectionStart??s.length,t.dirty=!0,b()}function x(e){if(i===e)return;v();const t=n.get(e,cr);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),b())}function v(){if(null!==i&&n.valid(i)&&n.has(i,cr)){const e=n.get(i,cr);e.focused=!1,e.dirty=!0}i=null,f.blur()}function b(){l=!0,c=0}function S(e,i,a,c){(r.width<a||r.height<c)&&(r.width=ur(Math.max(r.width,a)),r.height=ur(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const h=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,u=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),g=i.padding;if(i.multiline){const e=dr(o,u,a-2*g);let t=g;for(const n of e)o.fillText(n,g,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(u,g,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=dr(o,i.value.substring(0,i.cursorPos),a-2*g),r=e.length>0?e[e.length-1]:"";t=g+o.measureText(r).width,n=g+(e.length-1)*p,s=p}else t=g+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const y=o.getImageData(0,0,a,c),m=new Uint8Array(y.data.buffer),_=t.getResourceManager(),w=t._malloc(m.length);t.HEAPU8.set(m,w);const x=s.get(e);void 0!==x&&_.releaseTexture(x);const v=_.createTexture(a,c,w,m.length,1,!0);s.set(e,v),t._free(w);const b=n.get(e,Pe);b.texture=v,b.size.x=a,b.size.y=c,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},n.insert(e,Pe,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",g),f.addEventListener("compositionend",y),f.addEventListener("keydown",m),f.addEventListener("blur",_),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",g),f.removeEventListener("compositionend",y),f.removeEventListener("keydown",m),f.removeEventListener("blur",_),f.remove()},e.addSystemToSchedule(et.PreUpdate,nt([He(Vs)],e=>{const t=n.getEntitiesWithComponents([cr,Hs]);for(const e of t){if(!n.has(e,js))continue;if(n.get(e,js).justPressed)return void x(e)}if(null!==i){const e=n.getEntitiesWithComponents([Hs]);for(const t of e){if(n.has(t,cr))continue;if(!n.has(t,js))continue;if(n.get(t,js).justPressed)return void v()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(et.PreUpdate,nt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===h?0:(e-h)/1e3;if(h=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,cr)))){n.get(i,cr).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,cr)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([cr,Ms]);for(const e of a){const t=n.get(e,cr);if(!t.dirty)continue;const s=n.get(e,Ms),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,Pe)||n.insert(e,Pe,{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),S(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function dr(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function ur(e){let t=1;for(;t<e;)t*=2;return t}const fr=new hr,pr={Simple:0,Sliced:1,Tiled:2,Filled:3},gr={Horizontal:0,Vertical:1},yr={Left:0,Right:1,Bottom:2,Top:3},mr=le("Image",{texture:K,color:{r:1,g:1,b:1,a:1},imageType:pr.Simple,fillMethod:gr.Horizontal,fillOrigin:yr.Left,fillAmount:1,preserveAspect:!1,layer:0,material:0});const _r=new class{build(e){ye("Image",mr);const t=e.world;e.addSystemToSchedule(et.PreUpdate,nt([],()=>{const e=t.getEntitiesWithComponents([mr]);for(const n of e){const e=t.get(n,mr);t.has(n,Pe)||t.insert(n,Pe,{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const s=t.get(n,Pe);if(s.texture=e.texture,s.color.r=e.color.r,s.color.g=e.color.g,s.color.b=e.color.b,s.color.a=e.color.a,s.layer=e.layer,s.material=e.material,t.has(n,Ms)){const e=t.get(n,Ms);s.size.x=e.size.x,s.size.y=e.size.y}if(s.uvOffset.x=0,s.uvOffset.y=0,s.uvScale.x=1,s.uvScale.y=1,e.imageType===pr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount));e.fillMethod===gr.Horizontal?e.fillOrigin===yr.Left?(s.uvScale.x=t,s.size.x*=t):(s.uvOffset.x=1-t,s.uvScale.x=t,s.size.x*=t):e.fillOrigin===yr.Bottom?(s.uvScale.y=t,s.size.y*=t):(s.uvOffset.y=1-t,s.uvScale.y=t,s.size.y*=t)}t.insert(n,Pe,s)}},{name:"ImageSystem"}))}},wr=le("Toggle",{isOn:!0,graphicEntity:0,transition:null});const xr=new class{build(e){ye("Toggle",wr);const t=e.world;e.addSystemToSchedule(et.Update,nt([He(Vs)],e=>{const n=t.getEntitiesWithComponents([wr]);for(const s of n){if(t.has(s,Hs)||t.insert(s,Hs,{enabled:!0}),!t.has(s,js))continue;const n=t.get(s,js),r=t.get(s,wr),o=t.get(s,Hs);if(n.justPressed&&o.enabled&&(r.isOn=!r.isOn,e.emit(s,"change")),r.graphicEntity&&t.valid(r.graphicEntity)){const e=r.graphicEntity;if(t.has(e,Pe)){const n=t.get(e,Pe);n.color.a=r.isOn?1:0,t.insert(e,Pe,n)}}if(r.transition&&t.has(s,Pe)){const e=t.get(s,Pe),i=r.transition;o.enabled?n.pressed?e.color={...i.pressedColor}:n.hovered?e.color={...i.hoveredColor}:e.color={...i.normalColor}:e.color={...i.disabledColor},t.insert(s,Pe,e)}}},{name:"ToggleSystem"}))}};var vr;!function(e){e[e.LeftToRight=0]="LeftToRight",e[e.RightToLeft=1]="RightToLeft",e[e.BottomToTop=2]="BottomToTop",e[e.TopToBottom=3]="TopToBottom"}(vr||(vr={}));const br=le("ProgressBar",{value:0,fillEntity:0,direction:vr.LeftToRight});const Sr=new class{build(e){ye("ProgressBar",br);const t=e.world;e.addSystemToSchedule(et.PreUpdate,nt([],()=>{const e=t.getEntitiesWithComponents([br,Ms]);for(const n of e){const e=t.get(n,br);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=e.fillEntity;if(!t.has(s,Ms))continue;const r=t.get(s,Ms),o=Math.max(0,Math.min(1,e.value));switch(e.direction){case vr.LeftToRight:r.anchorMin={x:0,y:0},r.anchorMax={x:o,y:1};break;case vr.RightToLeft:r.anchorMin={x:1-o,y:0},r.anchorMax={x:1,y:1};break;case vr.BottomToTop:r.anchorMin={x:0,y:0},r.anchorMax={x:1,y:o};break;case vr.TopToBottom:r.anchorMin={x:0,y:1-o},r.anchorMax={x:1,y:1}}r.offsetMin={x:0,y:0},r.offsetMax={x:0,y:0},t.insert(s,Ms,r)}},{name:"ProgressBarSystem"}))}},Pr=le("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Mr=le("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}}),Tr=new Float32Array(16),Er=new Float32Array(16);let Cr=!0;function Rr(e,t,n){const s=e.mouseX*n,r=t.screenH-e.mouseY*n;return function(e){let t=!1;for(let n=0;n<16;n++)if(Er[n]!==e[n]){t=!0;break}t&&(Er.set(e),Cr=!0)}(t.viewProjection),Cr&&(ks(t.viewProjection,Tr),Cr=!1),$s(s,r,Tr,t.vpX,t.vpY,t.vpW,t.vpH)}const Ar=new class{build(e){ye("Draggable",Pr),ye("DragState",Mr);const t=e.world,n=e.getResource(Vs);let s=null,r={x:0,y:0},o=null;const i="undefined"!=typeof window&&window.devicePixelRatio||1;e.addSystemToSchedule(et.PreUpdate,nt([He(ct),He(xt)],(e,a)=>{if(!a.valid)return;const l=Rr(e,a,i);if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Pr,js]);let n=null;for(const s of e){if(!t.get(s,Pr).enabled)continue;t.get(s,js).hovered&&(n=s)}if(null!==n){s=n,r={x:l.x,y:l.y},t.has(n,Mr)||t.insert(n,Mr);const e=t.get(n,Mr),o=t.get(n,Se);e.startWorldPos={x:o.position.x,y:o.position.y},e.currentWorldPos={x:o.position.x,y:o.position.y},e.pointerStartWorld={x:l.x,y:l.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,Mr)){t.get(s,Mr).isDragging=!1}s=null}if(null!==s&&null===o){if(!t.valid(s))return void(s=null);const e=l.x-r.x,i=l.y-r.y,c=Math.sqrt(e*e+i*i),h=t.get(s,Pr);if(c*(a.vpW/(a.worldRight-a.worldLeft))>=h.dragThreshold){o=s,s=null;t.get(o,Mr).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Mr))return void(o=null);const s=t.get(o,Mr),r=t.get(o,Pr),i=l.x-s.pointerStartWorld.x,a=l.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+i,h=s.startWorldPos.y+a;const d=function(e,t,n,s){let r=e.lockX?t.startWorldPos.x:n,o=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(r=Math.max(r,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(r=Math.min(r,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:r,y:o}}(r,s,c,h);c=d.x,h=d.y;const u=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-u,y:h-f},s.currentWorldPos={x:c,y:h},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:h-s.startWorldPos.y},t.has(o,be)){const e=function(e,t,n,s){if(!e.has(t,Ce))return{x:n,y:s};const r=e.get(t,Ce).entity;if(!e.valid(r)||!e.has(r,Se))return{x:n,y:s};const o=e.get(r,Se),i=0!==o.scale.x?o.scale.x:1,a=0!==o.scale.y?o.scale.y:1,l=2*Math.atan2(o.rotation.z,o.rotation.w),c=Math.sin(-l),h=Math.cos(-l);return{x:(n*h-s*c)/i,y:(n*c+s*h)/a}}(t,o,s.deltaWorld.x,s.deltaWorld.y),n=t.get(o,be);n.position.x+=e.x,n.position.y+=e.y,t.insert(o,be,n)}n.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},Fr=le("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135});const Ir=new class{build(e){ye("ScrollView",Fr);const t=e.world,n=new Map,s=new Float32Array(16),r="undefined"!=typeof window&&window.devicePixelRatio||1;let o=0;e.addSystemToSchedule(et.PreUpdate,nt([He(ct),He(xt)],(e,i)=>{const a=performance.now()/1e3,l=o>0?Math.min(a-o,.05):0;if(o=a,!i.valid)return;const c=e.mouseX*r,h=i.screenH-e.mouseY*r;ks(i.viewProjection,s);const d=$s(c,h,s,i.vpX,i.vpY,i.vpW,i.vpH),u=t.getEntitiesWithComponents([Fr,Ms]);for(const s of u){t.has(s,Hs)||t.insert(s,Hs,{enabled:!0,blockRaycast:!0}),t.has(s,Fs)||t.insert(s,Fs,{enabled:!0,mode:"scissor"});const r=t.get(s,Fr),o=t.get(s,Ms);let i=n.get(s);i||(i={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0},n.set(s,i));const a=t.has(s,js)?t.get(s,js):null;if(a?.justPressed&&(i.isDragging=!0,i.lastWorldX=d.x,i.lastWorldY=d.y,i.velocityX=0,i.velocityY=0),i.isDragging&&e.isMouseButtonDown(0)){const e=d.x-i.lastWorldX,t=d.y-i.lastWorldY;r.horizontalEnabled&&(r.scrollX-=e,i.velocityX=l>0?-e/l:0),r.verticalEnabled&&(r.scrollY-=t,i.velocityY=l>0?-t/l:0),i.lastWorldX=d.x,i.lastWorldY=d.y}if(i.isDragging&&e.isMouseButtonReleased(0)&&(i.isDragging=!1),a?.hovered){const t=e.getScrollDelta();r.verticalEnabled&&0!==t.y&&(r.scrollY+=.1*t.y,i.velocityY=0),r.horizontalEnabled&&0!==t.x&&(r.scrollX+=.1*t.x,i.velocityX=0)}if(!i.isDragging&&r.inertia&&l>0){const e=Math.pow(r.decelerationRate,l);r.horizontalEnabled&&Math.abs(i.velocityX)>.1?(r.scrollX+=i.velocityX*l,i.velocityX*=e):i.velocityX=0,r.verticalEnabled&&Math.abs(i.velocityY)>.1?(r.scrollY+=i.velocityY*l,i.velocityY*=e):i.velocityY=0}const c=o.size.x,h=o.size.y,u=Math.max(0,r.contentWidth-c),f=Math.max(0,r.contentHeight-h);if(r.scrollX=Math.max(0,Math.min(r.scrollX,u)),r.scrollY=Math.max(0,Math.min(r.scrollY,f)),0!==r.contentEntity&&t.valid(r.contentEntity)){const e=r.contentEntity;if(t.has(e,be)){const n=t.get(e,be);n.position.x=-r.scrollX,n.position.y=r.scrollY,t.insert(e,be,n)}}}},{name:"ScrollViewSystem"}))}};var Br;!function(e){e[e.LeftToRight=0]="LeftToRight",e[e.RightToLeft=1]="RightToLeft",e[e.BottomToTop=2]="BottomToTop",e[e.TopToBottom=3]="TopToBottom"}(Br||(Br={}));const kr=le("Slider",{value:0,minValue:0,maxValue:1,direction:Br.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});const $r=new class{build(e){ye("Slider",kr);const t=e.world,n=new Float32Array(16),s="undefined"!=typeof window&&window.devicePixelRatio||1;let r=null;e.addSystemToSchedule(et.PreUpdate,nt([He(ct),He(xt)],(e,o)=>{if(!o.valid)return;const i=e.mouseX*s,a=o.screenH-e.mouseY*s;ks(o.viewProjection,n);const l=$s(i,a,n,o.vpX,o.vpY,o.vpW,o.vpH),c=t.getEntitiesWithComponents([kr,Ms,Se]);for(const n of c){t.has(n,Hs)||t.insert(n,Hs,{enabled:!0,blockRaycast:!0});const s=t.get(n,kr),o=t.get(n,Ms),i=t.get(n,Se),a=t.has(n,js)?t.get(n,js):null;if(a?.justPressed&&(r=n),r===n&&e.isMouseButtonDown(0)){const e=o.size.x*i.scale.x,t=o.size.y*i.scale.y,n=i.position.x-o.pivot.x*e,r=i.position.y-o.pivot.y*t;let a;switch(s.direction){case Br.LeftToRight:a=e>0?(l.x-n)/e:0;break;case Br.RightToLeft:a=e>0?1-(l.x-n)/e:0;break;case Br.BottomToTop:a=t>0?(l.y-r)/t:0;break;case Br.TopToBottom:a=t>0?1-(l.y-r)/t:0}a=Math.max(0,Math.min(1,a));let c=s.minValue+a*(s.maxValue-s.minValue);s.wholeNumbers&&(c=Math.round(c)),s.value=Math.max(s.minValue,Math.min(s.maxValue,c))}r===n&&e.isMouseButtonReleased(0)&&(r=null);const c=s.maxValue-s.minValue,h=c>0?(s.value-s.minValue)/c:0;if(0!==s.fillEntity&&t.valid(s.fillEntity)){const e=s.fillEntity;if(t.has(e,Ms)){const n=t.get(e,Ms);switch(s.direction){case Br.LeftToRight:n.anchorMin={x:0,y:0},n.anchorMax={x:h,y:1};break;case Br.RightToLeft:n.anchorMin={x:1-h,y:0},n.anchorMax={x:1,y:1};break;case Br.BottomToTop:n.anchorMin={x:0,y:0},n.anchorMax={x:1,y:h};break;case Br.TopToBottom:n.anchorMin={x:0,y:1-h},n.anchorMax={x:1,y:1}}t.insert(e,Ms,n)}}if(0!==s.handleEntity&&t.valid(s.handleEntity)){const e=s.handleEntity;if(t.has(e,Ms)){const n=t.get(e,Ms);switch(s.direction){case Br.LeftToRight:n.anchorMin={x:h,y:0},n.anchorMax={x:h,y:1};break;case Br.RightToLeft:n.anchorMin={x:1-h,y:0},n.anchorMax={x:1-h,y:1};break;case Br.BottomToTop:n.anchorMin={x:0,y:h},n.anchorMax={x:1,y:h};break;case Br.TopToBottom:n.anchorMin={x:0,y:1-h},n.anchorMax={x:1,y:1-h}}t.insert(e,Ms,n)}}}},{name:"SliderSystem"}))}},Wr=le("Focusable",{tabIndex:0,isFocused:!1});class Dr{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Ur=Oe(new Dr,"FocusManager");const zr=new class{build(e){ye("Focusable",Wr);const t=e.world,n=new Dr;e.insertResource(Ur,n),e.addSystemToSchedule(et.Update,nt([He(ct),He(Vs)],(e,s)=>{const r=t.getEntitiesWithComponents([Wr]);for(const e of r){if(!t.has(e,js))continue;t.get(e,js).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of r){const s=t.get(n,Wr);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const i=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===i?a?s.length-1:0:a?(i-1+s.length)%s.length:(i+1)%s.length,o(s[l])}function o(e){const r=n.focusedEntity;if(r===e)return;if(null!==r&&t.valid(r)&&t.has(r,Wr)){t.get(r,Wr).isFocused=!1,s.emit(r,"hover_exit",r)}n.focus(e);t.get(e,Wr).isFocused=!0,s.emit(e,"hover_enter",e)}},{name:"FocusSystem"}))}},Lr=le("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});const Or=new class{build(e){ye("SafeArea",Lr);const t=e.world;let n={top:0,bottom:0,left:0,right:0},s=0;e.addSystemToSchedule(et.PreUpdate,nt([],()=>{s++%60==0&&(n=function(){if("undefined"==typeof document)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}());const e=t.getEntitiesWithComponents([Lr,Ms]);for(const s of e){const e=t.get(s,Lr),r=t.get(s,Ms);let o=!1;const i=e.applyTop?n.top:0,a=e.applyBottom?n.bottom:0,l=e.applyLeft?n.left:0,c=e.applyRight?n.right:0;r.offsetMin.x===l&&r.offsetMin.y===a||(r.offsetMin={x:l,y:a},o=!0),r.offsetMax.x===-c&&r.offsetMax.y===-i||(r.offsetMax={x:-c,y:-i},o=!0),o&&t.insert(s,Ms,r)}},{name:"SafeAreaSystem"}))}},Hr=le("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2}),jr=new Map;function Xr(e,t){const n=jr.get(e);n&&(n.renderer=t)}const Yr=new class{build(e){ye("ListView",Hr);const t=e.world;e.addSystemToSchedule(et.PreUpdate,nt([He(ct)],e=>{const n=t.getEntitiesWithComponents([Hr,Ms]);for(const s of n){t.has(s,Hs)||t.insert(s,Hs,{enabled:!0,blockRaycast:!0}),t.has(s,Fs)||t.insert(s,Fs,{enabled:!0,mode:"scissor"});let n=jr.get(s);n||(n={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},jr.set(s,n));const r=t.get(s,Hr),o=t.get(s,Ms),i=o.size.y,a=t.has(s,js)?t.get(s,js):null;if(a?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}const l=Math.max(0,r.itemCount*r.itemHeight-i);r.scrollY=Math.max(0,Math.min(r.scrollY,l));const c=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),h=Math.min(r.itemCount,Math.ceil((r.scrollY+i)/r.itemHeight)+r.overscan);for(const[e,s]of n.itemEntities)(e<c||e>=h)&&(t.valid(s)&&t.despawn(s),n.itemEntities.delete(e));for(let e=c;e<h;e++){let i=n.itemEntities.get(e);if(i&&t.valid(i)||(i=t.spawn(),t.insert(i,Ie,{value:`ListItem_${e}`}),t.insert(i,Ms,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o.size.x,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(i,s),n.itemEntities.set(e,i),n.renderer&&n.renderer(e,i)),t.has(i,be)){const n=t.get(i,be);n.position.y=-(e*r.itemHeight-r.scrollY),t.insert(i,be,n)}}n.visibleStart=c,n.visibleEnd=h}},{name:"ListViewSystem"}))}},Nr=le("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const Vr=new class{build(e){ye("Dropdown",Nr);const t=e.world;e.addSystemToSchedule(et.Update,nt([He(ct),He(Vs)],(e,n)=>{const s=t.getEntitiesWithComponents([Nr]);for(const o of s){t.has(o,Hs)||t.insert(o,Hs,{enabled:!0,blockRaycast:!0});const s=t.get(o,Nr),i=t.has(o,js)?t.get(o,js):null;if(i?.justPressed&&(s.isOpen=!s.isOpen,r(s.listEntity,s.isOpen),n.emit(o,"change",o)),s.isOpen&&e.isMouseButtonPressed(0)&&!i?.hovered){0!==s.listEntity&&t.valid(s.listEntity)&&t.has(s.listEntity,js)&&t.get(s.listEntity,js).hovered||(s.isOpen=!1,r(s.listEntity,!1))}}function r(e,n){if(0===e)return;const s=e;if(!t.valid(s)||!t.has(s,be))return;const r=t.get(s,be),o=n?1:0;r.scale={x:o,y:o,z:o},t.insert(s,be,r)}},{name:"DropdownSystem"}))}};async function qr(e,t,n){const s=e.getResource(rs);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function Gr(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const Jr=Oe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Kr=Oe(null,"PhysicsAPI");function Qr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Zr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class eo{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Jr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Gr(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([Te]);for(const n of t){const t=e.world.get(n,Te);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(et.PostUpdate,nt([He(Ne)],a=>{const l=i.getEntitiesWithComponents([$e,be,Se]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,$e),l=i.get(r,Se);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=Qr(l.rotation);s._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),to(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===ze.Kinematic){const e=Qr(l.rotation);s._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const h=e.world.get(i,be);if(!h)continue;let d=a,u=l,f=c;if(e.world.has(i,Ce)){const t=e.world.get(i,Ce);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,Se)){const n=e.world.get(t.entity,Se),s=Qr(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),h=Math.sin(-s);d=(r*i-o*h)/(0!==n.scale.x?n.scale.x:1),u=(r*h+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}h.position.x=d,h.position.y=u;const p=Zr(f);h.rotation.w=p.w,h.rotation.x=p.x,h.rotation.y=p.y,h.rotation.z=p.z,e.world.insert(i,be,h)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],h=t._physics_getSensorExitCount();if(h>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<h;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Jr,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(Kr,no._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function to(e,t,n){const s=e.world;if(s.has(n,We)){const e=s.get(n,We);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,De)){const e=s.get(n,De);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,Ue)){const e=s.get(n,Ue);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class no{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(no.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function so(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function ro(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function oo(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,h=e.rotation.w,d=a+a,u=l+l,f=c+c,p=a*d,g=a*u,y=a*f,m=l*u,_=l*f,w=c*f,x=h*d,v=h*u,b=h*f;return new Float32Array([(1-(m+w))*r,(g+b)*r,(y-v)*r,0,(g-b)*o,(1-(p+w))*o,(_+x)*o,0,(y+v)*i,(_-x)*i,(1-(p+m))*i,0,e.position.x,e.position.y,e.position.z,1])}async function io(e,t,n,s,r,o,i,a,l){const c=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=so(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,c);let h={},d=null;if(r&&(d=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),h=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=await r.readText(a),h="binary"===x(l)?.contentType;let d,u;if(h){const e=await r.readBinary(i);u=e.length,d=t._malloc(u),t.HEAPU8.set(e,d)}else{const e=await r.readText(i),n=(new TextEncoder).encode(e);u=n.length,d=t._malloc(u+1),t.HEAPU8.set(n,d),t.HEAPU8[d+u]=0}const f=n.loadSkeleton(d,u,s,s.length,h);if(t._free(d),f<0)continue;o[i]=f;const p=ro(s),g=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=g+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=so(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,d,n,s)),o){new eo("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const u=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;const i=x(r);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[r]=0;continue}const l=o?`${o}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),h=so(e,c,!1),d=e.getResourceManager();s[r]=d.loadBitmapFont(t,h,c.width,c.height)}catch{s[r]=0}}return s}(t,n,s),f=await async function(e,t){const n={},s={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===n[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=At.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=At.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s);!function(e,t,n,s){const r={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=Xt(e.type);if(0===t.length)continue;const n=e.data;for(const e of t)"string"==typeof n[e.field]&&(n[e.field]=r[e.type][n[e.field]]||0)}}(n,c,u,f);const p=Yt(e.world,n);if(l&&e.hasResource(rs))for(const t of p.values())e.world.insert(t,Be,{scene:l,persistent:!1});if(r&&d){const s=function(e,t,n,s){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(d,n,h,p);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,Fe)?c.get(o,Fe):null,h=!1!==a?.playing,d=a?.timeScale??1;h&&s.update(i,l*d);let u=0;if(c.has(o,Se)){const e=oo(c.get(o,Se),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);u=t._malloc(64),t.HEAPF32.set(e,u>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),h=n._malloc(l),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,h,d,f);const p=n.HEAPU32[d>>2],g=n.HEAPU32[f>>2],y=new Float32Array(n.HEAPF32.buffer,c,8*r),m=new Uint16Array(n.HEAPU8.buffer,h,o),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(y,_>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(m),t.renderer_submitTriangles(_,r,w,o,p,g,u),t._free(_),t._free(w),n._free(c),n._free(h),n._free(d),n._free(f)}u&&t._free(u)}})}(e,t,r,d,s)}if(a){const t=e.getResource(Kt);t&&t.setAddressableManifest(a)}}function ao(e,t,n){return{name:e,data:t,async setup(){await io(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class lo{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&("binary"===x(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of s){const t=x(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const co="__preview__";class ho{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(rs);t.register({name:co,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(co),this.loadPromise_=t.load(co).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new lo(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.spineInitPromise;if(r){s=(await r).controller.raw}await io(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,co)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([Me]);for(const s of n){if(e.get(s,Me).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([Te]);for(const r of s){const s=e.get(r,Te);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=this.app_.getResource(rs).getScene(co),o=r?r.spawn():e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(o,be,i);const a={isActive:!0,projectionType:we.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:xe.ColorAndDepth};e.insert(o,Me,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(rs);await e.switchTo(co),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}}const uo={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=qn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:qn.getTargetTexture(n),width:e.width,height:e.height}},release(e){qn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(qn.releaseRenderTarget(e._handle),uo.create({width:t,height:n,depth:!0})),begin(e,t){qn.begin(t,e._handle)},end(){qn.end()},getDepthTexture:e=>qn.getTargetDepthTexture(e._handle)};let fo=!1;function po(e){fo=e}function go(){return fo}function yo(){return!fo}var mo;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(mo||(mo={}));class _o{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${mo[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case mo.Debug:console.debug(t,n);break;case mo.Info:console.log(t,n);break;case mo.Warn:console.warn(t,n);break;case mo.Error:console.error(t,n)}}}class wo{constructor(){this.handlers_=[],this.minLevel_=mo.Info,this.addHandler(new _o)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log(mo.Debug,e,t,n)}info(e,t,n){this.log(mo.Info,e,t,n)}warn(e,t,n){this.log(mo.Warn,e,t,n)}error(e,t,n){this.log(mo.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const xo=new wo;function vo(){return xo}function bo(e){xo.setMinLevel(e)}function So(e,t,n){xo.debug(e,t,n)}function Po(e,t,n){xo.info(e,t,n)}function Mo(e,t,n){xo.warn(e,t,n)}function To(e,t,n){xo.error(e,t,n)}const Eo=[As,Os,tr,_r,Sr,lr,Ar,Ir,$r,xr,fr,zr,Or,Yr,Vr];function Co(e,t){return function(e,t){const n=ls.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),yn(e),Et(e),Bn(e),Un(e),Nn(e),Jn(e);const r=new Zn;n.setPipeline(r);let o=u();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,o){o||(o=us(e,s,t,r));const i=n.getResource(xt);if(o.length>0){const e=o[0],n=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(n.x*t),i.vpY=Math.round((1-n.y-n.h)*r),i.vpW=Math.round(n.w*t),i.vpH=Math.round(n.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}n.insertResource(xt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=i();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;qn.setClearColor(e.x,e.y,e.z,e.w)}const h=(u()-o)/1e3;let d;if(qn.resize(t,l),On.isInitialized()&&On.getPassCount()>0&&!On.isBypassed()&&On.resize(t,l),n.hasResource(rs)){const e=n.getResource(rs).getActiveScenes();e.length>0&&(d=new Set(e))}r.setActiveScenes(d??null);const f=us(e,s,t,l,n.world,d);if(a(t,l,f),0===f.length)r.render({registry:{_cpp:s},viewProjection:hs,width:t,height:l,elapsed:h});else{for(const e of f){const n=e.viewportRect,o=Math.round(n.x*t),i=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:c},clearFlags:e.clearFlags,elapsed:h})}qn.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(et.First,l),n.addSystemToSchedule(et.Last,c),n.addPlugin(Zt),n.addPlugin(hn),n.addPlugin(dt),n.addPlugin(as),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Eo,...t})}H||(H=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await f(n,s);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:n}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return p(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),n=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?n[s++]=r:r<2048?(n[s++]=192|r>>6,n[s++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,n[s++]=240|r>>18,n[s++]=128|r>>12&63,n[s++]=128|r>>6&63,n[s++]=128|63&r):(n[s++]=224|r>>12,n[s++]=128|r>>6&63,n[s++]=128|63&r)}return n.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let n="";for(let e=0;e<t.length;){const s=t[e];if(s<128)n+=String.fromCharCode(s),e++;else if(192==(224&s))n+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))n+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=j;export{ls as App,Qt as AssetPlugin,en as AssetRefCounter,Jt as AssetServer,Kt as Assets,zt as AsyncCache,Ae as BitmapText,vt as BlendMode,ze as BodyType,We as BoxCollider,Ys as Button,Xs as ButtonState,Me as Camera,Te as Canvas,Ue as CapsuleCollider,Re as Children,De as CircleCollider,xe as ClearFlags,Ke as Commands,Ze as CommandsInstance,Y as DEFAULT_DESIGN_HEIGHT,X as DEFAULT_DESIGN_WIDTH,N as DEFAULT_PIXELS_PER_UNIT,V as DEFAULT_TEXT_CANVAS_SIZE,Cn as DataType,Mr as DragState,Pr as Draggable,xn as Draw,Nr as Dropdown,Qe as EntityCommands,gr as FillMethod,yr as FillOrigin,Ur as FocusManager,Dr as FocusManagerState,Wr as Focusable,Qn as GLDebug,Wn as Geometry,J as INVALID_ENTITY,Q as INVALID_FONT,K as INVALID_TEXTURE,mr as Image,pr as ImageType,ct as Input,ht as InputPlugin,lt as InputState,Hs as Interactable,Hr as ListView,be as LocalTransform,mo as LogLevel,wo as Logger,At as Material,Lt as MaterialLoader,Ve as Mut,Ie as Name,Ce as Parent,no as Physics,Jr as PhysicsEvents,eo as PhysicsPlugin,On as PostProcess,an as PrefabServer,ln as Prefabs,cn as PrefabsPlugin,ho as PreviewPlugin,br as ProgressBar,vr as ProgressBarDirection,we as ProjectionType,Ge as Query,Je as QueryInstance,Zn as RenderPipeline,jn as RenderStage,uo as RenderTexture,qn as Renderer,He as Res,je as ResMut,$e as RigidBody,q as RuntimeConfig,Lr as SafeArea,ve as ScaleMode,rs as SceneManager,ss as SceneManagerState,Be as SceneOwner,et as Schedule,qs as ScreenSpace,Fr as ScrollView,Ut as ShaderSources,kr as Slider,Br as SliderDirection,Fe as SpineAnimation,Pe as Sprite,at as SystemRunner,Ps as Text,vs as TextAlign,cr as TextInput,hr as TextInputPlugin,Ss as TextOverflow,Rs as TextPlugin,Ts as TextRenderer,bs as TextVerticalAlign,Ne as Time,wr as Toggle,xt as UICameraInfo,Ns as UIEventQueue,Vs as UIEvents,js as UIInteraction,ar as UIInteractionPlugin,er as UILayoutPlugin,Fs as UIMask,Ls as UIMaskPlugin,Ms as UIRect,Ee as Velocity,lo as WebAssetProvider,wt as World,Se as WorldTransform,ot as addStartupSystem,rt as addSystem,it as addSystemToSchedule,G as applyRuntimeConfig,Zt as assetPlugin,En as clearDrawCallbacks,de as clearUserComponents,ne as color,Gs as computeUIRectLayout,zs as createMaskProcessor,ao as createRuntimeSceneConfig,Co as createWebApp,So as debug,le as defineComponent,Oe as defineResource,nt as defineSystem,ce as defineTag,To as error,Gt as findEntityByName,cs as flushPendingSystems,b as getAddressableType,S as getAddressableTypeByEditorType,M as getAllAssetExtensions,R as getAssetMimeType,x as getAssetTypeEntry,me as getComponent,jt as getComponentAssetFields,ke as getComponentDefaults,E as getCustomExtensions,v as getEditorType,vo as getLogger,t as getPlatform,s as getPlatformType,he as getUserComponent,C as getWeChatPackOptions,Po as info,yn as initDrawAPI,Jn as initGLDebugAPI,Bn as initGeometryAPI,Et as initMaterialAPI,Un as initPostProcessAPI,Nn as initRendererAPI,dt as inputPlugin,nn as instantiatePrefab,Is as intersectRects,ks as invertMatrix4,pe as isBuiltinComponent,A as isCustomExtension,go as isEditor,P as isKnownAssetExtension,n as isPlatformInitialized,yo as isRuntime,bt as isTextureRef,r as isWeChat,o as isWeb,Vt as loadComponent,Gr as loadPhysicsModule,io as loadRuntimeScene,Yt as loadSceneData,Nt as loadSceneWithAssets,T as looksLikeAssetPath,i as platformFetch,c as platformFileExists,h as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Ds as pointInOBB,Ws as pointInWorldRect,hn as prefabsPlugin,se as quat,ye as registerComponent,Ht as registerComponentAssetFields,Mn as registerDrawCallback,tn as registerEmbeddedAssets,Dt as registerMaterialCallback,as as sceneManagerPlugin,$s as screenToWorld,po as setEditorMode,Xr as setListViewRenderer,bo as setLogLevel,yt as setWasmErrorHandler,mn as shutdownDrawAPI,Kn as shutdownGLDebugAPI,kn as shutdownGeometryAPI,Ct as shutdownMaterialAPI,zn as shutdownPostProcessAPI,Vn as shutdownRendererAPI,fr as textInputPlugin,As as textPlugin,qr as transitionTo,lr as uiInteractionPlugin,tr as uiLayoutPlugin,Os as uiMaskPlugin,Eo as uiPlugins,ue as unregisterComponent,Tn as unregisterDrawCallback,qt as updateCameraAspectRatio,Z as vec2,ee as vec3,te as vec4,Mo as warn,Bs as worldRectToScreen,os as wrapSceneSystem,W as wxFileExists,D as wxFileExistsSync,L as wxGetImagePixels,z as wxLoadImage,O as wxLoadImagePixels,k as wxReadFile,$ as wxReadTextFile,U as wxWriteFile};
+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function h(e,n){return t().instantiateWasm(e,n)}function d(e,n){return t().createCanvas(e,n)}function u(){return t().now()}function f(e,t){return new Promise((n,s)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];n({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,n="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(n).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function p(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const n=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(n,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${n}": ${t}`)}}const g=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],y={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},m=new Map,_=new Set;for(const e of g)for(const t of e.extensions)m.set(t,e),_.add(t);function w(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function x(e){return m.get(w(e))}function v(e){return x(e)?.editorType??"unknown"}function b(e){return x(e)?.addressableType??null}function S(e){for(const t of g)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function P(e){return _.has(e.toLowerCase())}function M(){return _}function T(e){return"string"==typeof e&&(!!e.includes("/")&&P(w(e)))}function E(){const e=[];for(const t of g)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function C(){return E().map(e=>({type:"suffix",value:e}))}function R(e){return y[e.toLowerCase()]}function A(e){const t=x(e);return t?.wechatPackInclude??!1}let F=null;function I(){return F||(F=wx.getFileSystemManager()),F}function B(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if(A(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return n.includes("no such file")||n.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function k(e){return new Promise((t,n)=>{I().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(B(e,t.errMsg)))}})})}function $(e,t="utf-8"){return new Promise((n,s)=>{I().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(B(e,t.errMsg)))}})})}function W(e){return new Promise(t=>{I().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function D(e){const t=I();try{return t.accessSync(e),!0}catch{return!1}}function U(e,t){return new Promise((n,s)=>{I().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function z(e){return new Promise((t,n)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>n(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function L(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){const n=wx.createCanvas();n.width=e,n.height=t;const s=n.getContext("2d");return{canvas:n,ctx:s}}(t,n);s.clearRect(0,0,t,n),s.drawImage(e,0,0);const r=s.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(r.data.buffer)}}async function O(e){return L(await z(e))}let H=!1;const j=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return k(e)}async readTextFile(e){return $(e)}async fileExists(e){return W(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return p(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const n=wx.createCanvas();return n.width=e,n.height=t,n}now(){return Date.now()}bindInputEvents(e,t){const{pixelRatio:n}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX*n,s.clientY*n)}),wx.onTouchMove(t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX*n,s.clientY*n)}),wx.onTouchEnd(t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)})}},X=1920,Y=1080,N=100,V=512,q={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function G(e){e.Text&&(e.Text._default.fontFamily=q.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=q.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=q.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=q.canvasMatchWidthOrHeight)}const J=0,K=4294967295,Q=4294967295,Z=(e=0,t=0)=>({x:e,y:t}),ee=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),te=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),ne=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),se=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function re(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(re);const t={};for(const n in e)t[n]=re(e[n]);return t}let oe=0;function ie(e,t){const n=++oe;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...re(t),...e}:re(t)}}function ae(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function le(e,t){const n=ae(),s=n.get(e);if(s)return s;const r=ie(e,t);return n.set(e,r),fe(e,t,!1),r}function ce(e){const t=ae(),n=t.get(e);if(n)return n;const s=ie(e,{});return t.set(e,s),fe(e,{},!0),s}function he(e){return ae().get(e)}function de(){ae().clear()}function ue(e){ae().delete(e)}function fe(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function pe(e){return!0===e._builtin}const ge=new Map;function ye(e,t){ge.set(e,t)}function me(e){return ge.get(e)??he(e)}function _e(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return ge.set(e,n),n}const we={Perspective:0,Orthographic:1},xe={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ve={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},be=_e("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Se=_e("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Pe=_e("Sprite",{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),Me=_e("Camera",{projectionType:we.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:xe.ColorAndDepth}),Te=_e("Canvas",{designResolution:{x:X,y:Y},pixelsPerUnit:100,scaleMode:ve.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Ee=_e("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Ce=_e("Parent",{entity:0}),Re=_e("Children",{entities:[]}),Ae=_e("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:Q,enabled:!0}),Fe=_e("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),Ie={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},Be=le("SceneOwner",{scene:"",persistent:!1});function ke(e){const t=me(e);return t?re(t._default):null}ye("Name",Ie);const $e=_e("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),We=_e("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),De=_e("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ue=_e("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ze={Static:0,Kinematic:1,Dynamic:2};let Le=0;function Oe(e,t){const n=++Le;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function He(e){return{_type:"res",_resource:e}}function je(e){return{_type:"res_mut",_resource:e}}class Xe{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class Ye{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new Xe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Ne=Oe({delta:0,elapsed:0,frameCount:0},"Time");function Ve(e){return{_type:"mut",_component:e}}function qe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Ge(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{qe(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class Je{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>qe(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=n.length,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let h=null;this.world_.beginIteration();try{for(const d of s){if(null!==h&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(h,t.component,t.data)}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(d,t[n])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,n[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];h=d}yield a}}finally{if(this.world_.endIteration(),null!==h&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(h,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function Ke(){return{_type:"commands"}}class Qe{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=pe(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Ze{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Qe(this,null);return this.spawned_.push(e),e}entity(e){return new Qe(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var et;!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(et||(et={}));let tt=0;function nt(e,t,n){const s=++tt;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function st(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function rt(e){st().push({schedule:et.Update,system:e})}function ot(e){st().push({schedule:et.Startup,system:e})}function it(e,t){st().push({schedule:e,system:t})}class at{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Ze&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new Je(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Ze(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class lt{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const ct=Oe(new lt,"Input");class ht{constructor(e){this.target_=e??null}build(e){const n=new lt;e.insertResource(ct,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(et.Last,nt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const dt=new ht;function ut(e,t,n){const s=[];for(const[e,r]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const n=ft(t[e]),o=ft(r);"null"!==n&&"undefined"!==n&&(n!==o&&null!=r&&s.push({field:e,expected:n,actual:o,value:r}))}return s}function ft(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function pt(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let gt=null;function yt(e){gt=e}function mt(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),gt&&gt(e,t)}function _t(e){const t={};for(const n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:_t(e)}}return t}class wt{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw mt(e,"spawn"),e}else e=this.entities_.size+1;return this.entities_.add(e),e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){mt(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t)this.tsStorage_.get(n)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(n){mt(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){mt(t,`removeParent(entity=${e})`)}}insert(e,t,n){return pe(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return pe(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return pe(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(pe(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return mt(n,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");pe(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_;return t={add:n[`add${e}`].bind(n),get:n[`get${e}`].bind(n),has:n[`has${e}`].bind(n),remove:n[`remove${e}`].bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const e=ut(t._name,t._default,s);if(e.length>0)throw new Error(pt(t._name,e))}const r={...t._default,...s};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,_t(r))}catch(n){mt(n,`insertBuiltin(${t._name}, entity=${e})`)}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return this.getBuiltinMethods(t._cppName).get(e)}catch(n){return mt(n,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(n){return mt(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){mt(n,`removeBuiltin(${t._name}, entity=${e})`)}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const r=ut(t._name,t._default,e);if(r.length>0)throw new Error(pt(t._name,r));s=e}const r=t.create(s);this.getStorage(t).set(e,r),this.worldVersion_++;let o=this.entityComponents_.get(e);return o||(o=[],this.entityComponents_.set(e,o)),-1===o.indexOf(t._id)&&o.push(t._id),r}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getComponentTypes(e){const t=[];for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.push(n)}catch{}if(this.cppRegistry_)for(const[n,s]of ge)if(pe(s)&&!t.includes(n))try{this.getBuiltinMethods(s._cppName).has(e)&&t.push(n)}catch{}const n=this.entityComponents_.get(e);if(n){const e="undefined"!=typeof window?window.__esengine_componentRegistry:void 0;if(e)for(const s of n)for(const[n,r]of e)if(r._id===s){t.push(n);break}}return t}getEntitiesWithComponents(e,t=[],n=[]){if(0===e.length&&0===t.length&&0===n.length)return this.getAllEntities();let s=e.map(e=>e._name).sort().join(",");t.length>0&&(s+="|+"+t.map(e=>e._name).sort().join(",")),n.length>0&&(s+="|-"+n.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(s);if(r&&r.version===this.worldVersion_)return r.result;let o=null,i=1/0;for(const t of e)if(!pe(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<i&&(i=n,o=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const l=o?o.keys():this.entities_;for(const t of l){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&a.push(t)}return this.queryCache_.set(s,{version:this.worldVersion_,result:a}),a}}const xt=Oe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var vt;function bt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}!function(e){e[e.Normal=0]="Normal",e[e.Additive=1]="Additive",e[e.Multiply=2]="Multiply",e[e.Screen=3]="Screen",e[e.PremultipliedAlpha=4]="PremultipliedAlpha"}(vt||(vt={}));let St=null,Pt=null,Mt=1;const Tt=new Map;function Et(e){St=e,Pt=e.getResourceManager(),Dt()}function Ct(){0!==It&&St&&(St._free(It),It=0),Tt.clear(),Mt=1,Ft=!1,kt.clear(),$t=null,Pt=null,St=null}function Rt(){if(!Pt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Pt}const At={createShader:(e,t)=>Rt().createShader(e,t),releaseShader(e){e>0&&Rt().releaseShader(e)},create(e){const t=Mt++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??vt.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return Tt.set(t,n),t},get:e=>Tt.get(e),setUniform(e,t,n){const s=Tt.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=Tt.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Tt.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Tt.get(e);return t?.blendMode??vt.Normal},setDepthTest(e,t){const n=Tt.get(e);n&&(n.depthTest=t)},getShader(e){const t=Tt.get(e);return t?.shader??0},release(e){Tt.delete(e)},isValid:e=>Tt.has(e),releaseAll(){Tt.clear()},createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??vt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Tt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Mt++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Tt.set(n,s),n},toAssetData(e,t){const n=Tt.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=Tt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ft=!1,It=0;const Bt=4096,kt=new Map;let $t=null;function Wt(e){const t=(0===It&&St&&(It=St._malloc(Bt)),It);if(0===t||!St)return{ptr:0,count:0};let n=0,s=0;const r=St.HEAPU8,o=St.HEAPU32,i=St.HEAPF32;for(const[a,l]of e){if(n+128>Bt)break;let e=kt.get(a);e||($t||($t=new TextEncoder),e=$t.encode(a),kt.set(a,e));const c=e.length,h=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=h;let d=0,u=[0,0,0,0];if("number"==typeof l)d=0,u[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)u[e]=l[e]}else"w"in l?(d=3,u=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,u=[l.x,l.y,l.z,0]):"y"in l&&(d=1,u=[l.x,l.y,0,0]);o[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=u[e],n+=4;s++}return{ptr:t,count:s}}function Dt(){if(!St||Ft)return;St.materialDataProvider=(e,t,n,s,r)=>{const o=Tt.get(e);if(!o)return St.HEAPU32[t>>2]=0,St.HEAPU32[n>>2]=0,St.HEAPU32[s>>2]=0,void(St.HEAPU32[r>>2]=0);St.HEAPU32[t>>2]=o.shader,St.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Wt(o.uniforms);St.HEAPU32[s>>2]=i,St.HEAPU32[r>>2]=a},Ft=!0}const Ut={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class zt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const s=t(),r=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{o.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Lt{constructor(e,t=""){this.cache_=new zt,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(At.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())At.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(r);return{handle:At.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}const Ot=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}]]);function Ht(e,t){Ot.set(e,t)}function jt(e){const t=Ot.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function Xt(e){return Ot.get(e)?.fields??[]}function Yt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,Ie,{value:s.name}),!1!==s.visible)for(const n of s.components)Vt(e,t,n,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function Nt(e,t,n){const s=new Map,r=n?.assetServer,o=n?.assetBaseUrl,i=new Map;r&&await async function(e,t,n,s){e=JSON.parse(JSON.stringify(e));const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ot.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,h=new Map,d=new Map,u=[];for(const e of r)u.push((async()=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)u.push((async()=>{try{const s=await t.loadMaterial(e,n);h.set(e,s.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),h.set(e,0)}})());for(const e of i)u.push((async()=>{try{const s=await t.loadBitmapFont(e,n);d.set(e,s)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.set(e,0)}})());for(const e of a)u.push((async()=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)})());await Promise.all(u);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ot.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":n[e.field]=c.get(t)??0;break;case"material":n[e.field]=h.get(t)??0;break;case"font":n[e.field]=d.get(t)??0}}}}(t,r,o,i);for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,Ie,{value:n.name}),!1!==n.visible)for(const s of n.components)Vt(e,t,s,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function Vt(e,t,n,s){if("UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=me(n.type);if(r)e.insert(t,r,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function qt(e,t){const n=e.getEntitiesWithComponents([Me]);for(const s of n){const n=e.get(s,Me);n&&(n.aspectRatio=t,e.insert(s,Me,n))}}function Gt(e,t){const n=e.getEntitiesWithComponents([Ie]);for(const s of n){const n=e.get(s,Ie);if(n&&n.value===t)return s}return null}class Jt{constructor(e){this.textureCache_=new zt,this.shaderCache_=new zt,this.jsonCache_=new zt,this.textCache_=new zt,this.binaryCache_=new zt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new zt,this.prefabCache_=new zt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.module_=e,this.canvas_=d(q.textCanvasSize,q.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Lt(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);if(!r)continue;const o=(this.textureRefCounts_.get(s)??1)-1;o<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),At.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),h="binary"===x(e)?.contentType,d=h?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,h);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),r=l.find(e=>e.name===n);if(r){const n=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,r.info.width,r.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=x(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return Nt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const r=s.metadata?.atlas;r&&n.push(this.loadSpine(s.path,r).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??n;return new Promise((n,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return At.createShader(s,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:o}=this.parseEsShader(s);if(!r||!o)throw new Error(`Invalid shader format: ${e}`);return At.createShader(r,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Kt=Oe(null,"Assets");class Qt{build(e){const t=e.wasmModule;t?e.insertResource(Kt,new Jt(t)):console.warn("AssetPlugin: No WASM module available")}}const Zt=new Qt;class en{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function tn(e,t){const n=e.getResource(Kt);n&&n.registerEmbeddedAssets(t)}async function nn(e,t,n){const{entities:s,rootId:r}=await rn(t,n?.overrides??[],n,void 0,new Set),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await Nt(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}const sn=10;async function rn(e,t,n,s,r,o=0){if(o>sn)throw new Error(`Prefab nesting depth exceeded ${sn}. Check for deep or circular nesting in: ${e.name}`);const i=new Map;let a;if(void 0===s){a=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=s;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(r?.has(s.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${s.nestedPrefab.prefabPath}`);continue}r?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await rn(e,s.nestedPrefab.overrides,n,a,r,o+1);i.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?i.get(s.parent)??null:null),l.push(...t.entities);continue}const c=i.get(s.prefabEntityId),h=s.prefabEntityId===e.rootEntityId,d={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:h?null:null!==s.parent?i.get(s.parent)??null:null,children:s.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};on(d,t),l.push(d)}const c=i.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function on(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class an{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,r=await this.assetServer_.loadPrefab(s,t?.baseUrl);return nn(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const ln=Oe(null,"Prefabs");class cn{constructor(){this.name="PrefabsPlugin",this.dependencies=[Kt]}build(e){const t=e.getResource(Kt);e.insertResource(ln,new an(e.world,t))}}const hn=new cn;let dn=null,un=0,fn=0,pn=0;const gn=new Float32Array(256);function yn(e){dn=e,un=dn._malloc(64),fn=dn._malloc(64),pn=dn._malloc(1024)}function mn(){dn&&(un&&(dn._free(un),un=0),fn&&(dn._free(fn),fn=0),pn&&(dn._free(pn),pn=0)),dn=null}function _n(){if(!dn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return dn}const wn={r:1,g:1,b:1,a:1},xn={begin(e){const t=_n();try{t.HEAPF32.set(e,un/4),t.draw_begin(un)}catch(e){mt(e,"Draw.begin")}},end(){try{_n().draw_end()}catch(e){mt(e,"Draw.end")}},line(e,t,n,s=1){try{_n().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){mt(e,"Draw.line")}},rect(e,t,n,s=!0){try{_n().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){mt(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{_n().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){mt(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,r=32){try{_n().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)}catch(e){mt(e,"Draw.circle")}},circleOutline(e,t,n,s=1,r=32){try{_n().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)}catch(e){mt(e,"Draw.circleOutline")}},texture(e,t,n,s=wn){try{_n().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){mt(e,"Draw.texture")}},textureRotated(e,t,n,s,r=wn){try{_n().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)}catch(e){mt(e,"Draw.textureRotated")}},setLayer(e){_n().draw_setLayer(e)},setDepth(e){_n().draw_setDepth(e)},getDrawCallCount:()=>dn?dn.draw_getDrawCallCount():0,getPrimitiveCount:()=>dn?dn.draw_getPrimitiveCount():0,setBlendMode(e){_n().draw_setBlendMode(e)},setDepthTest(e){_n().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=_n();s.HEAPF32.set(n,fn/4),s.draw_mesh(e,t,fn)}catch(n){mt(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=_n(),r=At.get(t);if(!r)return;if(xn.setBlendMode(r.blendMode),xn.setDepthTest(r.depthTest),0===r.uniforms.size)return void xn.drawMesh(e,r.shader,n);let o;if(s.HEAPF32.set(n,fn/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,n]of r.uniforms){const s=Sn(t);if(!(s<0)){if(bt(n))gn[o++]=10,gn[o++]=s,gn[o++]=n.slot??e++,gn[o++]=n.textureId;else if("number"==typeof n)gn[o++]=1,gn[o++]=s,gn[o++]=n;else if(Array.isArray(n)){gn[o++]=n.length,gn[o++]=s;for(let e=0;e<n.length;e++)gn[o++]=n[e]}else"w"in n?(gn[o++]=4,gn[o++]=s,gn[o++]=n.x,gn[o++]=n.y,gn[o++]=n.z,gn[o++]=n.w):"z"in n?(gn[o++]=3,gn[o++]=s,gn[o++]=n.x,gn[o++]=n.y,gn[o++]=n.z):(gn[o++]=2,gn[o++]=s,gn[o++]=n.x,gn[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(gn.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void s.draw_mesh(e,r.shader,fn);s.HEAPF32.set(r.cachedBuffer_.subarray(0,o),pn/4),s.draw_meshWithUniforms(e,r.shader,fn,pn,o)}catch(n){mt(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},vn={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17},bn=new Set;function Sn(e){const t=vn[e];return void 0!==t?t:(bn.has(e)||(bn.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(vn).join(", ")}`)),-1)}const Pn=new Map;function Mn(e,t,n){Pn.set(e,{fn:t,scene:n??""})}function Tn(e){Pn.delete(e)}function En(){Pn.clear()}var Cn;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(Cn||(Cn={}));let Rn=null,An=0,Fn=0,In=0;function Bn(e){Rn=e,An=Rn._malloc(262144),Fn=Rn._malloc(65536),In=Rn._malloc(256)}function kn(){Rn&&(An&&Rn._free(An),Fn&&Rn._free(Fn),In&&Rn._free(In),An=0,Fn=0,In=0),Rn=null}function $n(){if(!Rn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Rn}const Wn={create(e){const t=$n(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,An/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,In,r).set(o),t.geometry_init(n,An,s,In,r,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Fn,s).set(e.indices),t.geometry_setIndices16(n,Fn,s)}else{new Uint32Array(t.HEAPU8.buffer,Fn,s).set(e.indices),t.geometry_setIndices32(n,Fn,s)}}return n},updateVertices(e,t,n=0){const s=$n(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,An/4),s.geometry_updateVertices(e,An,r,n)},release(e){e>0&&$n().geometry_release(e)},isValid:e=>!(!Rn||e<=0)&&Rn.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Wn.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:Cn.Float2},{name:"a_texCoord",type:Cn.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;n.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return Wn.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Cn.Float2},{name:"a_texCoord",type:Cn.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-n);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return Wn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Cn.Float2},{name:"a_texCoord",type:Cn.Float2}],indices:new Uint16Array(i)})}};let Dn=null;function Un(e){Dn=e}function zn(){Dn&&On.isInitialized()&&On.shutdown(),Dn=null}function Ln(){if(!Dn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Dn}const On={init(e,t){try{return Ln().postprocess_init(e,t)}catch(n){return mt(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ln().postprocess_shutdown()}catch(e){mt(e,"PostProcess.shutdown")}},resize(e,t){try{Ln().postprocess_resize(e,t)}catch(n){mt(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Ln().postprocess_addPass(e,t)}catch(t){return mt(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Ln().postprocess_removePass(e)}catch(t){mt(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Ln().postprocess_setPassEnabled(e,t)}catch(t){mt(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Ln().postprocess_isPassEnabled(e)}catch(t){return mt(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{Ln().postprocess_setUniformFloat(e,t,n)}catch(n){mt(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{Ln().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){mt(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Ln().postprocess_begin()}catch(e){mt(e,"PostProcess.begin")}},end(){try{Ln().postprocess_end()}catch(e){mt(e,"PostProcess.end")}},getPassCount(){try{return Ln().postprocess_getPassCount()}catch(e){return mt(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Dn)return!1;try{return Dn.postprocess_isInitialized()}catch(e){return mt(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ln().postprocess_setBypass(e)}catch(e){mt(e,"PostProcess.setBypass")}},isBypassed(){if(!Dn)return!0;try{return Dn.postprocess_isBypassed()}catch(e){return mt(e,"PostProcess.isBypassed"),!0}},createBlur:()=>At.createShader(Hn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>At.createShader(Hn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>At.createShader(Hn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>At.createShader(Hn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},Hn="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var jn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(jn||(jn={}));let Xn=null,Yn=0;function Nn(e){Xn=e,Yn=Xn._malloc(64)}function Vn(){Xn&&Yn&&(Xn._free(Yn),Yn=0),Xn=null}const qn={init(e,t){Xn?.renderer_init(e,t)},resize(e,t){Xn?.renderer_resize(e,t)},begin(e,t){if(Xn&&Yn)try{Xn.HEAPF32.set(e,Yn/4),Xn.renderer_begin(Yn,t??0)}catch(e){mt(e,"Renderer.begin")}},flush(){try{Xn?.renderer_flush()}catch(e){mt(e,"Renderer.flush")}},end(){try{Xn?.renderer_end()}catch(e){mt(e,"Renderer.end")}},submitSprites(e){if(Xn)try{Xn.renderer_submitSprites(e._cpp)}catch(e){mt(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Xn)try{Xn.renderer_submitBitmapText(e._cpp)}catch(e){mt(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Xn)try{Xn.renderer_submitSpine?.(e._cpp)}catch(e){mt(e,"Renderer.submitSpine")}},setStage(e){Xn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Xn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Xn?.renderer_releaseTarget(e)},getTargetTexture:e=>Xn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Xn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Xn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Xn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){Xn?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){Xn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Xn?Xn.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Xn?{drawCalls:Xn.renderer_getDrawCalls(),triangles:Xn.renderer_getTriangles(),sprites:Xn.renderer_getSprites(),text:Xn.renderer_getText(),spine:Xn.renderer_getSpine?.()??0,meshes:Xn.renderer_getMeshes(),culled:Xn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Gn=null;function Jn(e){Gn=e}function Kn(){Gn=null}const Qn={enable(){Gn?.gl_enableErrorCheck(!0)},disable(){Gn?.gl_enableErrorCheck(!1)},check:e=>Gn?.gl_checkErrors(e)??0,diagnose(){Gn?.renderer_diagnose()}};class Zn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(qn.resize(s,r),On.isInitialized()&&On.getPassCount()>0&&On.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),qn.setViewport(0,0,s,r),qn.clearBuffers(3),qn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),qn.submitSprites(t),qn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):qn.submitSpine(t),qn.flush(),this.executeDrawCallbacks(n,o),qn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;qn.setViewport(s.x,s.y,s.w,s.h),qn.setScissor(s.x,s.y,s.w,s.h,!0),qn.clearBuffers(r),qn.setScissor(0,0,0,0,!1),qn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),qn.submitSprites(t),qn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):qn.submitSpine(t),qn.flush(),this.executeDrawCallbacks(n,o),qn.end()}executeDrawCallbacks(e,t){const n=Pn;if(n.size>0){xn.begin(e);const s=[];for(const[e,r]of n.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}xn.end();for(const e of s)Tn(e)}}}const es="__scene_transition_overlay__";class ts{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class ns{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,Be,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),Mn(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=On.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){On.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,Be)){const n=this.app_.world.get(e,Be);n.persistent=t,this.app_.world.insert(e,Be,n)}}}class ss{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_)return void console.warn(`[SceneManager] Transition already in progress, ignoring switchTo("${e}")`);"fade"!==(t?.transition??"none")?(this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)):await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(n=>{const s=t.duration??q.sceneTransitionDuration,r=t.color??{...q.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:r,targetScene:e,options:t,resolve:n},Mn(es,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;xn.setLayer(9999),xn.setDepth(9999),xn.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{n&&n!==e&&await this.unload(n,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,Tn(es)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Tn(es),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new ts(t);this.scenes_.set(e,n);const s=new ns(n,this.app_);this.contexts_.set(e,s);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Kt)?this.app_.getResource(Kt):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Kt)&&(t.assetServer=this.app_.getResource(Kt));const s=await Nt(this.app_.world,r,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,Be,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=os(this.app_,e,s);this.app_.addSystemToSchedule(n,t)}return t.setup&&await t.setup(s),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new ts(t);this.scenes_.set(e,n);const s=new ns(n,this.app_);this.contexts_.set(e,s);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Kt)?this.app_.getResource(Kt):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Kt)&&(t.assetServer=this.app_.getResource(Kt));const s=await Nt(this.app_.world,r,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,Be,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=os(this.app_,e,s);this.app_.addSystemToSchedule(n,t)}return t.setup&&await t.setup(s),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const r=t?.keepPersistent??!0;for(const e of n.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,Be)){if(this.app_.world.get(e,Be).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())Tn(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{On.removePass(e)}catch{}n.postProcessPasses.length=0,this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(t&&"running"===t.status){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Pe)){const n=this.app_.world.get(e,Pe);t.savedAlphas.set(e,n.color.a),n.color={...n.color,a:0},this.app_.world.insert(e,Pe,n)}}}wake(e){const t=this.scenes_.get(e);if(t&&"sleeping"===t.status){t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Pe)){const n=this.app_.world.get(e,Pe),s=t.savedAlphas.get(e)??1;n.color={...n.color,a:s},this.app_.world.insert(e,Pe,n)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{On.setEnabled(n,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,n]of this.scenes_)"running"===n.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const rs=Oe(null,"SceneManager");function os(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(rs).getSceneStatus(t)&&n._fn(...s)}}}const is=nt([je(rs),He(Ne)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),as={name:"SceneManager",build(e){const t=new ss(e);e.insertResource(rs,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(rs),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(et.Startup,n),e.addSystemToSchedule(et.Last,is)}};class ls{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=u(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(et.Last);else{this.runSchedule(et.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(et.FixedPreUpdate),this.runSchedule(et.FixedUpdate),this.runSchedule(et.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(et.PreUpdate),this.runSchedule(et.Update),this.runSchedule(et.PostUpdate),this.runSchedule(et.Last),this.step_pending_&&(this.step_pending_=!1)}requestAnimationFrame(this.mainLoop)},this.world_=new wt,this.resources_=new Ye;for(const e of Object.values(et))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new ls}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(et.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(et.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return yt(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(rs).register(e),this}setInitialScene(e){return this.getResource(rs).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new at(this.world_,this.resources_),this.resources_.insert(Ne,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(et.Startup),this.lastTime_=u(),this.mainLoop())}quit(){this.running_=!1,En();const e=[Kn,Vn,zn,kn,Ct,mn];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const r=t.get(s);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,r=new Set,o=i=>{if(s.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&o(n)}r.delete(i),s.add(i),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));for(const e of n)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(Ne);t.delta=e,t.elapsed+=e,t.frameCount++}}function cs(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const hs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ds(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case ve.FixedWidth:return o;case ve.FixedHeight:return i;case ve.Expand:return Math.max(o,i);case ve.Shrink:return Math.min(o,i);case ve.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function us(e,t,n,s,r,o){if(0===n||0===s)return[];const i=e.registry_getCameraEntities(t);if(0===i.length)return[];const a=o&&r?i.filter(e=>{const t=r.tryGet(e,Be);return!t||""===t.scene||o.has(t.scene)}):i;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const r=t.getCamera(e),o=t.getLocalTransform(e),i={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=i.w*n/(i.h*s);let h,d=0,u=0;if(r.projectionType===we.Orthographic){if(u=r.orthoSize,l){u=ds(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}d=u*a,h=ps(-d,d,-u,u,-r.farPlane,r.farPlane)}else h=ys(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=_s(o.position.x,o.position.y,o.position.z);c.push({entity:e,viewProjection:new Float32Array(xs(h,f)),viewportRect:i,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:u,cameraX:o.position.x,cameraY:o.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const fs=new Float32Array(16);function ps(e,t,n,s,r,o){const i=fs;i.fill(0);const a=t-e,l=s-n,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+n)/l,i[14]=-(o+r)/c,i[15]=1,i}const gs=new Float32Array(16);function ys(e,t,n,s){const r=gs;r.fill(0);const o=1/Math.tan(e/2),i=n-s;return r[0]=o/t,r[5]=o,r[10]=(s+n)/i,r[11]=-1,r[14]=2*s*n/i,r}const ms=new Float32Array(16);function _s(e,t,n){const s=ms;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}const ws=new Float32Array(16);function xs(e,t){const n=ws;for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}var vs,bs,Ss;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(vs||(vs={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(bs||(bs={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Ss||(Ss={}));const Ps=le("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:vs.Left,verticalAlign:bs.Top,wordWrap:!0,overflow:Ss.Visible,lineHeight:1.2}),Ms=le("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class Ts{constructor(e){this.cache=new Map,this.module=e,this.canvas=d(q.textCanvasSize,q.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),h=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),u=Math.ceil(l.length*c),f=r?Math.ceil(o):d+2*h,p=r?Math.ceil(i):u+2*h;if(r&&e.overflow===Ss.Ellipsis&&u>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const g=Math.round(255*e.color.r),y=Math.round(255*e.color.g),m=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${g}, ${y}, ${m}, ${_})`,r&&e.overflow===Ss.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(r)switch(e.verticalAlign){case bs.Top:x=h;break;case bs.Middle:x=(p-w)/2;break;case bs.Bottom:x=p-w-h;break;default:x=h}else x=h;let v=x;for(const t of l){let s;switch(e.align){case vs.Left:s=h;break;case vs.Center:s=f/2;break;case vs.Right:s=f-h;break;default:s=h}n.fillText(t,s,v),v+=c}r&&e.overflow===Ss.Clip&&n.restore();const b=n.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(f,p,M,S.length,1,!0);return this.module._free(M),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const r=this.renderText(t,n);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case vs.Left:return"left";case vs.Center:return"center";case vs.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function Es(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function Cs(e,t,n){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(n?n.size.x:0)||e.containerHeight!==(n?n.size.y:0)}class Rs{build(e){ye("Text",Ps);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Ts(t),s=e.world,r=new Map;e.addSystemToSchedule(et.PreUpdate,nt([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Ps));for(const e of r.keys())s.valid(e)&&s.has(e,Ps)||r.delete(e);const e=s.getEntitiesWithComponents([Ps]);for(const t of e){const e=s.get(t,Ps),o=s.has(t,Ms)?s.get(t,Ms):null,i=r.get(t);if(i&&!Cs(i,e,o))continue;s.has(t,Pe)||s.insert(t,Pe,{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=n.renderForEntity(t,e,o),l=s.get(t,Pe);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,Pe,l),r.set(t,Es(e,o))}}))}}const As=new Rs,Fs=le("UIMask",{enabled:!0,mode:"scissor"});function Is(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,o-s)}}function Bs(e,t,n,s,r,o,i,a,l,c,h){const d=e-n*r,u=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function g(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*h]}const[y,m]=g(d,f),[_,w]=g(u,p),x=Math.min(y,_),v=Math.max(y,_),b=Math.min(m,w),S=Math.max(m,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function ks(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],h=e[7],d=e[8],u=e[9],f=e[10],p=e[11],g=e[12],y=e[13],m=e[14],_=e[15],w=s*l-r*a,x=s*c-o*a,v=s*h-i*a,b=r*c-o*l,S=r*h-i*l,P=o*h-i*c,M=d*y-u*g,T=d*m-f*g,E=d*_-p*g,C=u*m-f*y,R=u*_-p*y,A=f*_-p*m;let F=w*A-x*R+v*C+b*E-S*T+P*M;return 0===F||(F=1/F,n[0]=(l*A-c*R+h*C)*F,n[1]=(o*R-r*A-i*C)*F,n[2]=(y*P-m*S+_*b)*F,n[3]=(f*S-u*P-p*b)*F,n[4]=(c*E-a*A-h*T)*F,n[5]=(s*A-o*E+i*T)*F,n[6]=(m*v-g*P-_*x)*F,n[7]=(d*P-f*v+p*x)*F,n[8]=(a*R-l*E+h*M)*F,n[9]=(r*E-s*R-i*M)*F,n[10]=(g*S-y*v+_*w)*F,n[11]=(u*v-d*S-p*w)*F,n[12]=(l*T-a*C-c*M)*F,n[13]=(s*C-r*T+o*M)*F,n[14]=(y*x-g*b-m*w)*F,n[15]=(d*b-u*x+f*w)*F),n}function $s(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],h=n[1]*a+n[5]*l+n[13],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:h/d}}function Ws(e,t,n,s,r,o,i,a){return e>=n-r*i&&e<=n+r*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function Ds(e,t,n,s,r,o,i,a,l,c){const h=2*Math.atan2(l,c),d=Math.sin(-h),u=Math.cos(-h),f=e-n,p=t-s,g=f*u-p*d+n,y=f*d+p*u+s;return g>=n-r*i&&g<=n+r*(1-i)&&y>=s-o*a&&y<=s+o*(1-a)}function Us(e,t,n,s,r,o,i){if(!e.has(t,Ms)||!e.has(t,Se))return null;const a=e.get(t,Ms),l=e.get(t,Se),c=a.size.x*l.scale.x,h=a.size.y*l.scale.y;return Bs(l.position.x,l.position.y,c,h,a.pivot.x,a.pivot.y,n,s,r,o,i)}function zs(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Fs]);if(0===l.length)return;const c=[],h=[],d=new Set,u=new Set;for(const e of l){const n=t.get(e,Fs);n.enabled&&(d.add(e),"stencil"===n.mode?(h.push(e),u.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,r,o,i,a,l,c){const h=[];for(const e of s){let n=!0,s=e;for(;t.has(s,Ce);){const e=t.get(s,Ce);if(r.has(e.entity)){if("scissor"===t.get(e.entity,Fs).mode){n=!1;break}}s=e.entity}n&&h.push(e)}function d(s,h){const u=e.getChildEntities(n,s);for(const n of u){let s=h;if(r.has(n)){if("scissor"===t.get(n,Fs).mode){const e=Us(t,n,o,i,a,l,c);e&&(s=Is(h,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of h){const n=Us(t,e,o,i,a,l,c);n&&d(e,n)}}(e,t,n,c,d,s,r,o,i,a),h.length>0&&function(e,t,n,s,r){e.renderer_clearStencil();const o=[];for(const e of s){let n=!0,s=e;for(;t.has(s,Ce);){const e=t.get(s,Ce);if(r.has(e.entity)){n=!1;break}s=e.entity}n&&o.push(e)}let i=1;function a(t,s){e.renderer_setEntityStencilMask(t,s);const o=e.getChildEntities(n,t);for(const t of o)if(r.has(t)){a(t,i++)}else e.renderer_setEntityStencilTest(t,s),l(t,s)}function l(t,s){const o=e.getChildEntities(n,t);for(const t of o)if(r.has(t)){a(t,i++)}else e.renderer_setEntityStencilTest(t,s),l(t,s)}for(const e of o){a(e,i++)}}(e,t,n,h,u)}catch(t){e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class Ls{build(e){if(ye("UIMask",Fs),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(zs(e.wasmModule,e.world))}}const Os=new Ls,Hs=le("Interactable",{enabled:!0,blockRaycast:!0}),js=le("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Xs;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Xs||(Xs={}));const Ys=le("Button",{state:Xs.Normal,transition:null,enabled:!0});class Ns{constructor(){this.events_=[]}emit(e,t,n){const s=n??e;this.events_.push({entity:e,type:t,target:s,currentTarget:e})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const Vs=Oe(new Ns,"UIEvents"),qs=ce("ScreenSpace");function Gs(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,h=o.bottom+e.y*a,d=o.bottom+t.y*a;let u,f,p,g;if(e.x===t.x){const e=l+n.x,t=.5*r.x;u=e-t,p=e+t}else u=l+n.x,p=c+s.x;if(e.y===t.y){const e=h+n.y,t=.5*r.y;f=e-t,g=e+t}else f=h+n.y,g=d+s.y;return{centerX:.5*(u+p),centerY:.5*(f+g),width:p-u,height:g-f,rect:{left:u,bottom:f,right:p,top:g}}}function Js(e){return{anchorMinX:e.anchorMin.x,anchorMinY:e.anchorMin.y,anchorMaxX:e.anchorMax.x,anchorMaxY:e.anchorMax.y,offsetMinX:e.offsetMin.x,offsetMinY:e.offsetMin.y,offsetMaxX:e.offsetMax.x,offsetMaxY:e.offsetMax.y,sizeX:e.size.x,sizeY:e.size.y}}function Ks(e,t){return e.anchorMinX!==t.anchorMin.x||e.anchorMinY!==t.anchorMin.y||e.anchorMaxX!==t.anchorMax.x||e.anchorMaxY!==t.anchorMax.y||e.offsetMinX!==t.offsetMin.x||e.offsetMinY!==t.offsetMin.y||e.offsetMaxX!==t.offsetMax.x||e.offsetMaxY!==t.offsetMax.y||e.sizeX!==t.size.x||e.sizeY!==t.size.y}function Qs(e,t){let n=t;for(;;){if(e.has(n,qs))return n;if(!e.has(n,Ce))return null;const t=e.get(n,Ce);if(!e.valid(t.entity))return null;n=t.entity}}function Zs(e,t,n,s,r,o){if(!e.has(t,Ms))return;const i=e.get(t,Ms),a=Gs(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,be);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,be,l),!e.has(t,Re))return;const c=e.get(t,Re);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&Zs(e,t,a.rect,a.centerX,a.centerY,!1)}class er{build(e){ye("UIRect",Ms);const t=e.world,n=new Map;let s=NaN,r=NaN,o=NaN,i=NaN;e.addSystemToSchedule(et.PreUpdate,nt([He(xt)],e=>{if(!e.valid)return;const a={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},l=.5*(a.left+a.right),c=.5*(a.bottom+a.top),h=s!==e.worldLeft||r!==e.worldBottom||o!==e.worldRight||i!==e.worldTop;s=e.worldLeft,r=e.worldBottom,o=e.worldRight,i=e.worldTop;const d=new Set;if(h){const e=t.getEntitiesWithComponents([qs,Ms,be]);for(const t of e)d.add(t)}const u=t.getEntitiesWithComponents([Ms]);for(const e of u){const s=t.get(e,Ms),r=n.get(e);if(!r||Ks(r,s)){const n=Qs(t,e);null!==n&&d.add(n)}}for(const e of n.keys())if(!t.valid(e)||!t.has(e,Ms)){n.delete(e);const s=Qs(t,e);null!==s&&d.add(s)}for(const e of d)Zs(t,e,a,l,c,!0);for(const e of u){const s=t.get(e,Ms);n.set(e,Js(s))}},{name:"UILayoutSystem"}))}}const tr=new er,nr=new Float32Array(16),sr=new Float32Array(16);let rr=!0,or=1;function ir(e,t,n,s){t.emit(n,s,n);let r=n;for(;e.has(r,Ce);){const o=e.get(r,Ce).entity;if(!e.valid(o))break;if(!e.has(o,Hs)){r=o;continue}const i=e.get(o,Hs);if(i.enabled&&t.emit(o,s,n),i.blockRaycast)break;r=o}}class ar{build(e){ye("Interactable",Hs),ye("Button",Ys);const t=e.world,n=new Ns;e.insertResource(Vs,n);let s=null,r=null;or="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(et.PreUpdate,nt([He(ct),He(xt)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([js]);for(const e of i){const n=t.get(e,js);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a=e.mouseX*or,l=o.screenH-e.mouseY*or;!function(e){let t=!1;for(let n=0;n<16;n++)if(sr[n]!==e[n]){t=!0;break}t&&(sr.set(e),rr=!0)}(o.viewProjection),rr&&(ks(o.viewProjection,nr),rr=!1);const c=$s(a,l,nr,o.vpX,o.vpY,o.vpW,o.vpH),h=t.getEntitiesWithComponents([Hs,Ms,Se]);let d=null,u=-1/0;for(const e of h){t.has(e,js)||t.insert(e,js);if(!t.get(e,Hs).enabled)continue;const n=t.get(e,Se),s=t.get(e,Ms),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(Ds(c.x,c.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y,n.rotation.z,n.rotation.w)){let n=0;t.has(e,Pe)&&(n=t.get(e,Pe).layer),n>=u&&(u=n,d=e)}}if(s!==d){if(null!==s&&t.valid(s)&&t.has(s,js)){t.get(s,js).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,js).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,js);e.pressed=!0,e.justPressed=!0,r=d,ir(t,n,d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,js)){const e=t.get(r,js);e.pressed=!1,e.justReleased=!0,ir(t,n,r,"release"),r===s&&ir(t,n,r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(et.Update,nt([],()=>{const e=t.getEntitiesWithComponents([Ys]);for(const n of e){if(t.has(n,Hs)||t.insert(n,Hs,{enabled:!0}),!t.has(n,js))continue;const e=t.get(n,js),s=t.get(n,Ys),r=t.get(n,Hs),o=s.state;if(r.enabled?e.pressed?s.state=Xs.Pressed:e.hovered?s.state=Xs.Hovered:s.state=Xs.Normal:s.state=Xs.Disabled,o!==s.state&&s.transition&&t.has(n,Pe)){const e=t.get(n,Pe),r=s.transition;switch(s.state){case Xs.Normal:e.color={...r.normalColor};break;case Xs.Hovered:e.color={...r.hoveredColor};break;case Xs.Pressed:e.color={...r.pressedColor};break;case Xs.Disabled:e.color={...r.disabledColor}}t.insert(n,Pe,e)}}},{name:"ButtonSystem"}))}}const lr=new ar,cr=le("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class hr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){ye("TextInput",cr);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=d(q.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,h=0;const u=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!u)return;const f=u,p=()=>{a||null===i||w()},g=()=>{a=!0},y=()=>{a=!1,w()},m=t=>{if(null===i)return;if("Escape"===t.key)return void v();const s=n.get(i,cr);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(Vs).emit(i,"submit"),void v()}let r=s.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?r=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=s.value.length),r!==s.cursorPos&&(s.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,s.dirty=!0,b())},_=()=>{if(null!==i&&n.valid(i)&&n.has(i,cr)){const e=n.get(i,cr);e.focused=!1,e.dirty=!0}i=null};function w(){if(null===i||!n.valid(i))return;const t=n.get(i,cr);if(t.readOnly)return;let s=f.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),f.value=s),s!==t.value){t.value=s;e.getResource(Vs).emit(i,"change")}t.cursorPos=f.selectionStart??s.length,t.dirty=!0,b()}function x(e){if(i===e)return;v();const t=n.get(e,cr);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),b())}function v(){if(null!==i&&n.valid(i)&&n.has(i,cr)){const e=n.get(i,cr);e.focused=!1,e.dirty=!0}i=null,f.blur()}function b(){l=!0,c=0}function S(e,i,a,c){(r.width<a||r.height<c)&&(r.width=ur(Math.max(r.width,a)),r.height=ur(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const h=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,u=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),g=i.padding;if(i.multiline){const e=dr(o,u,a-2*g);let t=g;for(const n of e)o.fillText(n,g,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(u,g,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=dr(o,i.value.substring(0,i.cursorPos),a-2*g),r=e.length>0?e[e.length-1]:"";t=g+o.measureText(r).width,n=g+(e.length-1)*p,s=p}else t=g+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const y=o.getImageData(0,0,a,c),m=new Uint8Array(y.data.buffer),_=t.getResourceManager(),w=t._malloc(m.length);t.HEAPU8.set(m,w);const x=s.get(e);void 0!==x&&_.releaseTexture(x);const v=_.createTexture(a,c,w,m.length,1,!0);s.set(e,v),t._free(w);const b=n.get(e,Pe);b.texture=v,b.size.x=a,b.size.y=c,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},n.insert(e,Pe,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",g),f.addEventListener("compositionend",y),f.addEventListener("keydown",m),f.addEventListener("blur",_),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",g),f.removeEventListener("compositionend",y),f.removeEventListener("keydown",m),f.removeEventListener("blur",_),f.remove()},e.addSystemToSchedule(et.PreUpdate,nt([He(Vs)],e=>{const t=n.getEntitiesWithComponents([cr,Hs]);for(const e of t){if(!n.has(e,js))continue;if(n.get(e,js).justPressed)return void x(e)}if(null!==i){const e=n.getEntitiesWithComponents([Hs]);for(const t of e){if(n.has(t,cr))continue;if(!n.has(t,js))continue;if(n.get(t,js).justPressed)return void v()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(et.PreUpdate,nt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===h?0:(e-h)/1e3;if(h=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,cr)))){n.get(i,cr).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,cr)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([cr,Ms]);for(const e of a){const t=n.get(e,cr);if(!t.dirty)continue;const s=n.get(e,Ms),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,Pe)||n.insert(e,Pe,{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),S(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function dr(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function ur(e){let t=1;for(;t<e;)t*=2;return t}const fr=new hr,pr={Simple:0,Sliced:1,Tiled:2,Filled:3},gr={Horizontal:0,Vertical:1},yr={Left:0,Right:1,Bottom:2,Top:3},mr=le("Image",{texture:K,color:{r:1,g:1,b:1,a:1},imageType:pr.Simple,fillMethod:gr.Horizontal,fillOrigin:yr.Left,fillAmount:1,preserveAspect:!1,layer:0,material:0,enabled:!0});const _r=new class{build(e){ye("Image",mr);const t=e.world;e.addSystemToSchedule(et.PreUpdate,nt([],()=>{const e=t.getEntitiesWithComponents([mr]);for(const n of e){const e=t.get(n,mr);t.has(n,Pe)||t.insert(n,Pe,{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const s=t.get(n,Pe);if(s.texture=e.texture,s.color.r=e.color.r,s.color.g=e.color.g,s.color.b=e.color.b,s.color.a=e.color.a,s.layer=e.layer,s.material=e.material,t.has(n,Ms)){const e=t.get(n,Ms);s.size.x=e.size.x,s.size.y=e.size.y}if(s.uvOffset.x=0,s.uvOffset.y=0,s.uvScale.x=1,s.uvScale.y=1,e.imageType===pr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount));e.fillMethod===gr.Horizontal?e.fillOrigin===yr.Left?(s.uvScale.x=t,s.size.x*=t):(s.uvOffset.x=1-t,s.uvScale.x=t,s.size.x*=t):e.fillOrigin===yr.Bottom?(s.uvScale.y=t,s.size.y*=t):(s.uvOffset.y=1-t,s.uvScale.y=t,s.size.y*=t)}t.insert(n,Pe,s)}},{name:"ImageSystem"}))}},wr=le("Toggle",{isOn:!0,graphicEntity:0,transition:null,enabled:!0});const xr=new class{build(e){ye("Toggle",wr);const t=e.world;e.addSystemToSchedule(et.Update,nt([He(Vs)],e=>{const n=t.getEntitiesWithComponents([wr]);for(const s of n){if(t.has(s,Hs)||t.insert(s,Hs,{enabled:!0}),!t.has(s,js))continue;const n=t.get(s,js),r=t.get(s,wr),o=t.get(s,Hs);if(n.justPressed&&o.enabled&&(r.isOn=!r.isOn,e.emit(s,"change")),r.graphicEntity&&t.valid(r.graphicEntity)){const e=r.graphicEntity;if(t.has(e,Pe)){const n=t.get(e,Pe);n.color.a=r.isOn?1:0,t.insert(e,Pe,n)}}if(r.transition&&t.has(s,Pe)){const e=t.get(s,Pe),i=r.transition;o.enabled?n.pressed?e.color={...i.pressedColor}:n.hovered?e.color={...i.hoveredColor}:e.color={...i.normalColor}:e.color={...i.disabledColor},t.insert(s,Pe,e)}}},{name:"ToggleSystem"}))}};var vr;!function(e){e[e.LeftToRight=0]="LeftToRight",e[e.RightToLeft=1]="RightToLeft",e[e.BottomToTop=2]="BottomToTop",e[e.TopToBottom=3]="TopToBottom"}(vr||(vr={}));const br=le("ProgressBar",{value:0,fillEntity:0,direction:vr.LeftToRight});const Sr=new class{build(e){ye("ProgressBar",br);const t=e.world;e.addSystemToSchedule(et.PreUpdate,nt([],()=>{const e=t.getEntitiesWithComponents([br,Ms]);for(const n of e){const e=t.get(n,br);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=e.fillEntity;if(!t.has(s,Ms))continue;const r=t.get(s,Ms),o=Math.max(0,Math.min(1,e.value));switch(e.direction){case vr.LeftToRight:r.anchorMin={x:0,y:0},r.anchorMax={x:o,y:1};break;case vr.RightToLeft:r.anchorMin={x:1-o,y:0},r.anchorMax={x:1,y:1};break;case vr.BottomToTop:r.anchorMin={x:0,y:0},r.anchorMax={x:1,y:o};break;case vr.TopToBottom:r.anchorMin={x:0,y:1-o},r.anchorMax={x:1,y:1}}r.offsetMin={x:0,y:0},r.offsetMax={x:0,y:0},t.insert(s,Ms,r)}},{name:"ProgressBarSystem"}))}},Pr=le("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Mr=le("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}}),Tr=new Float32Array(16),Er=new Float32Array(16);let Cr=!0;function Rr(e,t,n){const s=e.mouseX*n,r=t.screenH-e.mouseY*n;return function(e){let t=!1;for(let n=0;n<16;n++)if(Er[n]!==e[n]){t=!0;break}t&&(Er.set(e),Cr=!0)}(t.viewProjection),Cr&&(ks(t.viewProjection,Tr),Cr=!1),$s(s,r,Tr,t.vpX,t.vpY,t.vpW,t.vpH)}const Ar=new class{build(e){ye("Draggable",Pr),ye("DragState",Mr);const t=e.world,n=e.getResource(Vs);let s=null,r={x:0,y:0},o=null;const i="undefined"!=typeof window&&window.devicePixelRatio||1;e.addSystemToSchedule(et.PreUpdate,nt([He(ct),He(xt)],(e,a)=>{if(!a.valid)return;const l=Rr(e,a,i);if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Pr,js]);let n=null;for(const s of e){if(!t.get(s,Pr).enabled)continue;t.get(s,js).hovered&&(n=s)}if(null!==n){s=n,r={x:l.x,y:l.y},t.has(n,Mr)||t.insert(n,Mr);const e=t.get(n,Mr),o=t.get(n,Se);e.startWorldPos={x:o.position.x,y:o.position.y},e.currentWorldPos={x:o.position.x,y:o.position.y},e.pointerStartWorld={x:l.x,y:l.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,Mr)){t.get(s,Mr).isDragging=!1}s=null}if(null!==s&&null===o){if(!t.valid(s))return void(s=null);const e=l.x-r.x,i=l.y-r.y,c=Math.sqrt(e*e+i*i),h=t.get(s,Pr);if(c*(a.vpW/(a.worldRight-a.worldLeft))>=h.dragThreshold){o=s,s=null;t.get(o,Mr).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Mr))return void(o=null);const s=t.get(o,Mr),r=t.get(o,Pr),i=l.x-s.pointerStartWorld.x,a=l.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+i,h=s.startWorldPos.y+a;const d=function(e,t,n,s){let r=e.lockX?t.startWorldPos.x:n,o=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(r=Math.max(r,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(r=Math.min(r,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:r,y:o}}(r,s,c,h);c=d.x,h=d.y;const u=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-u,y:h-f},s.currentWorldPos={x:c,y:h},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:h-s.startWorldPos.y},t.has(o,be)){const e=function(e,t,n,s){if(!e.has(t,Ce))return{x:n,y:s};const r=e.get(t,Ce).entity;if(!e.valid(r)||!e.has(r,Se))return{x:n,y:s};const o=e.get(r,Se),i=0!==o.scale.x?o.scale.x:1,a=0!==o.scale.y?o.scale.y:1,l=2*Math.atan2(o.rotation.z,o.rotation.w),c=Math.sin(-l),h=Math.cos(-l);return{x:(n*h-s*c)/i,y:(n*c+s*h)/a}}(t,o,s.deltaWorld.x,s.deltaWorld.y),n=t.get(o,be);n.position.x+=e.x,n.position.y+=e.y,t.insert(o,be,n)}n.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},Fr=le("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135});const Ir=new class{build(e){ye("ScrollView",Fr);const t=e.world,n=new Map,s=new Float32Array(16),r="undefined"!=typeof window&&window.devicePixelRatio||1;let o=0;e.addSystemToSchedule(et.PreUpdate,nt([He(ct),He(xt)],(e,i)=>{const a=performance.now()/1e3,l=o>0?Math.min(a-o,.05):0;if(o=a,!i.valid)return;const c=e.mouseX*r,h=i.screenH-e.mouseY*r;ks(i.viewProjection,s);const d=$s(c,h,s,i.vpX,i.vpY,i.vpW,i.vpH),u=t.getEntitiesWithComponents([Fr,Ms]);for(const s of u){t.has(s,Hs)||t.insert(s,Hs,{enabled:!0,blockRaycast:!0}),t.has(s,Fs)||t.insert(s,Fs,{enabled:!0,mode:"scissor"});const r=t.get(s,Fr),o=t.get(s,Ms);let i=n.get(s);i||(i={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0},n.set(s,i));const a=t.has(s,js)?t.get(s,js):null;if(a?.justPressed&&(i.isDragging=!0,i.lastWorldX=d.x,i.lastWorldY=d.y,i.velocityX=0,i.velocityY=0),i.isDragging&&e.isMouseButtonDown(0)){const e=d.x-i.lastWorldX,t=d.y-i.lastWorldY;r.horizontalEnabled&&(r.scrollX-=e,i.velocityX=l>0?-e/l:0),r.verticalEnabled&&(r.scrollY-=t,i.velocityY=l>0?-t/l:0),i.lastWorldX=d.x,i.lastWorldY=d.y}if(i.isDragging&&e.isMouseButtonReleased(0)&&(i.isDragging=!1),a?.hovered){const t=e.getScrollDelta();r.verticalEnabled&&0!==t.y&&(r.scrollY+=.1*t.y,i.velocityY=0),r.horizontalEnabled&&0!==t.x&&(r.scrollX+=.1*t.x,i.velocityX=0)}if(!i.isDragging&&r.inertia&&l>0){const e=Math.pow(r.decelerationRate,l);r.horizontalEnabled&&Math.abs(i.velocityX)>.1?(r.scrollX+=i.velocityX*l,i.velocityX*=e):i.velocityX=0,r.verticalEnabled&&Math.abs(i.velocityY)>.1?(r.scrollY+=i.velocityY*l,i.velocityY*=e):i.velocityY=0}const c=o.size.x,h=o.size.y,u=Math.max(0,r.contentWidth-c),f=Math.max(0,r.contentHeight-h);if(r.scrollX=Math.max(0,Math.min(r.scrollX,u)),r.scrollY=Math.max(0,Math.min(r.scrollY,f)),0!==r.contentEntity&&t.valid(r.contentEntity)){const e=r.contentEntity;if(t.has(e,be)){const n=t.get(e,be);n.position.x=-r.scrollX,n.position.y=r.scrollY,t.insert(e,be,n)}}}},{name:"ScrollViewSystem"}))}};var Br;!function(e){e[e.LeftToRight=0]="LeftToRight",e[e.RightToLeft=1]="RightToLeft",e[e.BottomToTop=2]="BottomToTop",e[e.TopToBottom=3]="TopToBottom"}(Br||(Br={}));const kr=le("Slider",{value:0,minValue:0,maxValue:1,direction:Br.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1,enabled:!0});const $r=new class{build(e){ye("Slider",kr);const t=e.world,n=new Float32Array(16),s="undefined"!=typeof window&&window.devicePixelRatio||1;let r=null;e.addSystemToSchedule(et.PreUpdate,nt([He(ct),He(xt)],(e,o)=>{if(!o.valid)return;const i=e.mouseX*s,a=o.screenH-e.mouseY*s;ks(o.viewProjection,n);const l=$s(i,a,n,o.vpX,o.vpY,o.vpW,o.vpH),c=t.getEntitiesWithComponents([kr,Ms,Se]);for(const n of c){t.has(n,Hs)||t.insert(n,Hs,{enabled:!0,blockRaycast:!0});const s=t.get(n,kr),o=t.get(n,Ms),i=t.get(n,Se),a=t.has(n,js)?t.get(n,js):null;if(a?.justPressed&&(r=n),r===n&&e.isMouseButtonDown(0)){const e=o.size.x*i.scale.x,t=o.size.y*i.scale.y,n=i.position.x-o.pivot.x*e,r=i.position.y-o.pivot.y*t;let a;switch(s.direction){case Br.LeftToRight:a=e>0?(l.x-n)/e:0;break;case Br.RightToLeft:a=e>0?1-(l.x-n)/e:0;break;case Br.BottomToTop:a=t>0?(l.y-r)/t:0;break;case Br.TopToBottom:a=t>0?1-(l.y-r)/t:0}a=Math.max(0,Math.min(1,a));let c=s.minValue+a*(s.maxValue-s.minValue);s.wholeNumbers&&(c=Math.round(c)),s.value=Math.max(s.minValue,Math.min(s.maxValue,c))}r===n&&e.isMouseButtonReleased(0)&&(r=null);const c=s.maxValue-s.minValue,h=c>0?(s.value-s.minValue)/c:0;if(0!==s.fillEntity&&t.valid(s.fillEntity)){const e=s.fillEntity;if(t.has(e,Ms)){const n=t.get(e,Ms);switch(s.direction){case Br.LeftToRight:n.anchorMin={x:0,y:0},n.anchorMax={x:h,y:1};break;case Br.RightToLeft:n.anchorMin={x:1-h,y:0},n.anchorMax={x:1,y:1};break;case Br.BottomToTop:n.anchorMin={x:0,y:0},n.anchorMax={x:1,y:h};break;case Br.TopToBottom:n.anchorMin={x:0,y:1-h},n.anchorMax={x:1,y:1}}t.insert(e,Ms,n)}}if(0!==s.handleEntity&&t.valid(s.handleEntity)){const e=s.handleEntity;if(t.has(e,Ms)){const n=t.get(e,Ms);switch(s.direction){case Br.LeftToRight:n.anchorMin={x:h,y:0},n.anchorMax={x:h,y:1};break;case Br.RightToLeft:n.anchorMin={x:1-h,y:0},n.anchorMax={x:1-h,y:1};break;case Br.BottomToTop:n.anchorMin={x:0,y:h},n.anchorMax={x:1,y:h};break;case Br.TopToBottom:n.anchorMin={x:0,y:1-h},n.anchorMax={x:1,y:1-h}}t.insert(e,Ms,n)}}}},{name:"SliderSystem"}))}},Wr=le("Focusable",{tabIndex:0,isFocused:!1});class Dr{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Ur=Oe(new Dr,"FocusManager");const zr=new class{build(e){ye("Focusable",Wr);const t=e.world,n=new Dr;e.insertResource(Ur,n),e.addSystemToSchedule(et.Update,nt([He(ct),He(Vs)],(e,s)=>{const r=t.getEntitiesWithComponents([Wr]);for(const e of r){if(!t.has(e,js))continue;t.get(e,js).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of r){const s=t.get(n,Wr);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const i=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===i?a?s.length-1:0:a?(i-1+s.length)%s.length:(i+1)%s.length,o(s[l])}function o(e){const r=n.focusedEntity;if(r===e)return;if(null!==r&&t.valid(r)&&t.has(r,Wr)){t.get(r,Wr).isFocused=!1,s.emit(r,"hover_exit",r)}n.focus(e);t.get(e,Wr).isFocused=!0,s.emit(e,"hover_enter",e)}},{name:"FocusSystem"}))}},Lr=le("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});const Or=new class{build(e){ye("SafeArea",Lr);const t=e.world;let n={top:0,bottom:0,left:0,right:0},s=0;e.addSystemToSchedule(et.PreUpdate,nt([],()=>{s++%60==0&&(n=function(){if("undefined"==typeof document)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}());const e=t.getEntitiesWithComponents([Lr,Ms]);for(const s of e){const e=t.get(s,Lr),r=t.get(s,Ms);let o=!1;const i=e.applyTop?n.top:0,a=e.applyBottom?n.bottom:0,l=e.applyLeft?n.left:0,c=e.applyRight?n.right:0;r.offsetMin.x===l&&r.offsetMin.y===a||(r.offsetMin={x:l,y:a},o=!0),r.offsetMax.x===-c&&r.offsetMax.y===-i||(r.offsetMax={x:-c,y:-i},o=!0),o&&t.insert(s,Ms,r)}},{name:"SafeAreaSystem"}))}},Hr=le("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2}),jr=new Map;function Xr(e,t){const n=jr.get(e);n&&(n.renderer=t)}const Yr=new class{build(e){ye("ListView",Hr);const t=e.world;e.addSystemToSchedule(et.PreUpdate,nt([He(ct)],e=>{const n=t.getEntitiesWithComponents([Hr,Ms]);for(const s of n){t.has(s,Hs)||t.insert(s,Hs,{enabled:!0,blockRaycast:!0}),t.has(s,Fs)||t.insert(s,Fs,{enabled:!0,mode:"scissor"});let n=jr.get(s);n||(n={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},jr.set(s,n));const r=t.get(s,Hr),o=t.get(s,Ms),i=o.size.y,a=t.has(s,js)?t.get(s,js):null;if(a?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}const l=Math.max(0,r.itemCount*r.itemHeight-i);r.scrollY=Math.max(0,Math.min(r.scrollY,l));const c=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),h=Math.min(r.itemCount,Math.ceil((r.scrollY+i)/r.itemHeight)+r.overscan);for(const[e,s]of n.itemEntities)(e<c||e>=h)&&(t.valid(s)&&t.despawn(s),n.itemEntities.delete(e));for(let e=c;e<h;e++){let i=n.itemEntities.get(e);if(i&&t.valid(i)||(i=t.spawn(),t.insert(i,Ie,{value:`ListItem_${e}`}),t.insert(i,Ms,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o.size.x,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(i,s),n.itemEntities.set(e,i),n.renderer&&n.renderer(e,i)),t.has(i,be)){const n=t.get(i,be);n.position.y=-(e*r.itemHeight-r.scrollY),t.insert(i,be,n)}}n.visibleStart=c,n.visibleEnd=h}},{name:"ListViewSystem"}))}},Nr=le("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const Vr=new class{build(e){ye("Dropdown",Nr);const t=e.world;e.addSystemToSchedule(et.Update,nt([He(ct),He(Vs)],(e,n)=>{const s=t.getEntitiesWithComponents([Nr]);for(const o of s){t.has(o,Hs)||t.insert(o,Hs,{enabled:!0,blockRaycast:!0});const s=t.get(o,Nr),i=t.has(o,js)?t.get(o,js):null;if(i?.justPressed&&(s.isOpen=!s.isOpen,r(s.listEntity,s.isOpen),n.emit(o,"change",o)),s.isOpen&&e.isMouseButtonPressed(0)&&!i?.hovered){0!==s.listEntity&&t.valid(s.listEntity)&&t.has(s.listEntity,js)&&t.get(s.listEntity,js).hovered||(s.isOpen=!1,r(s.listEntity,!1))}}function r(e,n){if(0===e)return;const s=e;if(!t.valid(s)||!t.has(s,be))return;const r=t.get(s,be),o=n?1:0;r.scale={x:o,y:o,z:o},t.insert(s,be,r)}},{name:"DropdownSystem"}))}};async function qr(e,t,n){const s=e.getResource(rs);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function Gr(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const Jr=Oe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Kr=Oe(null,"PhysicsAPI");function Qr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Zr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class eo{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Jr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Gr(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([Te]);for(const n of t){const t=e.world.get(n,Te);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(et.PostUpdate,nt([He(Ne)],a=>{const l=i.getEntitiesWithComponents([$e,be,Se]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,$e),l=i.get(r,Se);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=Qr(l.rotation);s._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),to(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===ze.Kinematic){const e=Qr(l.rotation);s._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const h=e.world.get(i,be);if(!h)continue;let d=a,u=l,f=c;if(e.world.has(i,Ce)){const t=e.world.get(i,Ce);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,Se)){const n=e.world.get(t.entity,Se),s=Qr(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),h=Math.sin(-s);d=(r*i-o*h)/(0!==n.scale.x?n.scale.x:1),u=(r*h+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}h.position.x=d,h.position.y=u;const p=Zr(f);h.rotation.w=p.w,h.rotation.x=p.x,h.rotation.y=p.y,h.rotation.z=p.z,e.world.insert(i,be,h)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],h=t._physics_getSensorExitCount();if(h>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<h;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Jr,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(Kr,no._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function to(e,t,n){const s=e.world;if(s.has(n,We)){const e=s.get(n,We);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,De)){const e=s.get(n,De);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,Ue)){const e=s.get(n,Ue);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class no{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(no.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function so(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function ro(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function oo(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,h=e.rotation.w,d=a+a,u=l+l,f=c+c,p=a*d,g=a*u,y=a*f,m=l*u,_=l*f,w=c*f,x=h*d,v=h*u,b=h*f;return new Float32Array([(1-(m+w))*r,(g+b)*r,(y-v)*r,0,(g-b)*o,(1-(p+w))*o,(_+x)*o,0,(y+v)*i,(_-x)*i,(1-(p+m))*i,0,e.position.x,e.position.y,e.position.z,1])}async function io(e,t,n,s,r,o,i,a,l){const c=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=so(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,c);let h={},d=null;if(r&&(d=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),h=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=await r.readText(a),h="binary"===x(l)?.contentType;let d,u;if(h){const e=await r.readBinary(i);u=e.length,d=t._malloc(u),t.HEAPU8.set(e,d)}else{const e=await r.readText(i),n=(new TextEncoder).encode(e);u=n.length,d=t._malloc(u+1),t.HEAPU8.set(n,d),t.HEAPU8[d+u]=0}const f=n.loadSkeleton(d,u,s,s.length,h);if(t._free(d),f<0)continue;o[i]=f;const p=ro(s),g=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=g+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=so(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,d,n,s)),o){new eo("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const u=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;const i=x(r);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[r]=0;continue}const l=o?`${o}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),h=so(e,c,!1),d=e.getResourceManager();s[r]=d.loadBitmapFont(t,h,c.width,c.height)}catch{s[r]=0}}return s}(t,n,s),f=await async function(e,t){const n={},s={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===n[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=At.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=At.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s);!function(e,t,n,s){const r={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=Xt(e.type);if(0===t.length)continue;const n=e.data;for(const e of t)"string"==typeof n[e.field]&&(n[e.field]=r[e.type][n[e.field]]||0)}}(n,c,u,f);const p=Yt(e.world,n);if(l&&e.hasResource(rs))for(const t of p.values())e.world.insert(t,Be,{scene:l,persistent:!1});if(r&&d){const s=function(e,t,n,s){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(d,n,h,p);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,Fe)?c.get(o,Fe):null,h=!1!==a?.playing,d=a?.timeScale??1;h&&s.update(i,l*d);let u=0;if(c.has(o,Se)){const e=oo(c.get(o,Se),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);u=t._malloc(64),t.HEAPF32.set(e,u>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),h=n._malloc(l),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,h,d,f);const p=n.HEAPU32[d>>2],g=n.HEAPU32[f>>2],y=new Float32Array(n.HEAPF32.buffer,c,8*r),m=new Uint16Array(n.HEAPU8.buffer,h,o),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(y,_>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(m),t.renderer_submitTriangles(_,r,w,o,p,g,u),t._free(_),t._free(w),n._free(c),n._free(h),n._free(d),n._free(f)}u&&t._free(u)}})}(e,t,r,d,s)}if(a){const t=e.getResource(Kt);t&&t.setAddressableManifest(a)}}function ao(e,t,n){return{name:e,data:t,async setup(){await io(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class lo{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&("binary"===x(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of s){const t=x(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const co="__preview__";class ho{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(rs);t.register({name:co,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(co),this.loadPromise_=t.load(co).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new lo(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.spineInitPromise;if(r){s=(await r).controller.raw}await io(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,co)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([Me]);for(const s of n){if(e.get(s,Me).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([Te]);for(const r of s){const s=e.get(r,Te);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=this.app_.getResource(rs).getScene(co),o=r?r.spawn():e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(o,be,i);const a={isActive:!0,projectionType:we.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:xe.ColorAndDepth};e.insert(o,Me,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(rs);await e.switchTo(co),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}}const uo={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=qn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:qn.getTargetTexture(n),width:e.width,height:e.height}},release(e){qn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(qn.releaseRenderTarget(e._handle),uo.create({width:t,height:n,depth:!0})),begin(e,t){qn.begin(t,e._handle)},end(){qn.end()},getDepthTexture:e=>qn.getTargetDepthTexture(e._handle)};let fo=!1;function po(e){fo=e}function go(){return fo}function yo(){return!fo}var mo;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(mo||(mo={}));class _o{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${mo[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case mo.Debug:console.debug(t,n);break;case mo.Info:console.log(t,n);break;case mo.Warn:console.warn(t,n);break;case mo.Error:console.error(t,n)}}}class wo{constructor(){this.handlers_=[],this.minLevel_=mo.Info,this.addHandler(new _o)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log(mo.Debug,e,t,n)}info(e,t,n){this.log(mo.Info,e,t,n)}warn(e,t,n){this.log(mo.Warn,e,t,n)}error(e,t,n){this.log(mo.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const xo=new wo;function vo(){return xo}function bo(e){xo.setMinLevel(e)}function So(e,t,n){xo.debug(e,t,n)}function Po(e,t,n){xo.info(e,t,n)}function Mo(e,t,n){xo.warn(e,t,n)}function To(e,t,n){xo.error(e,t,n)}const Eo=[As,Os,tr,_r,Sr,lr,Ar,Ir,$r,xr,fr,zr,Or,Yr,Vr];function Co(e,t){return function(e,t){const n=ls.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),yn(e),Et(e),Bn(e),Un(e),Nn(e),Jn(e);const r=new Zn;n.setPipeline(r);let o=u();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,o){o||(o=us(e,s,t,r));const i=n.getResource(xt);if(o.length>0){const e=o[0],n=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(n.x*t),i.vpY=Math.round((1-n.y-n.h)*r),i.vpW=Math.round(n.w*t),i.vpH=Math.round(n.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}n.insertResource(xt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=i();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;qn.setClearColor(e.x,e.y,e.z,e.w)}const h=(u()-o)/1e3;let d;if(qn.resize(t,l),On.isInitialized()&&On.getPassCount()>0&&!On.isBypassed()&&On.resize(t,l),n.hasResource(rs)){const e=n.getResource(rs).getActiveScenes();e.length>0&&(d=new Set(e))}r.setActiveScenes(d??null);const f=us(e,s,t,l,n.world,d);if(a(t,l,f),0===f.length)r.render({registry:{_cpp:s},viewProjection:hs,width:t,height:l,elapsed:h});else{for(const e of f){const n=e.viewportRect,o=Math.round(n.x*t),i=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:c},clearFlags:e.clearFlags,elapsed:h})}qn.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(et.First,l),n.addSystemToSchedule(et.Last,c),n.addPlugin(Zt),n.addPlugin(hn),n.addPlugin(dt),n.addPlugin(as),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Eo,...t})}H||(H=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await f(n,s);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:n}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return p(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),n=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?n[s++]=r:r<2048?(n[s++]=192|r>>6,n[s++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,n[s++]=240|r>>18,n[s++]=128|r>>12&63,n[s++]=128|r>>6&63,n[s++]=128|63&r):(n[s++]=224|r>>12,n[s++]=128|r>>6&63,n[s++]=128|63&r)}return n.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let n="";for(let e=0;e<t.length;){const s=t[e];if(s<128)n+=String.fromCharCode(s),e++;else if(192==(224&s))n+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))n+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=j;export{ls as App,Qt as AssetPlugin,en as AssetRefCounter,Jt as AssetServer,Kt as Assets,zt as AsyncCache,Ae as BitmapText,vt as BlendMode,ze as BodyType,We as BoxCollider,Ys as Button,Xs as ButtonState,Me as Camera,Te as Canvas,Ue as CapsuleCollider,Re as Children,De as CircleCollider,xe as ClearFlags,Ke as Commands,Ze as CommandsInstance,Y as DEFAULT_DESIGN_HEIGHT,X as DEFAULT_DESIGN_WIDTH,N as DEFAULT_PIXELS_PER_UNIT,V as DEFAULT_TEXT_CANVAS_SIZE,Cn as DataType,Mr as DragState,Pr as Draggable,xn as Draw,Nr as Dropdown,Qe as EntityCommands,gr as FillMethod,yr as FillOrigin,Ur as FocusManager,Dr as FocusManagerState,Wr as Focusable,Qn as GLDebug,Wn as Geometry,J as INVALID_ENTITY,Q as INVALID_FONT,K as INVALID_TEXTURE,mr as Image,pr as ImageType,ct as Input,ht as InputPlugin,lt as InputState,Hs as Interactable,Hr as ListView,be as LocalTransform,mo as LogLevel,wo as Logger,At as Material,Lt as MaterialLoader,Ve as Mut,Ie as Name,Ce as Parent,no as Physics,Jr as PhysicsEvents,eo as PhysicsPlugin,On as PostProcess,an as PrefabServer,ln as Prefabs,cn as PrefabsPlugin,ho as PreviewPlugin,br as ProgressBar,vr as ProgressBarDirection,we as ProjectionType,Ge as Query,Je as QueryInstance,Zn as RenderPipeline,jn as RenderStage,uo as RenderTexture,qn as Renderer,He as Res,je as ResMut,$e as RigidBody,q as RuntimeConfig,Lr as SafeArea,ve as ScaleMode,rs as SceneManager,ss as SceneManagerState,Be as SceneOwner,et as Schedule,qs as ScreenSpace,Fr as ScrollView,Ut as ShaderSources,kr as Slider,Br as SliderDirection,Fe as SpineAnimation,Pe as Sprite,at as SystemRunner,Ps as Text,vs as TextAlign,cr as TextInput,hr as TextInputPlugin,Ss as TextOverflow,Rs as TextPlugin,Ts as TextRenderer,bs as TextVerticalAlign,Ne as Time,wr as Toggle,xt as UICameraInfo,Ns as UIEventQueue,Vs as UIEvents,js as UIInteraction,ar as UIInteractionPlugin,er as UILayoutPlugin,Fs as UIMask,Ls as UIMaskPlugin,Ms as UIRect,Ee as Velocity,lo as WebAssetProvider,wt as World,Se as WorldTransform,ot as addStartupSystem,rt as addSystem,it as addSystemToSchedule,G as applyRuntimeConfig,Zt as assetPlugin,En as clearDrawCallbacks,de as clearUserComponents,ne as color,Gs as computeUIRectLayout,zs as createMaskProcessor,ao as createRuntimeSceneConfig,Co as createWebApp,So as debug,le as defineComponent,Oe as defineResource,nt as defineSystem,ce as defineTag,To as error,Gt as findEntityByName,cs as flushPendingSystems,b as getAddressableType,S as getAddressableTypeByEditorType,M as getAllAssetExtensions,R as getAssetMimeType,x as getAssetTypeEntry,me as getComponent,jt as getComponentAssetFields,ke as getComponentDefaults,E as getCustomExtensions,v as getEditorType,vo as getLogger,t as getPlatform,s as getPlatformType,he as getUserComponent,C as getWeChatPackOptions,Po as info,yn as initDrawAPI,Jn as initGLDebugAPI,Bn as initGeometryAPI,Et as initMaterialAPI,Un as initPostProcessAPI,Nn as initRendererAPI,dt as inputPlugin,nn as instantiatePrefab,Is as intersectRects,ks as invertMatrix4,pe as isBuiltinComponent,A as isCustomExtension,go as isEditor,P as isKnownAssetExtension,n as isPlatformInitialized,yo as isRuntime,bt as isTextureRef,r as isWeChat,o as isWeb,Vt as loadComponent,Gr as loadPhysicsModule,io as loadRuntimeScene,Yt as loadSceneData,Nt as loadSceneWithAssets,T as looksLikeAssetPath,i as platformFetch,c as platformFileExists,h as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Ds as pointInOBB,Ws as pointInWorldRect,hn as prefabsPlugin,se as quat,ye as registerComponent,Ht as registerComponentAssetFields,Mn as registerDrawCallback,tn as registerEmbeddedAssets,Dt as registerMaterialCallback,as as sceneManagerPlugin,$s as screenToWorld,po as setEditorMode,Xr as setListViewRenderer,bo as setLogLevel,yt as setWasmErrorHandler,mn as shutdownDrawAPI,Kn as shutdownGLDebugAPI,kn as shutdownGeometryAPI,Ct as shutdownMaterialAPI,zn as shutdownPostProcessAPI,Vn as shutdownRendererAPI,fr as textInputPlugin,As as textPlugin,qr as transitionTo,lr as uiInteractionPlugin,tr as uiLayoutPlugin,Os as uiMaskPlugin,Eo as uiPlugins,ue as unregisterComponent,Tn as unregisterDrawCallback,qt as updateCameraAspectRatio,Z as vec2,ee as vec3,te as vec4,Mo as warn,Bs as worldRectToScreen,os as wrapSceneSystem,W as wxFileExists,D as wxFileExistsSync,L as wxGetImagePixels,z as wxLoadImage,O as wxLoadImagePixels,k as wxReadFile,$ as wxReadTextFile,U as wxWriteFile};
//# sourceMappingURL=index.wechat.js.map
diff --git a/desktop/public/sdk/esm/esengine.d.ts b/desktop/public/sdk/esm/esengine.d.ts
index 7bddb358c..5030484e1 100644
--- a/desktop/public/sdk/esm/esengine.d.ts
+++ b/desktop/public/sdk/esm/esengine.d.ts
@@ -88,6 +88,7 @@ interface BoxColliderData {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
interface CircleColliderData {
radius: number;
@@ -96,6 +97,7 @@ interface CircleColliderData {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
interface CapsuleColliderData {
radius: number;
@@ -105,6 +107,7 @@ interface CapsuleColliderData {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
declare const RigidBody$1: BuiltinComponentDef<RigidBodyData>;
declare const BoxCollider$1: BuiltinComponentDef<BoxColliderData>;
@@ -185,6 +188,7 @@ interface SpriteData {
flipX: boolean;
flipY: boolean;
material: number;
+ enabled: boolean;
}
interface CameraData {
projectionType: number;
@@ -233,6 +237,7 @@ interface SpineAnimationData {
layer: number;
skeletonScale: number;
material: number;
+ enabled: boolean;
}
interface BitmapTextData {
text: string;
@@ -242,6 +247,7 @@ interface BitmapTextData {
spacing: number;
layer: number;
font: number;
+ enabled: boolean;
}
interface NameData {
value: string;
@@ -330,6 +336,7 @@ interface BoxCollider {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
interface CircleCollider {
radius: number;
@@ -338,6 +345,7 @@ interface CircleCollider {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
interface CapsuleCollider {
radius: number;
@@ -347,6 +355,7 @@ interface CapsuleCollider {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
interface LocalTransform {
position: Vec3;
@@ -376,6 +385,7 @@ interface SpineAnimation {
layer: number;
skeletonScale: number;
material: number;
+ enabled: boolean;
}
interface RigidBody {
bodyType: number;
@@ -394,6 +404,7 @@ interface BitmapText {
spacing: number;
layer: number;
font: number;
+ enabled: boolean;
}
interface Sprite {
texture: number;
@@ -405,6 +416,7 @@ interface Sprite {
flipX: boolean;
flipY: boolean;
material: number;
+ enabled: boolean;
}
interface Parent {
entity: number;
@@ -1848,6 +1860,7 @@ interface ButtonTransition {
interface ButtonData {
state: ButtonState;
transition: ButtonTransition | null;
+ enabled: boolean;
}
declare const Button: ComponentDef<ButtonData>;
@@ -1980,6 +1993,7 @@ interface ImageData {
preserveAspect: boolean;
layer: number;
material: number;
+ enabled: boolean;
}
declare const Image: ComponentDef<ImageData>;
@@ -1993,6 +2007,7 @@ interface ToggleData {
isOn: boolean;
graphicEntity: Entity;
transition: ToggleTransition | null;
+ enabled: boolean;
}
declare const Toggle: ComponentDef<ToggleData>;
@@ -2076,6 +2091,7 @@ interface SliderData {
fillEntity: number;
handleEntity: number;
wholeNumbers: boolean;
+ enabled: boolean;
}
declare const Slider: ComponentDef<SliderData>;
diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.js
index 8c2953f86..6adb25e2c 100644
--- a/desktop/public/sdk/esm/esengine.js
+++ b/desktop/public/sdk/esm/esengine.js
@@ -1,2 +1,2 @@
-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function h(e,n){return t().instantiateWasm(e,n)}function u(e,n){return t().createCanvas(e,n)}function d(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.module}}createImage(){return new Image}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),r=t=>e.onKeyUp(t.code),o=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},i=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},h=()=>{e.onPointerUp(0)},u=t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)};document.addEventListener("keydown",s),document.addEventListener("keyup",r),n.addEventListener("mousemove",o),n.addEventListener("mousedown",i),n.addEventListener("mouseup",a),n.addEventListener("touchstart",l),n.addEventListener("touchmove",c),n.addEventListener("touchend",h),n.addEventListener("wheel",u),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",r),n.removeEventListener("mousemove",o),n.removeEventListener("mousedown",i),n.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",h),n.removeEventListener("wheel",u)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=1920,g=1080,m=100,y=512,_={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function w(e){e.Text&&(e.Text._default.fontFamily=_.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=_.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=_.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=_.canvasMatchWidthOrHeight)}const x=0,v=4294967295,b=4294967295,S=(e=0,t=0)=>({x:e,y:t}),P=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),M=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),T=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),E=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function C(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(C);const t={};for(const n in e)t[n]=C(e[n]);return t}let R=0;function A(e,t){const n=++R;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...C(t),...e}:C(t)}}function F(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function I(e,t){const n=F(),s=n.get(e);if(s)return s;const r=A(e,t);return n.set(e,r),U(e,t,!1),r}function k(e){const t=F(),n=t.get(e);if(n)return n;const s=A(e,{});return t.set(e,s),U(e,{},!0),s}function B(e){return F().get(e)}function $(){F().clear()}function D(e){F().delete(e)}function U(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function z(e){return!0===e._builtin}const L=new Map;function W(e,t){L.set(e,t)}function O(e){return L.get(e)??B(e)}function H(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return L.set(e,n),n}const j={Perspective:0,Orthographic:1},X={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},Y={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},N=H("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),V=H("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),q=H("Sprite",{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),G=H("Camera",{projectionType:j.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:X.ColorAndDepth}),J=H("Canvas",{designResolution:{x:p,y:g},pixelsPerUnit:100,scaleMode:Y.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),K=H("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Q=H("Parent",{entity:0}),Z=H("Children",{entities:[]}),ee=H("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:b}),te=H("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),ne={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},se=I("SceneOwner",{scene:"",persistent:!1});function re(e){const t=O(e);return t?C(t._default):null}W("Name",ne);const oe=H("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ie=H("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ae=H("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),le=H("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ce={Static:0,Kinematic:1,Dynamic:2};let he=0;function ue(e,t){const n=++he;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function de(e){return{_type:"res",_resource:e}}function fe(e){return{_type:"res_mut",_resource:e}}class pe{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class ge{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new pe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const me=ue({delta:0,elapsed:0,frameCount:0},"Time");function ye(e){return{_type:"mut",_component:e}}function _e(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function we(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{_e(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class xe{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>_e(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=n.length,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let h=null;this.world_.beginIteration();try{for(const u of s){if(null!==h&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(h,t.component,t.data)}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(u,t[n])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,n[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];h=u}yield a}}finally{if(this.world_.endIteration(),null!==h&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(h,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function ve(){return{_type:"commands"}}class be{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=z(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Se{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new be(this,null);return this.spawned_.push(e),e}entity(e){return new be(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Pe;!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(Pe||(Pe={}));let Me=0;function Te(e,t,n){const s=++Me;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Ee(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Ce(e){Ee().push({schedule:Pe.Update,system:e})}function Re(e){Ee().push({schedule:Pe.Startup,system:e})}function Ae(e,t){Ee().push({schedule:e,system:t})}class Fe{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Se&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new xe(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Se(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ie{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const ke=ue(new Ie,"Input");class Be{constructor(e){this.target_=e??null}build(e){const n=new Ie;e.insertResource(ke,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(Pe.Last,Te([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const $e=new Be;function De(e,t,n){const s=[];for(const[e,r]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const n=Ue(t[e]),o=Ue(r);"null"!==n&&"undefined"!==n&&(n!==o&&null!=r&&s.push({field:e,expected:n,actual:o,value:r}))}return s}function Ue(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ze(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let Le=null;function We(e){Le=e}function Oe(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Le&&Le(e,t)}function He(e){const t={};for(const n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:He(e)}}return t}class je{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw Oe(e,"spawn"),e}else e=this.entities_.size+1;return this.entities_.add(e),e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){Oe(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t)this.tsStorage_.get(n)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(n){Oe(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Oe(t,`removeParent(entity=${e})`)}}insert(e,t,n){return z(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return z(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return z(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(z(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return Oe(n,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");z(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_;return t={add:n[`add${e}`].bind(n),get:n[`get${e}`].bind(n),has:n[`has${e}`].bind(n),remove:n[`remove${e}`].bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const e=De(t._name,t._default,s);if(e.length>0)throw new Error(ze(t._name,e))}const r={...t._default,...s};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,He(r))}catch(n){Oe(n,`insertBuiltin(${t._name}, entity=${e})`)}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return this.getBuiltinMethods(t._cppName).get(e)}catch(n){return Oe(n,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(n){return Oe(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){Oe(n,`removeBuiltin(${t._name}, entity=${e})`)}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const r=De(t._name,t._default,e);if(r.length>0)throw new Error(ze(t._name,r));s=e}const r=t.create(s);this.getStorage(t).set(e,r),this.worldVersion_++;let o=this.entityComponents_.get(e);return o||(o=[],this.entityComponents_.set(e,o)),-1===o.indexOf(t._id)&&o.push(t._id),r}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getComponentTypes(e){const t=[];for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.push(n)}catch{}if(this.cppRegistry_)for(const[n,s]of L)if(z(s)&&!t.includes(n))try{this.getBuiltinMethods(s._cppName).has(e)&&t.push(n)}catch{}const n=this.entityComponents_.get(e);if(n){const e="undefined"!=typeof window?window.__esengine_componentRegistry:void 0;if(e)for(const s of n)for(const[n,r]of e)if(r._id===s){t.push(n);break}}return t}getEntitiesWithComponents(e,t=[],n=[]){if(0===e.length&&0===t.length&&0===n.length)return this.getAllEntities();let s=e.map(e=>e._name).sort().join(",");t.length>0&&(s+="|+"+t.map(e=>e._name).sort().join(",")),n.length>0&&(s+="|-"+n.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(s);if(r&&r.version===this.worldVersion_)return r.result;let o=null,i=1/0;for(const t of e)if(!z(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<i&&(i=n,o=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const l=o?o.keys():this.entities_;for(const t of l){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&a.push(t)}return this.queryCache_.set(s,{version:this.worldVersion_,result:a}),a}}const Xe=ue({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var Ye;function Ne(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}!function(e){e[e.Normal=0]="Normal",e[e.Additive=1]="Additive",e[e.Multiply=2]="Multiply",e[e.Screen=3]="Screen",e[e.PremultipliedAlpha=4]="PremultipliedAlpha"}(Ye||(Ye={}));let Ve=null,qe=null,Ge=1;const Je=new Map;function Ke(e){Ve=e,qe=e.getResourceManager(),at()}function Qe(){0!==nt&&Ve&&(Ve._free(nt),nt=0),Je.clear(),Ge=1,tt=!1,rt.clear(),ot=null,qe=null,Ve=null}function Ze(){if(!qe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return qe}const et={createShader:(e,t)=>Ze().createShader(e,t),releaseShader(e){e>0&&Ze().releaseShader(e)},create(e){const t=Ge++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Ye.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return Je.set(t,n),t},get:e=>Je.get(e),setUniform(e,t,n){const s=Je.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=Je.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Je.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Je.get(e);return t?.blendMode??Ye.Normal},setDepthTest(e,t){const n=Je.get(e);n&&(n.depthTest=t)},getShader(e){const t=Je.get(e);return t?.shader??0},release(e){Je.delete(e)},isValid:e=>Je.has(e),releaseAll(){Je.clear()},createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??Ye.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Je.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Ge++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Je.set(n,s),n},toAssetData(e,t){const n=Je.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=Je.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let tt=!1,nt=0;const st=4096,rt=new Map;let ot=null;function it(e){const t=(0===nt&&Ve&&(nt=Ve._malloc(st)),nt);if(0===t||!Ve)return{ptr:0,count:0};let n=0,s=0;const r=Ve.HEAPU8,o=Ve.HEAPU32,i=Ve.HEAPF32;for(const[a,l]of e){if(n+128>st)break;let e=rt.get(a);e||(ot||(ot=new TextEncoder),e=ot.encode(a),rt.set(a,e));const c=e.length,h=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=h;let u=0,d=[0,0,0,0];if("number"==typeof l)u=0,d[0]=l;else if(Array.isArray(l)){u=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(u=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(u=2,d=[l.x,l.y,l.z,0]):"y"in l&&(u=1,d=[l.x,l.y,0,0]);o[t+n>>2]=u,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function at(){if(!Ve||tt)return;Ve.materialDataProvider=(e,t,n,s,r)=>{const o=Je.get(e);if(!o)return Ve.HEAPU32[t>>2]=0,Ve.HEAPU32[n>>2]=0,Ve.HEAPU32[s>>2]=0,void(Ve.HEAPU32[r>>2]=0);Ve.HEAPU32[t>>2]=o.shader,Ve.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=it(o.uniforms);Ve.HEAPU32[s>>2]=i,Ve.HEAPU32[r>>2]=a},tt=!0}const lt={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class ct{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const s=t(),r=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{o.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class ht{constructor(e,t=""){this.cache_=new ct,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(et.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())et.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(r);return{handle:et.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}const ut=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}]]);function dt(e,t){ut.set(e,t)}function ft(e){const t=ut.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function pt(e){return ut.get(e)?.fields??[]}function gt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,ne,{value:s.name}),!1!==s.visible)for(const n of s.components)yt(e,t,n,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function mt(e,t,n){const s=new Map,r=n?.assetServer,o=n?.assetBaseUrl,i=new Map;r&&await async function(e,t,n,s){e=JSON.parse(JSON.stringify(e));const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ut.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,h=new Map,u=new Map,d=[];for(const e of r)d.push((async()=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)d.push((async()=>{try{const s=await t.loadMaterial(e,n);h.set(e,s.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),h.set(e,0)}})());for(const e of i)d.push((async()=>{try{const s=await t.loadBitmapFont(e,n);u.set(e,s)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),u.set(e,0)}})());for(const e of a)d.push((async()=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)})());await Promise.all(d);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ut.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":n[e.field]=c.get(t)??0;break;case"material":n[e.field]=h.get(t)??0;break;case"font":n[e.field]=u.get(t)??0}}}}(t,r,o,i);for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,ne,{value:n.name}),!1!==n.visible)for(const s of n.components)yt(e,t,s,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function yt(e,t,n,s){if("UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=O(n.type);if(r)e.insert(t,r,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function _t(e,t){const n=e.getEntitiesWithComponents([G]);for(const s of n){const n=e.get(s,G);n&&(n.aspectRatio=t,e.insert(s,G,n))}}function wt(e,t){const n=e.getEntitiesWithComponents([ne]);for(const s of n){const n=e.get(s,ne);if(n&&n.value===t)return s}return null}const xt=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],vt={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},bt=new Map,St=new Set;for(const e of xt)for(const t of e.extensions)bt.set(t,e),St.add(t);function Pt(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function Mt(e){return bt.get(Pt(e))}function Tt(e){return Mt(e)?.editorType??"unknown"}function Et(e){return Mt(e)?.addressableType??null}function Ct(e){for(const t of xt)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function Rt(e){return St.has(e.toLowerCase())}function At(){return St}function Ft(e){return"string"==typeof e&&(!!e.includes("/")&&Rt(Pt(e)))}function It(){const e=[];for(const t of xt)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function kt(){return It().map(e=>({type:"suffix",value:e}))}function Bt(e){return vt[e.toLowerCase()]}function $t(e){const t=Mt(e);return t?.wechatPackInclude??!1}class Dt{constructor(e){this.textureCache_=new ct,this.shaderCache_=new ct,this.jsonCache_=new ct,this.textCache_=new ct,this.binaryCache_=new ct,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new ct,this.prefabCache_=new ct,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.module_=e,this.canvas_=u(_.textCanvasSize,_.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new ht(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);if(!r)continue;const o=(this.textureRefCounts_.get(s)??1)-1;o<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),et.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),h="binary"===Mt(e)?.contentType,u=h?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(u,o,h);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),r=l.find(e=>e.name===n);if(r){const n=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,r.info.width,r.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=Mt(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return mt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const r=s.metadata?.atlas;r&&n.push(this.loadSpine(s.path,r).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??n;return new Promise((n,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return et.createShader(s,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:o}=this.parseEsShader(s);if(!r||!o)throw new Error(`Invalid shader format: ${e}`);return et.createShader(r,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Ut=ue(null,"Assets");class zt{build(e){const t=e.wasmModule;t?e.insertResource(Ut,new Dt(t)):console.warn("AssetPlugin: No WASM module available")}}const Lt=new zt;class Wt{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function Ot(e,t){const n=e.getResource(Ut);n&&n.registerEmbeddedAssets(t)}async function Ht(e,t,n){const{entities:s,rootId:r}=await Xt(t,n?.overrides??[],n,void 0,new Set),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await mt(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}const jt=10;async function Xt(e,t,n,s,r,o=0){if(o>jt)throw new Error(`Prefab nesting depth exceeded ${jt}. Check for deep or circular nesting in: ${e.name}`);const i=new Map;let a;if(void 0===s){a=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=s;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(r?.has(s.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${s.nestedPrefab.prefabPath}`);continue}r?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await Xt(e,s.nestedPrefab.overrides,n,a,r,o+1);i.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?i.get(s.parent)??null:null),l.push(...t.entities);continue}const c=i.get(s.prefabEntityId),h=s.prefabEntityId===e.rootEntityId,u={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:h?null:null!==s.parent?i.get(s.parent)??null:null,children:s.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};Yt(u,t),l.push(u)}const c=i.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function Yt(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class Nt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,r=await this.assetServer_.loadPrefab(s,t?.baseUrl);return Ht(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Vt=ue(null,"Prefabs");class qt{constructor(){this.name="PrefabsPlugin",this.dependencies=[Ut]}build(e){const t=e.getResource(Ut);e.insertResource(Vt,new Nt(e.world,t))}}const Gt=new qt;let Jt=null,Kt=0,Qt=0,Zt=0;const en=new Float32Array(256);function tn(e){Jt=e,Kt=Jt._malloc(64),Qt=Jt._malloc(64),Zt=Jt._malloc(1024)}function nn(){Jt&&(Kt&&(Jt._free(Kt),Kt=0),Qt&&(Jt._free(Qt),Qt=0),Zt&&(Jt._free(Zt),Zt=0)),Jt=null}function sn(){if(!Jt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Jt}const rn={r:1,g:1,b:1,a:1},on={begin(e){const t=sn();try{t.HEAPF32.set(e,Kt/4),t.draw_begin(Kt)}catch(e){Oe(e,"Draw.begin")}},end(){try{sn().draw_end()}catch(e){Oe(e,"Draw.end")}},line(e,t,n,s=1){try{sn().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Oe(e,"Draw.line")}},rect(e,t,n,s=!0){try{sn().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Oe(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{sn().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Oe(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,r=32){try{sn().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)}catch(e){Oe(e,"Draw.circle")}},circleOutline(e,t,n,s=1,r=32){try{sn().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)}catch(e){Oe(e,"Draw.circleOutline")}},texture(e,t,n,s=rn){try{sn().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){Oe(e,"Draw.texture")}},textureRotated(e,t,n,s,r=rn){try{sn().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)}catch(e){Oe(e,"Draw.textureRotated")}},setLayer(e){sn().draw_setLayer(e)},setDepth(e){sn().draw_setDepth(e)},getDrawCallCount:()=>Jt?Jt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Jt?Jt.draw_getPrimitiveCount():0,setBlendMode(e){sn().draw_setBlendMode(e)},setDepthTest(e){sn().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=sn();s.HEAPF32.set(n,Qt/4),s.draw_mesh(e,t,Qt)}catch(n){Oe(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=sn(),r=et.get(t);if(!r)return;if(on.setBlendMode(r.blendMode),on.setDepthTest(r.depthTest),0===r.uniforms.size)return void on.drawMesh(e,r.shader,n);let o;if(s.HEAPF32.set(n,Qt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,n]of r.uniforms){const s=cn(t);if(!(s<0)){if(Ne(n))en[o++]=10,en[o++]=s,en[o++]=n.slot??e++,en[o++]=n.textureId;else if("number"==typeof n)en[o++]=1,en[o++]=s,en[o++]=n;else if(Array.isArray(n)){en[o++]=n.length,en[o++]=s;for(let e=0;e<n.length;e++)en[o++]=n[e]}else"w"in n?(en[o++]=4,en[o++]=s,en[o++]=n.x,en[o++]=n.y,en[o++]=n.z,en[o++]=n.w):"z"in n?(en[o++]=3,en[o++]=s,en[o++]=n.x,en[o++]=n.y,en[o++]=n.z):(en[o++]=2,en[o++]=s,en[o++]=n.x,en[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(en.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void s.draw_mesh(e,r.shader,Qt);s.HEAPF32.set(r.cachedBuffer_.subarray(0,o),Zt/4),s.draw_meshWithUniforms(e,r.shader,Qt,Zt,o)}catch(n){Oe(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},an={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17},ln=new Set;function cn(e){const t=an[e];return void 0!==t?t:(ln.has(e)||(ln.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(an).join(", ")}`)),-1)}const hn=new Map;function un(e,t,n){hn.set(e,{fn:t,scene:n??""})}function dn(e){hn.delete(e)}function fn(){hn.clear()}var pn;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(pn||(pn={}));let gn=null,mn=0,yn=0,_n=0;function wn(e){gn=e,mn=gn._malloc(262144),yn=gn._malloc(65536),_n=gn._malloc(256)}function xn(){gn&&(mn&&gn._free(mn),yn&&gn._free(yn),_n&&gn._free(_n),mn=0,yn=0,_n=0),gn=null}function vn(){if(!gn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return gn}const bn={create(e){const t=vn(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,mn/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,_n,r).set(o),t.geometry_init(n,mn,s,_n,r,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,yn,s).set(e.indices),t.geometry_setIndices16(n,yn,s)}else{new Uint32Array(t.HEAPU8.buffer,yn,s).set(e.indices),t.geometry_setIndices32(n,yn,s)}}return n},updateVertices(e,t,n=0){const s=vn(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,mn/4),s.geometry_updateVertices(e,mn,r,n)},release(e){e>0&&vn().geometry_release(e)},isValid:e=>!(!gn||e<=0)&&gn.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return bn.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:pn.Float2},{name:"a_texCoord",type:pn.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;n.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return bn.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:pn.Float2},{name:"a_texCoord",type:pn.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-n);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return bn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:pn.Float2},{name:"a_texCoord",type:pn.Float2}],indices:new Uint16Array(i)})}};let Sn=null;function Pn(e){Sn=e}function Mn(){Sn&&En.isInitialized()&&En.shutdown(),Sn=null}function Tn(){if(!Sn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Sn}const En={init(e,t){try{return Tn().postprocess_init(e,t)}catch(n){return Oe(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Tn().postprocess_shutdown()}catch(e){Oe(e,"PostProcess.shutdown")}},resize(e,t){try{Tn().postprocess_resize(e,t)}catch(n){Oe(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Tn().postprocess_addPass(e,t)}catch(t){return Oe(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Tn().postprocess_removePass(e)}catch(t){Oe(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Tn().postprocess_setPassEnabled(e,t)}catch(t){Oe(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Tn().postprocess_isPassEnabled(e)}catch(t){return Oe(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{Tn().postprocess_setUniformFloat(e,t,n)}catch(n){Oe(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{Tn().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){Oe(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Tn().postprocess_begin()}catch(e){Oe(e,"PostProcess.begin")}},end(){try{Tn().postprocess_end()}catch(e){Oe(e,"PostProcess.end")}},getPassCount(){try{return Tn().postprocess_getPassCount()}catch(e){return Oe(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Sn)return!1;try{return Sn.postprocess_isInitialized()}catch(e){return Oe(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Tn().postprocess_setBypass(e)}catch(e){Oe(e,"PostProcess.setBypass")}},isBypassed(){if(!Sn)return!0;try{return Sn.postprocess_isBypassed()}catch(e){return Oe(e,"PostProcess.isBypassed"),!0}},createBlur:()=>et.createShader(Cn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>et.createShader(Cn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>et.createShader(Cn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>et.createShader(Cn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},Cn="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var Rn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Rn||(Rn={}));let An=null,Fn=0;function In(e){An=e,Fn=An._malloc(64)}function kn(){An&&Fn&&(An._free(Fn),Fn=0),An=null}const Bn={init(e,t){An?.renderer_init(e,t)},resize(e,t){An?.renderer_resize(e,t)},begin(e,t){if(An&&Fn)try{An.HEAPF32.set(e,Fn/4),An.renderer_begin(Fn,t??0)}catch(e){Oe(e,"Renderer.begin")}},flush(){try{An?.renderer_flush()}catch(e){Oe(e,"Renderer.flush")}},end(){try{An?.renderer_end()}catch(e){Oe(e,"Renderer.end")}},submitSprites(e){if(An)try{An.renderer_submitSprites(e._cpp)}catch(e){Oe(e,"Renderer.submitSprites")}},submitBitmapText(e){if(An)try{An.renderer_submitBitmapText(e._cpp)}catch(e){Oe(e,"Renderer.submitBitmapText")}},submitSpine(e){if(An)try{An.renderer_submitSpine?.(e._cpp)}catch(e){Oe(e,"Renderer.submitSpine")}},setStage(e){An?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>An?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){An?.renderer_releaseTarget(e)},getTargetTexture:e=>An?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>An?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){An?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){An?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){An?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){An?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>An?An.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>An?{drawCalls:An.renderer_getDrawCalls(),triangles:An.renderer_getTriangles(),sprites:An.renderer_getSprites(),text:An.renderer_getText(),spine:An.renderer_getSpine?.()??0,meshes:An.renderer_getMeshes(),culled:An.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let $n=null;function Dn(e){$n=e}function Un(){$n=null}const zn={enable(){$n?.gl_enableErrorCheck(!0)},disable(){$n?.gl_enableErrorCheck(!1)},check:e=>$n?.gl_checkErrors(e)??0,diagnose(){$n?.renderer_diagnose()}};class Ln{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(Bn.resize(s,r),En.isInitialized()&&En.getPassCount()>0&&En.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),Bn.setViewport(0,0,s,r),Bn.clearBuffers(3),Bn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),Bn.submitSprites(t),Bn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Bn.submitSpine(t),Bn.flush(),this.executeDrawCallbacks(n,o),Bn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;Bn.setViewport(s.x,s.y,s.w,s.h),Bn.setScissor(s.x,s.y,s.w,s.h,!0),Bn.clearBuffers(r),Bn.setScissor(0,0,0,0,!1),Bn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Bn.submitSprites(t),Bn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Bn.submitSpine(t),Bn.flush(),this.executeDrawCallbacks(n,o),Bn.end()}executeDrawCallbacks(e,t){const n=hn;if(n.size>0){on.begin(e);const s=[];for(const[e,r]of n.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}on.end();for(const e of s)dn(e)}}}const Wn="__scene_transition_overlay__";class On{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class Hn{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,se,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),un(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=En.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){En.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,se)){const n=this.app_.world.get(e,se);n.persistent=t,this.app_.world.insert(e,se,n)}}}class jn{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_)return void console.warn(`[SceneManager] Transition already in progress, ignoring switchTo("${e}")`);"fade"!==(t?.transition??"none")?(this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)):await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(n=>{const s=t.duration??_.sceneTransitionDuration,r=t.color??{..._.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:r,targetScene:e,options:t,resolve:n},un(Wn,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;on.setLayer(9999),on.setDepth(9999),on.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{n&&n!==e&&await this.unload(n,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,dn(Wn)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,dn(Wn),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new On(t);this.scenes_.set(e,n);const s=new Hn(n,this.app_);this.contexts_.set(e,s);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Ut)?this.app_.getResource(Ut):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Ut)&&(t.assetServer=this.app_.getResource(Ut));const s=await mt(this.app_.world,r,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,se,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=Yn(this.app_,e,s);this.app_.addSystemToSchedule(n,t)}return t.setup&&await t.setup(s),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new On(t);this.scenes_.set(e,n);const s=new Hn(n,this.app_);this.contexts_.set(e,s);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Ut)?this.app_.getResource(Ut):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Ut)&&(t.assetServer=this.app_.getResource(Ut));const s=await mt(this.app_.world,r,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,se,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=Yn(this.app_,e,s);this.app_.addSystemToSchedule(n,t)}return t.setup&&await t.setup(s),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const r=t?.keepPersistent??!0;for(const e of n.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,se)){if(this.app_.world.get(e,se).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())dn(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{En.removePass(e)}catch{}n.postProcessPasses.length=0,this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(t&&"running"===t.status){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,q)){const n=this.app_.world.get(e,q);t.savedAlphas.set(e,n.color.a),n.color={...n.color,a:0},this.app_.world.insert(e,q,n)}}}wake(e){const t=this.scenes_.get(e);if(t&&"sleeping"===t.status){t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,q)){const n=this.app_.world.get(e,q),s=t.savedAlphas.get(e)??1;n.color={...n.color,a:s},this.app_.world.insert(e,q,n)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{En.setEnabled(n,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,n]of this.scenes_)"running"===n.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const Xn=ue(null,"SceneManager");function Yn(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Xn).getSceneStatus(t)&&n._fn(...s)}}}const Nn=Te([fe(Xn),de(me)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Vn={name:"SceneManager",build(e){const t=new jn(e);e.insertResource(Xn,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Xn),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Pe.Startup,n),e.addSystemToSchedule(Pe.Last,Nn)}};class qn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(Pe.Last);else{this.runSchedule(Pe.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Pe.FixedPreUpdate),this.runSchedule(Pe.FixedUpdate),this.runSchedule(Pe.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(Pe.PreUpdate),this.runSchedule(Pe.Update),this.runSchedule(Pe.PostUpdate),this.runSchedule(Pe.Last),this.step_pending_&&(this.step_pending_=!1)}requestAnimationFrame(this.mainLoop)},this.world_=new je,this.resources_=new ge;for(const e of Object.values(Pe))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new qn}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(Pe.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Pe.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return We(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(Xn).register(e),this}setInitialScene(e){return this.getResource(Xn).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Fe(this.world_,this.resources_),this.resources_.insert(me,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Pe.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,fn();const e=[Un,kn,Mn,xn,Qe,nn];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const r=t.get(s);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,r=new Set,o=i=>{if(s.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&o(n)}r.delete(i),s.add(i),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));for(const e of n)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(me);t.delta=e,t.elapsed+=e,t.frameCount++}}function Gn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Jn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Kn(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case Y.FixedWidth:return o;case Y.FixedHeight:return i;case Y.Expand:return Math.max(o,i);case Y.Shrink:return Math.min(o,i);case Y.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function Qn(e,t,n,s,r,o){if(0===n||0===s)return[];const i=e.registry_getCameraEntities(t);if(0===i.length)return[];const a=o&&r?i.filter(e=>{const t=r.tryGet(e,se);return!t||""===t.scene||o.has(t.scene)}):i;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const r=t.getCamera(e),o=t.getLocalTransform(e),i={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=i.w*n/(i.h*s);let h,u=0,d=0;if(r.projectionType===j.Orthographic){if(d=r.orthoSize,l){d=Kn(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}u=d*a,h=es(-u,u,-d,d,-r.farPlane,r.farPlane)}else h=ns(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=rs(o.position.x,o.position.y,o.position.z);c.push({entity:e,viewProjection:new Float32Array(is(h,f)),viewportRect:i,clearFlags:r.clearFlags,priority:r.priority,halfW:u,halfH:d,cameraX:o.position.x,cameraY:o.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const Zn=new Float32Array(16);function es(e,t,n,s,r,o){const i=Zn;i.fill(0);const a=t-e,l=s-n,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+n)/l,i[14]=-(o+r)/c,i[15]=1,i}const ts=new Float32Array(16);function ns(e,t,n,s){const r=ts;r.fill(0);const o=1/Math.tan(e/2),i=n-s;return r[0]=o/t,r[5]=o,r[10]=(s+n)/i,r[11]=-1,r[14]=2*s*n/i,r}const ss=new Float32Array(16);function rs(e,t,n){const s=ss;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}const os=new Float32Array(16);function is(e,t){const n=os;for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}var as,ls,cs;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(as||(as={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(ls||(ls={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(cs||(cs={}));const hs=I("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:as.Left,verticalAlign:ls.Top,wordWrap:!0,overflow:cs.Visible,lineHeight:1.2}),us=I("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class ds{constructor(e){this.cache=new Map,this.module=e,this.canvas=u(_.textCanvasSize,_.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),h=Math.ceil(.2*e.fontSize),u=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=r?Math.ceil(o):u+2*h,p=r?Math.ceil(i):d+2*h;if(r&&e.overflow===cs.Ellipsis&&d>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const g=Math.round(255*e.color.r),m=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${g}, ${m}, ${y}, ${_})`,r&&e.overflow===cs.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(r)switch(e.verticalAlign){case ls.Top:x=h;break;case ls.Middle:x=(p-w)/2;break;case ls.Bottom:x=p-w-h;break;default:x=h}else x=h;let v=x;for(const t of l){let s;switch(e.align){case as.Left:s=h;break;case as.Center:s=f/2;break;case as.Right:s=f-h;break;default:s=h}n.fillText(t,s,v),v+=c}r&&e.overflow===cs.Clip&&n.restore();const b=n.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(f,p,M,S.length,1,!0);return this.module._free(M),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const r=this.renderText(t,n);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case as.Left:return"left";case as.Center:return"center";case as.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function fs(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function ps(e,t,n){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(n?n.size.x:0)||e.containerHeight!==(n?n.size.y:0)}class gs{build(e){W("Text",hs);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new ds(t),s=e.world,r=new Map;e.addSystemToSchedule(Pe.PreUpdate,Te([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,hs));for(const e of r.keys())s.valid(e)&&s.has(e,hs)||r.delete(e);const e=s.getEntitiesWithComponents([hs]);for(const t of e){const e=s.get(t,hs),o=s.has(t,us)?s.get(t,us):null,i=r.get(t);if(i&&!ps(i,e,o))continue;s.has(t,q)||s.insert(t,q,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=n.renderForEntity(t,e,o),l=s.get(t,q);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,q,l),r.set(t,fs(e,o))}}))}}const ms=new gs,ys=I("UIMask",{enabled:!0,mode:"scissor"});function _s(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,o-s)}}function ws(e,t,n,s,r,o,i,a,l,c,h){const u=e-n*r,d=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function g(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*h]}const[m,y]=g(u,f),[_,w]=g(d,p),x=Math.min(m,_),v=Math.max(m,_),b=Math.min(y,w),S=Math.max(y,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function xs(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],h=e[7],u=e[8],d=e[9],f=e[10],p=e[11],g=e[12],m=e[13],y=e[14],_=e[15],w=s*l-r*a,x=s*c-o*a,v=s*h-i*a,b=r*c-o*l,S=r*h-i*l,P=o*h-i*c,M=u*m-d*g,T=u*y-f*g,E=u*_-p*g,C=d*y-f*m,R=d*_-p*m,A=f*_-p*y;let F=w*A-x*R+v*C+b*E-S*T+P*M;return 0===F||(F=1/F,n[0]=(l*A-c*R+h*C)*F,n[1]=(o*R-r*A-i*C)*F,n[2]=(m*P-y*S+_*b)*F,n[3]=(f*S-d*P-p*b)*F,n[4]=(c*E-a*A-h*T)*F,n[5]=(s*A-o*E+i*T)*F,n[6]=(y*v-g*P-_*x)*F,n[7]=(u*P-f*v+p*x)*F,n[8]=(a*R-l*E+h*M)*F,n[9]=(r*E-s*R-i*M)*F,n[10]=(g*S-m*v+_*w)*F,n[11]=(d*v-u*S-p*w)*F,n[12]=(l*T-a*C-c*M)*F,n[13]=(s*C-r*T+o*M)*F,n[14]=(m*x-g*b-y*w)*F,n[15]=(u*b-d*x+f*w)*F),n}function vs(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],h=n[1]*a+n[5]*l+n[13],u=n[3]*a+n[7]*l+n[15];return{x:c/u,y:h/u}}function bs(e,t,n,s,r,o,i,a){return e>=n-r*i&&e<=n+r*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function Ss(e,t,n,s,r,o,i,a,l,c){const h=2*Math.atan2(l,c),u=Math.sin(-h),d=Math.cos(-h),f=e-n,p=t-s,g=f*d-p*u+n,m=f*u+p*d+s;return g>=n-r*i&&g<=n+r*(1-i)&&m>=s-o*a&&m<=s+o*(1-a)}function Ps(e,t,n,s,r,o,i){if(!e.has(t,us)||!e.has(t,V))return null;const a=e.get(t,us),l=e.get(t,V),c=a.size.x*l.scale.x,h=a.size.y*l.scale.y;return ws(l.position.x,l.position.y,c,h,a.pivot.x,a.pivot.y,n,s,r,o,i)}function Ms(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([ys]);if(0===l.length)return;const c=[],h=[],u=new Set,d=new Set;for(const e of l){const n=t.get(e,ys);n.enabled&&(u.add(e),"stencil"===n.mode?(h.push(e),d.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,r,o,i,a,l,c){const h=[];for(const e of s){let n=!0,s=e;for(;t.has(s,Q);){const e=t.get(s,Q);if(r.has(e.entity)){if("scissor"===t.get(e.entity,ys).mode){n=!1;break}}s=e.entity}n&&h.push(e)}function u(s,h){const d=e.getChildEntities(n,s);for(const n of d){let s=h;if(r.has(n)){if("scissor"===t.get(n,ys).mode){const e=Ps(t,n,o,i,a,l,c);e&&(s=_s(h,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),u(n,s)}}for(const e of h){const n=Ps(t,e,o,i,a,l,c);n&&u(e,n)}}(e,t,n,c,u,s,r,o,i,a),h.length>0&&function(e,t,n,s,r){e.renderer_clearStencil();const o=[];for(const e of s){let n=!0,s=e;for(;t.has(s,Q);){const e=t.get(s,Q);if(r.has(e.entity)){n=!1;break}s=e.entity}n&&o.push(e)}let i=1;function a(t,s){e.renderer_setEntityStencilMask(t,s);const o=e.getChildEntities(n,t);for(const t of o)if(r.has(t)){a(t,i++)}else e.renderer_setEntityStencilTest(t,s),l(t,s)}function l(t,s){const o=e.getChildEntities(n,t);for(const t of o)if(r.has(t)){a(t,i++)}else e.renderer_setEntityStencilTest(t,s),l(t,s)}for(const e of o){a(e,i++)}}(e,t,n,h,d)}catch(t){e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class Ts{build(e){if(W("UIMask",ys),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Ms(e.wasmModule,e.world))}}const Es=new Ts,Cs=I("Interactable",{enabled:!0,blockRaycast:!0}),Rs=I("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var As;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(As||(As={}));const Fs=I("Button",{state:As.Normal,transition:null});class Is{constructor(){this.events_=[]}emit(e,t,n){const s=n??e;this.events_.push({entity:e,type:t,target:s,currentTarget:e})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const ks=ue(new Is,"UIEvents"),Bs=k("ScreenSpace");function $s(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,h=o.bottom+e.y*a,u=o.bottom+t.y*a;let d,f,p,g;if(e.x===t.x){const e=l+n.x,t=.5*r.x;d=e-t,p=e+t}else d=l+n.x,p=c+s.x;if(e.y===t.y){const e=h+n.y,t=.5*r.y;f=e-t,g=e+t}else f=h+n.y,g=u+s.y;return{centerX:.5*(d+p),centerY:.5*(f+g),width:p-d,height:g-f,rect:{left:d,bottom:f,right:p,top:g}}}function Ds(e){return{anchorMinX:e.anchorMin.x,anchorMinY:e.anchorMin.y,anchorMaxX:e.anchorMax.x,anchorMaxY:e.anchorMax.y,offsetMinX:e.offsetMin.x,offsetMinY:e.offsetMin.y,offsetMaxX:e.offsetMax.x,offsetMaxY:e.offsetMax.y,sizeX:e.size.x,sizeY:e.size.y}}function Us(e,t){return e.anchorMinX!==t.anchorMin.x||e.anchorMinY!==t.anchorMin.y||e.anchorMaxX!==t.anchorMax.x||e.anchorMaxY!==t.anchorMax.y||e.offsetMinX!==t.offsetMin.x||e.offsetMinY!==t.offsetMin.y||e.offsetMaxX!==t.offsetMax.x||e.offsetMaxY!==t.offsetMax.y||e.sizeX!==t.size.x||e.sizeY!==t.size.y}function zs(e,t){let n=t;for(;;){if(e.has(n,Bs))return n;if(!e.has(n,Q))return null;const t=e.get(n,Q);if(!e.valid(t.entity))return null;n=t.entity}}function Ls(e,t,n,s,r,o){if(!e.has(t,us))return;const i=e.get(t,us),a=$s(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,N);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,N,l),!e.has(t,Z))return;const c=e.get(t,Z);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&Ls(e,t,a.rect,a.centerX,a.centerY,!1)}class Ws{build(e){W("UIRect",us);const t=e.world,n=new Map;let s=NaN,r=NaN,o=NaN,i=NaN;e.addSystemToSchedule(Pe.PreUpdate,Te([de(Xe)],e=>{if(!e.valid)return;const a={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},l=.5*(a.left+a.right),c=.5*(a.bottom+a.top),h=s!==e.worldLeft||r!==e.worldBottom||o!==e.worldRight||i!==e.worldTop;s=e.worldLeft,r=e.worldBottom,o=e.worldRight,i=e.worldTop;const u=new Set;if(h){const e=t.getEntitiesWithComponents([Bs,us,N]);for(const t of e)u.add(t)}const d=t.getEntitiesWithComponents([us]);for(const e of d){const s=t.get(e,us),r=n.get(e);if(!r||Us(r,s)){const n=zs(t,e);null!==n&&u.add(n)}}for(const e of n.keys())if(!t.valid(e)||!t.has(e,us)){n.delete(e);const s=zs(t,e);null!==s&&u.add(s)}for(const e of u)Ls(t,e,a,l,c,!0);for(const e of d){const s=t.get(e,us);n.set(e,Ds(s))}},{name:"UILayoutSystem"}))}}const Os=new Ws,Hs=new Float32Array(16),js=new Float32Array(16);let Xs=!0,Ys=1;function Ns(e,t,n,s){t.emit(n,s,n);let r=n;for(;e.has(r,Q);){const o=e.get(r,Q).entity;if(!e.valid(o))break;if(!e.has(o,Cs)){r=o;continue}const i=e.get(o,Cs);if(i.enabled&&t.emit(o,s,n),i.blockRaycast)break;r=o}}class Vs{build(e){W("Interactable",Cs),W("Button",Fs);const t=e.world,n=new Is;e.insertResource(ks,n);let s=null,r=null;Ys="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Pe.PreUpdate,Te([de(ke),de(Xe)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([Rs]);for(const e of i){const n=t.get(e,Rs);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a=e.mouseX*Ys,l=o.screenH-e.mouseY*Ys;!function(e){let t=!1;for(let n=0;n<16;n++)if(js[n]!==e[n]){t=!0;break}t&&(js.set(e),Xs=!0)}(o.viewProjection),Xs&&(xs(o.viewProjection,Hs),Xs=!1);const c=vs(a,l,Hs,o.vpX,o.vpY,o.vpW,o.vpH),h=t.getEntitiesWithComponents([Cs,us,V]);let u=null,d=-1/0;for(const e of h){t.has(e,Rs)||t.insert(e,Rs);if(!t.get(e,Cs).enabled)continue;const n=t.get(e,V),s=t.get(e,us),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(Ss(c.x,c.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y,n.rotation.z,n.rotation.w)){let n=0;t.has(e,q)&&(n=t.get(e,q).layer),n>=d&&(d=n,u=e)}}if(s!==u){if(null!==s&&t.valid(s)&&t.has(s,Rs)){t.get(s,Rs).hovered=!1,n.emit(s,"hover_exit")}if(null!==u){t.get(u,Rs).hovered=!0,n.emit(u,"hover_enter")}s=u}if(e.isMouseButtonPressed(0)&&null!==u){const e=t.get(u,Rs);e.pressed=!0,e.justPressed=!0,r=u,Ns(t,n,u,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Rs)){const e=t.get(r,Rs);e.pressed=!1,e.justReleased=!0,Ns(t,n,r,"release"),r===s&&Ns(t,n,r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Pe.Update,Te([],()=>{const e=t.getEntitiesWithComponents([Fs]);for(const n of e){if(t.has(n,Cs)||t.insert(n,Cs,{enabled:!0}),!t.has(n,Rs))continue;const e=t.get(n,Rs),s=t.get(n,Fs),r=t.get(n,Cs),o=s.state;if(r.enabled?e.pressed?s.state=As.Pressed:e.hovered?s.state=As.Hovered:s.state=As.Normal:s.state=As.Disabled,o!==s.state&&s.transition&&t.has(n,q)){const e=t.get(n,q),r=s.transition;switch(s.state){case As.Normal:e.color={...r.normalColor};break;case As.Hovered:e.color={...r.hoveredColor};break;case As.Pressed:e.color={...r.pressedColor};break;case As.Disabled:e.color={...r.disabledColor}}t.insert(n,q,e)}}},{name:"ButtonSystem"}))}}const qs=new Vs,Gs=I("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class Js{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){W("TextInput",Gs);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=u(_.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,h=0;const d=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!d)return;const f=d,p=()=>{a||null===i||x()},g=()=>{a=!0},m=()=>{a=!1,x()},y=t=>{if(null===i)return;if("Escape"===t.key)return void S();const s=n.get(i,Gs);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(ks).emit(i,"submit"),void S()}let r=s.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?r=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=s.value.length),r!==s.cursorPos&&(s.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,s.dirty=!0,P())},w=()=>{if(null!==i&&n.valid(i)&&n.has(i,Gs)){const e=n.get(i,Gs);e.focused=!1,e.dirty=!0}i=null};function x(){if(null===i||!n.valid(i))return;const t=n.get(i,Gs);if(t.readOnly)return;let s=f.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),f.value=s),s!==t.value){t.value=s;e.getResource(ks).emit(i,"change")}t.cursorPos=f.selectionStart??s.length,t.dirty=!0,P()}function b(e){if(i===e)return;S();const t=n.get(e,Gs);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),P())}function S(){if(null!==i&&n.valid(i)&&n.has(i,Gs)){const e=n.get(i,Gs);e.focused=!1,e.dirty=!0}i=null,f.blur()}function P(){l=!0,c=0}function M(e,i,a,c){(r.width<a||r.height<c)&&(r.width=Qs(Math.max(r.width,a)),r.height=Qs(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const h=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const u=0===i.value.length,d=u?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=u?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),g=i.padding;if(i.multiline){const e=Ks(o,d,a-2*g);let t=g;for(const n of e)o.fillText(n,g,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(d,g,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=Ks(o,i.value.substring(0,i.cursorPos),a-2*g),r=e.length>0?e[e.length-1]:"";t=g+o.measureText(r).width,n=g+(e.length-1)*p,s=p}else t=g+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const m=o.getImageData(0,0,a,c),y=new Uint8Array(m.data.buffer),_=t.getResourceManager(),w=t._malloc(y.length);t.HEAPU8.set(y,w);const x=s.get(e);void 0!==x&&_.releaseTexture(x);const v=_.createTexture(a,c,w,y.length,1,!0);s.set(e,v),t._free(w);const b=n.get(e,q);b.texture=v,b.size.x=a,b.size.y=c,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},n.insert(e,q,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",g),f.addEventListener("compositionend",m),f.addEventListener("keydown",y),f.addEventListener("blur",w),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",g),f.removeEventListener("compositionend",m),f.removeEventListener("keydown",y),f.removeEventListener("blur",w),f.remove()},e.addSystemToSchedule(Pe.PreUpdate,Te([de(ks)],e=>{const t=n.getEntitiesWithComponents([Gs,Cs]);for(const e of t){if(!n.has(e,Rs))continue;if(n.get(e,Rs).justPressed)return void b(e)}if(null!==i){const e=n.getEntitiesWithComponents([Cs]);for(const t of e){if(n.has(t,Gs))continue;if(!n.has(t,Rs))continue;if(n.get(t,Rs).justPressed)return void S()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Pe.PreUpdate,Te([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===h?0:(e-h)/1e3;if(h=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,Gs)))){n.get(i,Gs).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Gs)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([Gs,us]);for(const e of a){const t=n.get(e,Gs);if(!t.dirty)continue;const s=n.get(e,us),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,q)||n.insert(e,q,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),M(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Ks(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function Qs(e){let t=1;for(;t<e;)t*=2;return t}const Zs=new Js,er={Simple:0,Sliced:1,Tiled:2,Filled:3},tr={Horizontal:0,Vertical:1},nr={Left:0,Right:1,Bottom:2,Top:3},sr=I("Image",{texture:v,color:{r:1,g:1,b:1,a:1},imageType:er.Simple,fillMethod:tr.Horizontal,fillOrigin:nr.Left,fillAmount:1,preserveAspect:!1,layer:0,material:0});const rr=new class{build(e){W("Image",sr);const t=e.world;e.addSystemToSchedule(Pe.PreUpdate,Te([],()=>{const e=t.getEntitiesWithComponents([sr]);for(const n of e){const e=t.get(n,sr);t.has(n,q)||t.insert(n,q,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const s=t.get(n,q);if(s.texture=e.texture,s.color.r=e.color.r,s.color.g=e.color.g,s.color.b=e.color.b,s.color.a=e.color.a,s.layer=e.layer,s.material=e.material,t.has(n,us)){const e=t.get(n,us);s.size.x=e.size.x,s.size.y=e.size.y}if(s.uvOffset.x=0,s.uvOffset.y=0,s.uvScale.x=1,s.uvScale.y=1,e.imageType===er.Filled){const t=Math.max(0,Math.min(1,e.fillAmount));e.fillMethod===tr.Horizontal?e.fillOrigin===nr.Left?(s.uvScale.x=t,s.size.x*=t):(s.uvOffset.x=1-t,s.uvScale.x=t,s.size.x*=t):e.fillOrigin===nr.Bottom?(s.uvScale.y=t,s.size.y*=t):(s.uvOffset.y=1-t,s.uvScale.y=t,s.size.y*=t)}t.insert(n,q,s)}},{name:"ImageSystem"}))}},or=I("Toggle",{isOn:!0,graphicEntity:0,transition:null});const ir=new class{build(e){W("Toggle",or);const t=e.world;e.addSystemToSchedule(Pe.Update,Te([de(ks)],e=>{const n=t.getEntitiesWithComponents([or]);for(const s of n){if(t.has(s,Cs)||t.insert(s,Cs,{enabled:!0}),!t.has(s,Rs))continue;const n=t.get(s,Rs),r=t.get(s,or),o=t.get(s,Cs);if(n.justPressed&&o.enabled&&(r.isOn=!r.isOn,e.emit(s,"change")),r.graphicEntity&&t.valid(r.graphicEntity)){const e=r.graphicEntity;if(t.has(e,q)){const n=t.get(e,q);n.color.a=r.isOn?1:0,t.insert(e,q,n)}}if(r.transition&&t.has(s,q)){const e=t.get(s,q),i=r.transition;o.enabled?n.pressed?e.color={...i.pressedColor}:n.hovered?e.color={...i.hoveredColor}:e.color={...i.normalColor}:e.color={...i.disabledColor},t.insert(s,q,e)}}},{name:"ToggleSystem"}))}};var ar;!function(e){e[e.LeftToRight=0]="LeftToRight",e[e.RightToLeft=1]="RightToLeft",e[e.BottomToTop=2]="BottomToTop",e[e.TopToBottom=3]="TopToBottom"}(ar||(ar={}));const lr=I("ProgressBar",{value:0,fillEntity:0,direction:ar.LeftToRight});const cr=new class{build(e){W("ProgressBar",lr);const t=e.world;e.addSystemToSchedule(Pe.PreUpdate,Te([],()=>{const e=t.getEntitiesWithComponents([lr,us]);for(const n of e){const e=t.get(n,lr);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=e.fillEntity;if(!t.has(s,us))continue;const r=t.get(s,us),o=Math.max(0,Math.min(1,e.value));switch(e.direction){case ar.LeftToRight:r.anchorMin={x:0,y:0},r.anchorMax={x:o,y:1};break;case ar.RightToLeft:r.anchorMin={x:1-o,y:0},r.anchorMax={x:1,y:1};break;case ar.BottomToTop:r.anchorMin={x:0,y:0},r.anchorMax={x:1,y:o};break;case ar.TopToBottom:r.anchorMin={x:0,y:1-o},r.anchorMax={x:1,y:1}}r.offsetMin={x:0,y:0},r.offsetMax={x:0,y:0},t.insert(s,us,r)}},{name:"ProgressBarSystem"}))}},hr=I("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),ur=I("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}}),dr=new Float32Array(16),fr=new Float32Array(16);let pr=!0;function gr(e,t,n){const s=e.mouseX*n,r=t.screenH-e.mouseY*n;return function(e){let t=!1;for(let n=0;n<16;n++)if(fr[n]!==e[n]){t=!0;break}t&&(fr.set(e),pr=!0)}(t.viewProjection),pr&&(xs(t.viewProjection,dr),pr=!1),vs(s,r,dr,t.vpX,t.vpY,t.vpW,t.vpH)}const mr=new class{build(e){W("Draggable",hr),W("DragState",ur);const t=e.world,n=e.getResource(ks);let s=null,r={x:0,y:0},o=null;const i="undefined"!=typeof window&&window.devicePixelRatio||1;e.addSystemToSchedule(Pe.PreUpdate,Te([de(ke),de(Xe)],(e,a)=>{if(!a.valid)return;const l=gr(e,a,i);if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([hr,Rs]);let n=null;for(const s of e){if(!t.get(s,hr).enabled)continue;t.get(s,Rs).hovered&&(n=s)}if(null!==n){s=n,r={x:l.x,y:l.y},t.has(n,ur)||t.insert(n,ur);const e=t.get(n,ur),o=t.get(n,V);e.startWorldPos={x:o.position.x,y:o.position.y},e.currentWorldPos={x:o.position.x,y:o.position.y},e.pointerStartWorld={x:l.x,y:l.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,ur)){t.get(s,ur).isDragging=!1}s=null}if(null!==s&&null===o){if(!t.valid(s))return void(s=null);const e=l.x-r.x,i=l.y-r.y,c=Math.sqrt(e*e+i*i),h=t.get(s,hr);if(c*(a.vpW/(a.worldRight-a.worldLeft))>=h.dragThreshold){o=s,s=null;t.get(o,ur).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,ur))return void(o=null);const s=t.get(o,ur),r=t.get(o,hr),i=l.x-s.pointerStartWorld.x,a=l.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+i,h=s.startWorldPos.y+a;const u=function(e,t,n,s){let r=e.lockX?t.startWorldPos.x:n,o=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(r=Math.max(r,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(r=Math.min(r,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:r,y:o}}(r,s,c,h);c=u.x,h=u.y;const d=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-d,y:h-f},s.currentWorldPos={x:c,y:h},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:h-s.startWorldPos.y},t.has(o,N)){const e=function(e,t,n,s){if(!e.has(t,Q))return{x:n,y:s};const r=e.get(t,Q).entity;if(!e.valid(r)||!e.has(r,V))return{x:n,y:s};const o=e.get(r,V),i=0!==o.scale.x?o.scale.x:1,a=0!==o.scale.y?o.scale.y:1,l=2*Math.atan2(o.rotation.z,o.rotation.w),c=Math.sin(-l),h=Math.cos(-l);return{x:(n*h-s*c)/i,y:(n*c+s*h)/a}}(t,o,s.deltaWorld.x,s.deltaWorld.y),n=t.get(o,N);n.position.x+=e.x,n.position.y+=e.y,t.insert(o,N,n)}n.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},yr=I("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135});const _r=new class{build(e){W("ScrollView",yr);const t=e.world,n=new Map,s=new Float32Array(16),r="undefined"!=typeof window&&window.devicePixelRatio||1;let o=0;e.addSystemToSchedule(Pe.PreUpdate,Te([de(ke),de(Xe)],(e,i)=>{const a=performance.now()/1e3,l=o>0?Math.min(a-o,.05):0;if(o=a,!i.valid)return;const c=e.mouseX*r,h=i.screenH-e.mouseY*r;xs(i.viewProjection,s);const u=vs(c,h,s,i.vpX,i.vpY,i.vpW,i.vpH),d=t.getEntitiesWithComponents([yr,us]);for(const s of d){t.has(s,Cs)||t.insert(s,Cs,{enabled:!0,blockRaycast:!0}),t.has(s,ys)||t.insert(s,ys,{enabled:!0,mode:"scissor"});const r=t.get(s,yr),o=t.get(s,us);let i=n.get(s);i||(i={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0},n.set(s,i));const a=t.has(s,Rs)?t.get(s,Rs):null;if(a?.justPressed&&(i.isDragging=!0,i.lastWorldX=u.x,i.lastWorldY=u.y,i.velocityX=0,i.velocityY=0),i.isDragging&&e.isMouseButtonDown(0)){const e=u.x-i.lastWorldX,t=u.y-i.lastWorldY;r.horizontalEnabled&&(r.scrollX-=e,i.velocityX=l>0?-e/l:0),r.verticalEnabled&&(r.scrollY-=t,i.velocityY=l>0?-t/l:0),i.lastWorldX=u.x,i.lastWorldY=u.y}if(i.isDragging&&e.isMouseButtonReleased(0)&&(i.isDragging=!1),a?.hovered){const t=e.getScrollDelta();r.verticalEnabled&&0!==t.y&&(r.scrollY+=.1*t.y,i.velocityY=0),r.horizontalEnabled&&0!==t.x&&(r.scrollX+=.1*t.x,i.velocityX=0)}if(!i.isDragging&&r.inertia&&l>0){const e=Math.pow(r.decelerationRate,l);r.horizontalEnabled&&Math.abs(i.velocityX)>.1?(r.scrollX+=i.velocityX*l,i.velocityX*=e):i.velocityX=0,r.verticalEnabled&&Math.abs(i.velocityY)>.1?(r.scrollY+=i.velocityY*l,i.velocityY*=e):i.velocityY=0}const c=o.size.x,h=o.size.y,d=Math.max(0,r.contentWidth-c),f=Math.max(0,r.contentHeight-h);if(r.scrollX=Math.max(0,Math.min(r.scrollX,d)),r.scrollY=Math.max(0,Math.min(r.scrollY,f)),0!==r.contentEntity&&t.valid(r.contentEntity)){const e=r.contentEntity;if(t.has(e,N)){const n=t.get(e,N);n.position.x=-r.scrollX,n.position.y=r.scrollY,t.insert(e,N,n)}}}},{name:"ScrollViewSystem"}))}};var wr;!function(e){e[e.LeftToRight=0]="LeftToRight",e[e.RightToLeft=1]="RightToLeft",e[e.BottomToTop=2]="BottomToTop",e[e.TopToBottom=3]="TopToBottom"}(wr||(wr={}));const xr=I("Slider",{value:0,minValue:0,maxValue:1,direction:wr.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});const vr=new class{build(e){W("Slider",xr);const t=e.world,n=new Float32Array(16),s="undefined"!=typeof window&&window.devicePixelRatio||1;let r=null;e.addSystemToSchedule(Pe.PreUpdate,Te([de(ke),de(Xe)],(e,o)=>{if(!o.valid)return;const i=e.mouseX*s,a=o.screenH-e.mouseY*s;xs(o.viewProjection,n);const l=vs(i,a,n,o.vpX,o.vpY,o.vpW,o.vpH),c=t.getEntitiesWithComponents([xr,us,V]);for(const n of c){t.has(n,Cs)||t.insert(n,Cs,{enabled:!0,blockRaycast:!0});const s=t.get(n,xr),o=t.get(n,us),i=t.get(n,V),a=t.has(n,Rs)?t.get(n,Rs):null;if(a?.justPressed&&(r=n),r===n&&e.isMouseButtonDown(0)){const e=o.size.x*i.scale.x,t=o.size.y*i.scale.y,n=i.position.x-o.pivot.x*e,r=i.position.y-o.pivot.y*t;let a;switch(s.direction){case wr.LeftToRight:a=e>0?(l.x-n)/e:0;break;case wr.RightToLeft:a=e>0?1-(l.x-n)/e:0;break;case wr.BottomToTop:a=t>0?(l.y-r)/t:0;break;case wr.TopToBottom:a=t>0?1-(l.y-r)/t:0}a=Math.max(0,Math.min(1,a));let c=s.minValue+a*(s.maxValue-s.minValue);s.wholeNumbers&&(c=Math.round(c)),s.value=Math.max(s.minValue,Math.min(s.maxValue,c))}r===n&&e.isMouseButtonReleased(0)&&(r=null);const c=s.maxValue-s.minValue,h=c>0?(s.value-s.minValue)/c:0;if(0!==s.fillEntity&&t.valid(s.fillEntity)){const e=s.fillEntity;if(t.has(e,us)){const n=t.get(e,us);switch(s.direction){case wr.LeftToRight:n.anchorMin={x:0,y:0},n.anchorMax={x:h,y:1};break;case wr.RightToLeft:n.anchorMin={x:1-h,y:0},n.anchorMax={x:1,y:1};break;case wr.BottomToTop:n.anchorMin={x:0,y:0},n.anchorMax={x:1,y:h};break;case wr.TopToBottom:n.anchorMin={x:0,y:1-h},n.anchorMax={x:1,y:1}}t.insert(e,us,n)}}if(0!==s.handleEntity&&t.valid(s.handleEntity)){const e=s.handleEntity;if(t.has(e,us)){const n=t.get(e,us);switch(s.direction){case wr.LeftToRight:n.anchorMin={x:h,y:0},n.anchorMax={x:h,y:1};break;case wr.RightToLeft:n.anchorMin={x:1-h,y:0},n.anchorMax={x:1-h,y:1};break;case wr.BottomToTop:n.anchorMin={x:0,y:h},n.anchorMax={x:1,y:h};break;case wr.TopToBottom:n.anchorMin={x:0,y:1-h},n.anchorMax={x:1,y:1-h}}t.insert(e,us,n)}}}},{name:"SliderSystem"}))}},br=I("Focusable",{tabIndex:0,isFocused:!1});class Sr{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Pr=ue(new Sr,"FocusManager");const Mr=new class{build(e){W("Focusable",br);const t=e.world,n=new Sr;e.insertResource(Pr,n),e.addSystemToSchedule(Pe.Update,Te([de(ke),de(ks)],(e,s)=>{const r=t.getEntitiesWithComponents([br]);for(const e of r){if(!t.has(e,Rs))continue;t.get(e,Rs).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of r){const s=t.get(n,br);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const i=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===i?a?s.length-1:0:a?(i-1+s.length)%s.length:(i+1)%s.length,o(s[l])}function o(e){const r=n.focusedEntity;if(r===e)return;if(null!==r&&t.valid(r)&&t.has(r,br)){t.get(r,br).isFocused=!1,s.emit(r,"hover_exit",r)}n.focus(e);t.get(e,br).isFocused=!0,s.emit(e,"hover_enter",e)}},{name:"FocusSystem"}))}},Tr=I("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});const Er=new class{build(e){W("SafeArea",Tr);const t=e.world;let n={top:0,bottom:0,left:0,right:0},s=0;e.addSystemToSchedule(Pe.PreUpdate,Te([],()=>{s++%60==0&&(n=function(){if("undefined"==typeof document)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}());const e=t.getEntitiesWithComponents([Tr,us]);for(const s of e){const e=t.get(s,Tr),r=t.get(s,us);let o=!1;const i=e.applyTop?n.top:0,a=e.applyBottom?n.bottom:0,l=e.applyLeft?n.left:0,c=e.applyRight?n.right:0;r.offsetMin.x===l&&r.offsetMin.y===a||(r.offsetMin={x:l,y:a},o=!0),r.offsetMax.x===-c&&r.offsetMax.y===-i||(r.offsetMax={x:-c,y:-i},o=!0),o&&t.insert(s,us,r)}},{name:"SafeAreaSystem"}))}},Cr=I("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2}),Rr=new Map;function Ar(e,t){const n=Rr.get(e);n&&(n.renderer=t)}const Fr=new class{build(e){W("ListView",Cr);const t=e.world;e.addSystemToSchedule(Pe.PreUpdate,Te([de(ke)],e=>{const n=t.getEntitiesWithComponents([Cr,us]);for(const s of n){t.has(s,Cs)||t.insert(s,Cs,{enabled:!0,blockRaycast:!0}),t.has(s,ys)||t.insert(s,ys,{enabled:!0,mode:"scissor"});let n=Rr.get(s);n||(n={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},Rr.set(s,n));const r=t.get(s,Cr),o=t.get(s,us),i=o.size.y,a=t.has(s,Rs)?t.get(s,Rs):null;if(a?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}const l=Math.max(0,r.itemCount*r.itemHeight-i);r.scrollY=Math.max(0,Math.min(r.scrollY,l));const c=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),h=Math.min(r.itemCount,Math.ceil((r.scrollY+i)/r.itemHeight)+r.overscan);for(const[e,s]of n.itemEntities)(e<c||e>=h)&&(t.valid(s)&&t.despawn(s),n.itemEntities.delete(e));for(let e=c;e<h;e++){let i=n.itemEntities.get(e);if(i&&t.valid(i)||(i=t.spawn(),t.insert(i,ne,{value:`ListItem_${e}`}),t.insert(i,us,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o.size.x,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(i,s),n.itemEntities.set(e,i),n.renderer&&n.renderer(e,i)),t.has(i,N)){const n=t.get(i,N);n.position.y=-(e*r.itemHeight-r.scrollY),t.insert(i,N,n)}}n.visibleStart=c,n.visibleEnd=h}},{name:"ListViewSystem"}))}},Ir=I("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const kr=new class{build(e){W("Dropdown",Ir);const t=e.world;e.addSystemToSchedule(Pe.Update,Te([de(ke),de(ks)],(e,n)=>{const s=t.getEntitiesWithComponents([Ir]);for(const o of s){t.has(o,Cs)||t.insert(o,Cs,{enabled:!0,blockRaycast:!0});const s=t.get(o,Ir),i=t.has(o,Rs)?t.get(o,Rs):null;if(i?.justPressed&&(s.isOpen=!s.isOpen,r(s.listEntity,s.isOpen),n.emit(o,"change",o)),s.isOpen&&e.isMouseButtonPressed(0)&&!i?.hovered){0!==s.listEntity&&t.valid(s.listEntity)&&t.has(s.listEntity,Rs)&&t.get(s.listEntity,Rs).hovered||(s.isOpen=!1,r(s.listEntity,!1))}}function r(e,n){if(0===e)return;const s=e;if(!t.valid(s)||!t.has(s,N))return;const r=t.get(s,N),o=n?1:0;r.scale={x:o,y:o,z:o},t.insert(s,N,r)}},{name:"DropdownSystem"}))}};async function Br(e,t,n){const s=e.getResource(Xn);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function $r(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const Dr=ue({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Ur=ue(null,"PhysicsAPI");function zr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Lr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Wr{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Dr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=$r(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([J]);for(const n of t){const t=e.world.get(n,J);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(Pe.PostUpdate,Te([de(me)],a=>{const l=i.getEntitiesWithComponents([oe,N,V]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,oe),l=i.get(r,V);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=zr(l.rotation);s._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Or(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===ce.Kinematic){const e=zr(l.rotation);s._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const h=e.world.get(i,N);if(!h)continue;let u=a,d=l,f=c;if(e.world.has(i,Q)){const t=e.world.get(i,Q);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,V)){const n=e.world.get(t.entity,V),s=zr(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),h=Math.sin(-s);u=(r*i-o*h)/(0!==n.scale.x?n.scale.x:1),d=(r*h+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}h.position.x=u,h.position.y=d;const p=Lr(f);h.rotation.w=p.w,h.rotation.x=p.x,h.rotation.y=p.y,h.rotation.z=p.z,e.world.insert(i,N,h)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],h=t._physics_getSensorExitCount();if(h>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<h;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Dr,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(Ur,Hr._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function Or(e,t,n){const s=e.world;if(s.has(n,ie)){const e=s.get(n,ie);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,ae)){const e=s.get(n,ae);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,le)){const e=s.get(n,le);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Hr{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(Hr.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function jr(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function Xr(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function Yr(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,h=e.rotation.w,u=a+a,d=l+l,f=c+c,p=a*u,g=a*d,m=a*f,y=l*d,_=l*f,w=c*f,x=h*u,v=h*d,b=h*f;return new Float32Array([(1-(y+w))*r,(g+b)*r,(m-v)*r,0,(g-b)*o,(1-(p+w))*o,(_+x)*o,0,(m+v)*i,(_-x)*i,(1-(p+y))*i,0,e.position.x,e.position.y,e.position.z,1])}async function Nr(e,t,n,s,r,o,i,a,l){const c=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=jr(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,c);let h={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),h=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=await r.readText(a),h="binary"===Mt(l)?.contentType;let u,d;if(h){const e=await r.readBinary(i);d=e.length,u=t._malloc(d),t.HEAPU8.set(e,u)}else{const e=await r.readText(i),n=(new TextEncoder).encode(e);d=n.length,u=t._malloc(d+1),t.HEAPU8.set(n,u),t.HEAPU8[u+d]=0}const f=n.loadSkeleton(u,d,s,s.length,h);if(t._free(u),f<0)continue;o[i]=f;const p=Xr(s),g=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=g+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=jr(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,n,s)),o){new Wr("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;const i=Mt(r);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[r]=0;continue}const l=o?`${o}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),h=jr(e,c,!1),u=e.getResourceManager();s[r]=u.loadBitmapFont(t,h,c.width,c.height)}catch{s[r]=0}}return s}(t,n,s),f=await async function(e,t){const n={},s={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===n[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=et.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=et.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s);!function(e,t,n,s){const r={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=pt(e.type);if(0===t.length)continue;const n=e.data;for(const e of t)"string"==typeof n[e.field]&&(n[e.field]=r[e.type][n[e.field]]||0)}}(n,c,d,f);const p=gt(e.world,n);if(l&&e.hasResource(Xn))for(const t of p.values())e.world.insert(t,se,{scene:l,persistent:!1});if(r&&u){const s=function(e,t,n,s){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,n,h,p);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,te)?c.get(o,te):null,h=!1!==a?.playing,u=a?.timeScale??1;h&&s.update(i,l*u);let d=0;if(c.has(o,V)){const e=Yr(c.get(o,V),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),h=n._malloc(l),u=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,h,u,f);const p=n.HEAPU32[u>>2],g=n.HEAPU32[f>>2],m=new Float32Array(n.HEAPF32.buffer,c,8*r),y=new Uint16Array(n.HEAPU8.buffer,h,o),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(m,_>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(y),t.renderer_submitTriangles(_,r,w,o,p,g,d),t._free(_),t._free(w),n._free(c),n._free(h),n._free(u),n._free(f)}d&&t._free(d)}})}(e,t,r,u,s)}if(a){const t=e.getResource(Ut);t&&t.setAddressableManifest(a)}}function Vr(e,t,n){return{name:e,data:t,async setup(){await Nr(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class qr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&("binary"===Mt(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of s){const t=Mt(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Gr="__preview__";class Jr{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(Xn);t.register({name:Gr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Gr),this.loadPromise_=t.load(Gr).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new qr(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.spineInitPromise;if(r){s=(await r).controller.raw}await Nr(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,Gr)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([G]);for(const s of n){if(e.get(s,G).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([J]);for(const r of s){const s=e.get(r,J);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=this.app_.getResource(Xn).getScene(Gr),o=r?r.spawn():e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(o,N,i);const a={isActive:!0,projectionType:j.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:X.ColorAndDepth};e.insert(o,G,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(Xn);await e.switchTo(Gr),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}}const Kr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Bn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Bn.getTargetTexture(n),width:e.width,height:e.height}},release(e){Bn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Bn.releaseRenderTarget(e._handle),Kr.create({width:t,height:n,depth:!0})),begin(e,t){Bn.begin(t,e._handle)},end(){Bn.end()},getDepthTexture:e=>Bn.getTargetDepthTexture(e._handle)};let Qr=!1;function Zr(e){Qr=e}function eo(){return Qr}function to(){return!Qr}var no;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(no||(no={}));class so{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${no[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case no.Debug:console.debug(t,n);break;case no.Info:console.log(t,n);break;case no.Warn:console.warn(t,n);break;case no.Error:console.error(t,n)}}}class ro{constructor(){this.handlers_=[],this.minLevel_=no.Info,this.addHandler(new so)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log(no.Debug,e,t,n)}info(e,t,n){this.log(no.Info,e,t,n)}warn(e,t,n){this.log(no.Warn,e,t,n)}error(e,t,n){this.log(no.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const oo=new ro;function io(){return oo}function ao(e){oo.setMinLevel(e)}function lo(e,t,n){oo.debug(e,t,n)}function co(e,t,n){oo.info(e,t,n)}function ho(e,t,n){oo.warn(e,t,n)}function uo(e,t,n){oo.error(e,t,n)}const fo=[ms,Es,Os,rr,cr,qs,mr,_r,vr,ir,Zs,Mr,Er,Fr,kr];function po(e,t){return function(e,t){const n=qn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),tn(e),Ke(e),wn(e),Pn(e),In(e),Dn(e);const r=new Ln;n.setPipeline(r);let o=d();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,o){o||(o=Qn(e,s,t,r));const i=n.getResource(Xe);if(o.length>0){const e=o[0],n=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(n.x*t),i.vpY=Math.round((1-n.y-n.h)*r),i.vpW=Math.round(n.w*t),i.vpH=Math.round(n.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}n.insertResource(Xe,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=i();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;Bn.setClearColor(e.x,e.y,e.z,e.w)}const h=(d()-o)/1e3;let u;if(Bn.resize(t,l),En.isInitialized()&&En.getPassCount()>0&&!En.isBypassed()&&En.resize(t,l),n.hasResource(Xn)){const e=n.getResource(Xn).getActiveScenes();e.length>0&&(u=new Set(e))}r.setActiveScenes(u??null);const f=Qn(e,s,t,l,n.world,u);if(a(t,l,f),0===f.length)r.render({registry:{_cpp:s},viewProjection:Jn,width:t,height:l,elapsed:h});else{for(const e of f){const n=e.viewportRect,o=Math.round(n.x*t),i=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:c},clearFlags:e.clearFlags,elapsed:h})}Bn.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(Pe.First,l),n.addSystemToSchedule(Pe.Last,c),n.addPlugin(Lt),n.addPlugin(Gt),n.addPlugin($e),n.addPlugin(Vn),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:fo,...t})}e=f;export{qn as App,zt as AssetPlugin,Wt as AssetRefCounter,Dt as AssetServer,Ut as Assets,ct as AsyncCache,ee as BitmapText,Ye as BlendMode,ce as BodyType,ie as BoxCollider,Fs as Button,As as ButtonState,G as Camera,J as Canvas,le as CapsuleCollider,Z as Children,ae as CircleCollider,X as ClearFlags,ve as Commands,Se as CommandsInstance,g as DEFAULT_DESIGN_HEIGHT,p as DEFAULT_DESIGN_WIDTH,m as DEFAULT_PIXELS_PER_UNIT,y as DEFAULT_TEXT_CANVAS_SIZE,pn as DataType,ur as DragState,hr as Draggable,on as Draw,Ir as Dropdown,be as EntityCommands,tr as FillMethod,nr as FillOrigin,Pr as FocusManager,Sr as FocusManagerState,br as Focusable,zn as GLDebug,bn as Geometry,x as INVALID_ENTITY,b as INVALID_FONT,v as INVALID_TEXTURE,sr as Image,er as ImageType,ke as Input,Be as InputPlugin,Ie as InputState,Cs as Interactable,Cr as ListView,N as LocalTransform,no as LogLevel,ro as Logger,et as Material,ht as MaterialLoader,ye as Mut,ne as Name,Q as Parent,Hr as Physics,Dr as PhysicsEvents,Wr as PhysicsPlugin,En as PostProcess,Nt as PrefabServer,Vt as Prefabs,qt as PrefabsPlugin,Jr as PreviewPlugin,lr as ProgressBar,ar as ProgressBarDirection,j as ProjectionType,we as Query,xe as QueryInstance,Ln as RenderPipeline,Rn as RenderStage,Kr as RenderTexture,Bn as Renderer,de as Res,fe as ResMut,oe as RigidBody,_ as RuntimeConfig,Tr as SafeArea,Y as ScaleMode,Xn as SceneManager,jn as SceneManagerState,se as SceneOwner,Pe as Schedule,Bs as ScreenSpace,yr as ScrollView,lt as ShaderSources,xr as Slider,wr as SliderDirection,te as SpineAnimation,q as Sprite,Fe as SystemRunner,hs as Text,as as TextAlign,Gs as TextInput,Js as TextInputPlugin,cs as TextOverflow,gs as TextPlugin,ds as TextRenderer,ls as TextVerticalAlign,me as Time,or as Toggle,Xe as UICameraInfo,Is as UIEventQueue,ks as UIEvents,Rs as UIInteraction,Vs as UIInteractionPlugin,Ws as UILayoutPlugin,ys as UIMask,Ts as UIMaskPlugin,us as UIRect,K as Velocity,qr as WebAssetProvider,je as World,V as WorldTransform,Re as addStartupSystem,Ce as addSystem,Ae as addSystemToSchedule,w as applyRuntimeConfig,Lt as assetPlugin,fn as clearDrawCallbacks,$ as clearUserComponents,T as color,$s as computeUIRectLayout,Ms as createMaskProcessor,Vr as createRuntimeSceneConfig,po as createWebApp,lo as debug,I as defineComponent,ue as defineResource,Te as defineSystem,k as defineTag,uo as error,wt as findEntityByName,Gn as flushPendingSystems,Et as getAddressableType,Ct as getAddressableTypeByEditorType,At as getAllAssetExtensions,Bt as getAssetMimeType,Mt as getAssetTypeEntry,O as getComponent,ft as getComponentAssetFields,re as getComponentDefaults,It as getCustomExtensions,Tt as getEditorType,io as getLogger,t as getPlatform,s as getPlatformType,B as getUserComponent,kt as getWeChatPackOptions,co as info,tn as initDrawAPI,Dn as initGLDebugAPI,wn as initGeometryAPI,Ke as initMaterialAPI,Pn as initPostProcessAPI,In as initRendererAPI,$e as inputPlugin,Ht as instantiatePrefab,_s as intersectRects,xs as invertMatrix4,z as isBuiltinComponent,$t as isCustomExtension,eo as isEditor,Rt as isKnownAssetExtension,n as isPlatformInitialized,to as isRuntime,Ne as isTextureRef,r as isWeChat,o as isWeb,yt as loadComponent,$r as loadPhysicsModule,Nr as loadRuntimeScene,gt as loadSceneData,mt as loadSceneWithAssets,Ft as looksLikeAssetPath,i as platformFetch,c as platformFileExists,h as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Ss as pointInOBB,bs as pointInWorldRect,Gt as prefabsPlugin,E as quat,W as registerComponent,dt as registerComponentAssetFields,un as registerDrawCallback,Ot as registerEmbeddedAssets,at as registerMaterialCallback,Vn as sceneManagerPlugin,vs as screenToWorld,Zr as setEditorMode,Ar as setListViewRenderer,ao as setLogLevel,We as setWasmErrorHandler,nn as shutdownDrawAPI,Un as shutdownGLDebugAPI,xn as shutdownGeometryAPI,Qe as shutdownMaterialAPI,Mn as shutdownPostProcessAPI,kn as shutdownRendererAPI,Zs as textInputPlugin,ms as textPlugin,Br as transitionTo,qs as uiInteractionPlugin,Os as uiLayoutPlugin,Es as uiMaskPlugin,fo as uiPlugins,D as unregisterComponent,dn as unregisterDrawCallback,_t as updateCameraAspectRatio,S as vec2,P as vec3,M as vec4,ho as warn,ws as worldRectToScreen,Yn as wrapSceneSystem};
+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function h(e,n){return t().instantiateWasm(e,n)}function u(e,n){return t().createCanvas(e,n)}function d(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.module}}createImage(){return new Image}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),r=t=>e.onKeyUp(t.code),o=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},i=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},h=()=>{e.onPointerUp(0)},u=t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)};document.addEventListener("keydown",s),document.addEventListener("keyup",r),n.addEventListener("mousemove",o),n.addEventListener("mousedown",i),n.addEventListener("mouseup",a),n.addEventListener("touchstart",l),n.addEventListener("touchmove",c),n.addEventListener("touchend",h),n.addEventListener("wheel",u),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",r),n.removeEventListener("mousemove",o),n.removeEventListener("mousedown",i),n.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",h),n.removeEventListener("wheel",u)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=1920,g=1080,m=100,y=512,_={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function w(e){e.Text&&(e.Text._default.fontFamily=_.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=_.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=_.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=_.canvasMatchWidthOrHeight)}const x=0,v=4294967295,b=4294967295,S=(e=0,t=0)=>({x:e,y:t}),P=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),M=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),T=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),E=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function C(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(C);const t={};for(const n in e)t[n]=C(e[n]);return t}let R=0;function A(e,t){const n=++R;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...C(t),...e}:C(t)}}function F(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function I(e,t){const n=F(),s=n.get(e);if(s)return s;const r=A(e,t);return n.set(e,r),U(e,t,!1),r}function k(e){const t=F(),n=t.get(e);if(n)return n;const s=A(e,{});return t.set(e,s),U(e,{},!0),s}function B(e){return F().get(e)}function $(){F().clear()}function D(e){F().delete(e)}function U(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function z(e){return!0===e._builtin}const L=new Map;function W(e,t){L.set(e,t)}function O(e){return L.get(e)??B(e)}function H(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return L.set(e,n),n}const j={Perspective:0,Orthographic:1},X={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},Y={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},N=H("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),V=H("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),q=H("Sprite",{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),G=H("Camera",{projectionType:j.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:X.ColorAndDepth}),J=H("Canvas",{designResolution:{x:p,y:g},pixelsPerUnit:100,scaleMode:Y.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),K=H("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Q=H("Parent",{entity:0}),Z=H("Children",{entities:[]}),ee=H("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:b,enabled:!0}),te=H("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),ne={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},se=I("SceneOwner",{scene:"",persistent:!1});function re(e){const t=O(e);return t?C(t._default):null}W("Name",ne);const oe=H("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ie=H("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ae=H("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),le=H("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ce={Static:0,Kinematic:1,Dynamic:2};let he=0;function ue(e,t){const n=++he;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function de(e){return{_type:"res",_resource:e}}function fe(e){return{_type:"res_mut",_resource:e}}class pe{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class ge{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new pe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const me=ue({delta:0,elapsed:0,frameCount:0},"Time");function ye(e){return{_type:"mut",_component:e}}function _e(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function we(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{_e(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class xe{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>_e(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=n.length,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let h=null;this.world_.beginIteration();try{for(const u of s){if(null!==h&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(h,t.component,t.data)}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(u,t[n])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,n[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];h=u}yield a}}finally{if(this.world_.endIteration(),null!==h&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(h,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function ve(){return{_type:"commands"}}class be{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=z(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Se{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new be(this,null);return this.spawned_.push(e),e}entity(e){return new be(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Pe;!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(Pe||(Pe={}));let Me=0;function Te(e,t,n){const s=++Me;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Ee(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Ce(e){Ee().push({schedule:Pe.Update,system:e})}function Re(e){Ee().push({schedule:Pe.Startup,system:e})}function Ae(e,t){Ee().push({schedule:e,system:t})}class Fe{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Se&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new xe(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Se(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ie{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const ke=ue(new Ie,"Input");class Be{constructor(e){this.target_=e??null}build(e){const n=new Ie;e.insertResource(ke,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(Pe.Last,Te([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const $e=new Be;function De(e,t,n){const s=[];for(const[e,r]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const n=Ue(t[e]),o=Ue(r);"null"!==n&&"undefined"!==n&&(n!==o&&null!=r&&s.push({field:e,expected:n,actual:o,value:r}))}return s}function Ue(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ze(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let Le=null;function We(e){Le=e}function Oe(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Le&&Le(e,t)}function He(e){const t={};for(const n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:He(e)}}return t}class je{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw Oe(e,"spawn"),e}else e=this.entities_.size+1;return this.entities_.add(e),e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){Oe(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t)this.tsStorage_.get(n)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(n){Oe(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Oe(t,`removeParent(entity=${e})`)}}insert(e,t,n){return z(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return z(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return z(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(z(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return Oe(n,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");z(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_;return t={add:n[`add${e}`].bind(n),get:n[`get${e}`].bind(n),has:n[`has${e}`].bind(n),remove:n[`remove${e}`].bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const e=De(t._name,t._default,s);if(e.length>0)throw new Error(ze(t._name,e))}const r={...t._default,...s};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,He(r))}catch(n){Oe(n,`insertBuiltin(${t._name}, entity=${e})`)}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return this.getBuiltinMethods(t._cppName).get(e)}catch(n){return Oe(n,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(n){return Oe(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){Oe(n,`removeBuiltin(${t._name}, entity=${e})`)}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const r=De(t._name,t._default,e);if(r.length>0)throw new Error(ze(t._name,r));s=e}const r=t.create(s);this.getStorage(t).set(e,r),this.worldVersion_++;let o=this.entityComponents_.get(e);return o||(o=[],this.entityComponents_.set(e,o)),-1===o.indexOf(t._id)&&o.push(t._id),r}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getComponentTypes(e){const t=[];for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.push(n)}catch{}if(this.cppRegistry_)for(const[n,s]of L)if(z(s)&&!t.includes(n))try{this.getBuiltinMethods(s._cppName).has(e)&&t.push(n)}catch{}const n=this.entityComponents_.get(e);if(n){const e="undefined"!=typeof window?window.__esengine_componentRegistry:void 0;if(e)for(const s of n)for(const[n,r]of e)if(r._id===s){t.push(n);break}}return t}getEntitiesWithComponents(e,t=[],n=[]){if(0===e.length&&0===t.length&&0===n.length)return this.getAllEntities();let s=e.map(e=>e._name).sort().join(",");t.length>0&&(s+="|+"+t.map(e=>e._name).sort().join(",")),n.length>0&&(s+="|-"+n.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(s);if(r&&r.version===this.worldVersion_)return r.result;let o=null,i=1/0;for(const t of e)if(!z(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<i&&(i=n,o=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const l=o?o.keys():this.entities_;for(const t of l){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&a.push(t)}return this.queryCache_.set(s,{version:this.worldVersion_,result:a}),a}}const Xe=ue({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var Ye;function Ne(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}!function(e){e[e.Normal=0]="Normal",e[e.Additive=1]="Additive",e[e.Multiply=2]="Multiply",e[e.Screen=3]="Screen",e[e.PremultipliedAlpha=4]="PremultipliedAlpha"}(Ye||(Ye={}));let Ve=null,qe=null,Ge=1;const Je=new Map;function Ke(e){Ve=e,qe=e.getResourceManager(),at()}function Qe(){0!==nt&&Ve&&(Ve._free(nt),nt=0),Je.clear(),Ge=1,tt=!1,rt.clear(),ot=null,qe=null,Ve=null}function Ze(){if(!qe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return qe}const et={createShader:(e,t)=>Ze().createShader(e,t),releaseShader(e){e>0&&Ze().releaseShader(e)},create(e){const t=Ge++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Ye.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return Je.set(t,n),t},get:e=>Je.get(e),setUniform(e,t,n){const s=Je.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=Je.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Je.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Je.get(e);return t?.blendMode??Ye.Normal},setDepthTest(e,t){const n=Je.get(e);n&&(n.depthTest=t)},getShader(e){const t=Je.get(e);return t?.shader??0},release(e){Je.delete(e)},isValid:e=>Je.has(e),releaseAll(){Je.clear()},createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??Ye.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Je.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Ge++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Je.set(n,s),n},toAssetData(e,t){const n=Je.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=Je.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let tt=!1,nt=0;const st=4096,rt=new Map;let ot=null;function it(e){const t=(0===nt&&Ve&&(nt=Ve._malloc(st)),nt);if(0===t||!Ve)return{ptr:0,count:0};let n=0,s=0;const r=Ve.HEAPU8,o=Ve.HEAPU32,i=Ve.HEAPF32;for(const[a,l]of e){if(n+128>st)break;let e=rt.get(a);e||(ot||(ot=new TextEncoder),e=ot.encode(a),rt.set(a,e));const c=e.length,h=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=h;let u=0,d=[0,0,0,0];if("number"==typeof l)u=0,d[0]=l;else if(Array.isArray(l)){u=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(u=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(u=2,d=[l.x,l.y,l.z,0]):"y"in l&&(u=1,d=[l.x,l.y,0,0]);o[t+n>>2]=u,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function at(){if(!Ve||tt)return;Ve.materialDataProvider=(e,t,n,s,r)=>{const o=Je.get(e);if(!o)return Ve.HEAPU32[t>>2]=0,Ve.HEAPU32[n>>2]=0,Ve.HEAPU32[s>>2]=0,void(Ve.HEAPU32[r>>2]=0);Ve.HEAPU32[t>>2]=o.shader,Ve.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=it(o.uniforms);Ve.HEAPU32[s>>2]=i,Ve.HEAPU32[r>>2]=a},tt=!0}const lt={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class ct{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const s=t(),r=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{o.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class ht{constructor(e,t=""){this.cache_=new ct,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(et.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())et.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(r);return{handle:et.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}const ut=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}]]);function dt(e,t){ut.set(e,t)}function ft(e){const t=ut.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function pt(e){return ut.get(e)?.fields??[]}function gt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,ne,{value:s.name}),!1!==s.visible)for(const n of s.components)yt(e,t,n,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function mt(e,t,n){const s=new Map,r=n?.assetServer,o=n?.assetBaseUrl,i=new Map;r&&await async function(e,t,n,s){e=JSON.parse(JSON.stringify(e));const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ut.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,h=new Map,u=new Map,d=[];for(const e of r)d.push((async()=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)d.push((async()=>{try{const s=await t.loadMaterial(e,n);h.set(e,s.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),h.set(e,0)}})());for(const e of i)d.push((async()=>{try{const s=await t.loadBitmapFont(e,n);u.set(e,s)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),u.set(e,0)}})());for(const e of a)d.push((async()=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)})());await Promise.all(d);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ut.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":n[e.field]=c.get(t)??0;break;case"material":n[e.field]=h.get(t)??0;break;case"font":n[e.field]=u.get(t)??0}}}}(t,r,o,i);for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,ne,{value:n.name}),!1!==n.visible)for(const s of n.components)yt(e,t,s,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function yt(e,t,n,s){if("UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=O(n.type);if(r)e.insert(t,r,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function _t(e,t){const n=e.getEntitiesWithComponents([G]);for(const s of n){const n=e.get(s,G);n&&(n.aspectRatio=t,e.insert(s,G,n))}}function wt(e,t){const n=e.getEntitiesWithComponents([ne]);for(const s of n){const n=e.get(s,ne);if(n&&n.value===t)return s}return null}const xt=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],vt={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},bt=new Map,St=new Set;for(const e of xt)for(const t of e.extensions)bt.set(t,e),St.add(t);function Pt(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function Mt(e){return bt.get(Pt(e))}function Tt(e){return Mt(e)?.editorType??"unknown"}function Et(e){return Mt(e)?.addressableType??null}function Ct(e){for(const t of xt)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function Rt(e){return St.has(e.toLowerCase())}function At(){return St}function Ft(e){return"string"==typeof e&&(!!e.includes("/")&&Rt(Pt(e)))}function It(){const e=[];for(const t of xt)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function kt(){return It().map(e=>({type:"suffix",value:e}))}function Bt(e){return vt[e.toLowerCase()]}function $t(e){const t=Mt(e);return t?.wechatPackInclude??!1}class Dt{constructor(e){this.textureCache_=new ct,this.shaderCache_=new ct,this.jsonCache_=new ct,this.textCache_=new ct,this.binaryCache_=new ct,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new ct,this.prefabCache_=new ct,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.module_=e,this.canvas_=u(_.textCanvasSize,_.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new ht(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);if(!r)continue;const o=(this.textureRefCounts_.get(s)??1)-1;o<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),et.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),h="binary"===Mt(e)?.contentType,u=h?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(u,o,h);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),r=l.find(e=>e.name===n);if(r){const n=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,r.info.width,r.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=Mt(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return mt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const r=s.metadata?.atlas;r&&n.push(this.loadSpine(s.path,r).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??n;return new Promise((n,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return et.createShader(s,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:o}=this.parseEsShader(s);if(!r||!o)throw new Error(`Invalid shader format: ${e}`);return et.createShader(r,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Ut=ue(null,"Assets");class zt{build(e){const t=e.wasmModule;t?e.insertResource(Ut,new Dt(t)):console.warn("AssetPlugin: No WASM module available")}}const Lt=new zt;class Wt{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function Ot(e,t){const n=e.getResource(Ut);n&&n.registerEmbeddedAssets(t)}async function Ht(e,t,n){const{entities:s,rootId:r}=await Xt(t,n?.overrides??[],n,void 0,new Set),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await mt(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}const jt=10;async function Xt(e,t,n,s,r,o=0){if(o>jt)throw new Error(`Prefab nesting depth exceeded ${jt}. Check for deep or circular nesting in: ${e.name}`);const i=new Map;let a;if(void 0===s){a=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=s;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(r?.has(s.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${s.nestedPrefab.prefabPath}`);continue}r?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await Xt(e,s.nestedPrefab.overrides,n,a,r,o+1);i.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?i.get(s.parent)??null:null),l.push(...t.entities);continue}const c=i.get(s.prefabEntityId),h=s.prefabEntityId===e.rootEntityId,u={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:h?null:null!==s.parent?i.get(s.parent)??null:null,children:s.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};Yt(u,t),l.push(u)}const c=i.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function Yt(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class Nt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,r=await this.assetServer_.loadPrefab(s,t?.baseUrl);return Ht(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Vt=ue(null,"Prefabs");class qt{constructor(){this.name="PrefabsPlugin",this.dependencies=[Ut]}build(e){const t=e.getResource(Ut);e.insertResource(Vt,new Nt(e.world,t))}}const Gt=new qt;let Jt=null,Kt=0,Qt=0,Zt=0;const en=new Float32Array(256);function tn(e){Jt=e,Kt=Jt._malloc(64),Qt=Jt._malloc(64),Zt=Jt._malloc(1024)}function nn(){Jt&&(Kt&&(Jt._free(Kt),Kt=0),Qt&&(Jt._free(Qt),Qt=0),Zt&&(Jt._free(Zt),Zt=0)),Jt=null}function sn(){if(!Jt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Jt}const rn={r:1,g:1,b:1,a:1},on={begin(e){const t=sn();try{t.HEAPF32.set(e,Kt/4),t.draw_begin(Kt)}catch(e){Oe(e,"Draw.begin")}},end(){try{sn().draw_end()}catch(e){Oe(e,"Draw.end")}},line(e,t,n,s=1){try{sn().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Oe(e,"Draw.line")}},rect(e,t,n,s=!0){try{sn().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Oe(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{sn().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Oe(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,r=32){try{sn().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)}catch(e){Oe(e,"Draw.circle")}},circleOutline(e,t,n,s=1,r=32){try{sn().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)}catch(e){Oe(e,"Draw.circleOutline")}},texture(e,t,n,s=rn){try{sn().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){Oe(e,"Draw.texture")}},textureRotated(e,t,n,s,r=rn){try{sn().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)}catch(e){Oe(e,"Draw.textureRotated")}},setLayer(e){sn().draw_setLayer(e)},setDepth(e){sn().draw_setDepth(e)},getDrawCallCount:()=>Jt?Jt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Jt?Jt.draw_getPrimitiveCount():0,setBlendMode(e){sn().draw_setBlendMode(e)},setDepthTest(e){sn().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=sn();s.HEAPF32.set(n,Qt/4),s.draw_mesh(e,t,Qt)}catch(n){Oe(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=sn(),r=et.get(t);if(!r)return;if(on.setBlendMode(r.blendMode),on.setDepthTest(r.depthTest),0===r.uniforms.size)return void on.drawMesh(e,r.shader,n);let o;if(s.HEAPF32.set(n,Qt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,n]of r.uniforms){const s=cn(t);if(!(s<0)){if(Ne(n))en[o++]=10,en[o++]=s,en[o++]=n.slot??e++,en[o++]=n.textureId;else if("number"==typeof n)en[o++]=1,en[o++]=s,en[o++]=n;else if(Array.isArray(n)){en[o++]=n.length,en[o++]=s;for(let e=0;e<n.length;e++)en[o++]=n[e]}else"w"in n?(en[o++]=4,en[o++]=s,en[o++]=n.x,en[o++]=n.y,en[o++]=n.z,en[o++]=n.w):"z"in n?(en[o++]=3,en[o++]=s,en[o++]=n.x,en[o++]=n.y,en[o++]=n.z):(en[o++]=2,en[o++]=s,en[o++]=n.x,en[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(en.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void s.draw_mesh(e,r.shader,Qt);s.HEAPF32.set(r.cachedBuffer_.subarray(0,o),Zt/4),s.draw_meshWithUniforms(e,r.shader,Qt,Zt,o)}catch(n){Oe(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},an={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17},ln=new Set;function cn(e){const t=an[e];return void 0!==t?t:(ln.has(e)||(ln.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(an).join(", ")}`)),-1)}const hn=new Map;function un(e,t,n){hn.set(e,{fn:t,scene:n??""})}function dn(e){hn.delete(e)}function fn(){hn.clear()}var pn;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(pn||(pn={}));let gn=null,mn=0,yn=0,_n=0;function wn(e){gn=e,mn=gn._malloc(262144),yn=gn._malloc(65536),_n=gn._malloc(256)}function xn(){gn&&(mn&&gn._free(mn),yn&&gn._free(yn),_n&&gn._free(_n),mn=0,yn=0,_n=0),gn=null}function vn(){if(!gn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return gn}const bn={create(e){const t=vn(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,mn/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,_n,r).set(o),t.geometry_init(n,mn,s,_n,r,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,yn,s).set(e.indices),t.geometry_setIndices16(n,yn,s)}else{new Uint32Array(t.HEAPU8.buffer,yn,s).set(e.indices),t.geometry_setIndices32(n,yn,s)}}return n},updateVertices(e,t,n=0){const s=vn(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,mn/4),s.geometry_updateVertices(e,mn,r,n)},release(e){e>0&&vn().geometry_release(e)},isValid:e=>!(!gn||e<=0)&&gn.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return bn.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:pn.Float2},{name:"a_texCoord",type:pn.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;n.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return bn.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:pn.Float2},{name:"a_texCoord",type:pn.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-n);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return bn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:pn.Float2},{name:"a_texCoord",type:pn.Float2}],indices:new Uint16Array(i)})}};let Sn=null;function Pn(e){Sn=e}function Mn(){Sn&&En.isInitialized()&&En.shutdown(),Sn=null}function Tn(){if(!Sn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Sn}const En={init(e,t){try{return Tn().postprocess_init(e,t)}catch(n){return Oe(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Tn().postprocess_shutdown()}catch(e){Oe(e,"PostProcess.shutdown")}},resize(e,t){try{Tn().postprocess_resize(e,t)}catch(n){Oe(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Tn().postprocess_addPass(e,t)}catch(t){return Oe(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Tn().postprocess_removePass(e)}catch(t){Oe(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Tn().postprocess_setPassEnabled(e,t)}catch(t){Oe(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Tn().postprocess_isPassEnabled(e)}catch(t){return Oe(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{Tn().postprocess_setUniformFloat(e,t,n)}catch(n){Oe(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{Tn().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){Oe(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Tn().postprocess_begin()}catch(e){Oe(e,"PostProcess.begin")}},end(){try{Tn().postprocess_end()}catch(e){Oe(e,"PostProcess.end")}},getPassCount(){try{return Tn().postprocess_getPassCount()}catch(e){return Oe(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Sn)return!1;try{return Sn.postprocess_isInitialized()}catch(e){return Oe(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Tn().postprocess_setBypass(e)}catch(e){Oe(e,"PostProcess.setBypass")}},isBypassed(){if(!Sn)return!0;try{return Sn.postprocess_isBypassed()}catch(e){return Oe(e,"PostProcess.isBypassed"),!0}},createBlur:()=>et.createShader(Cn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>et.createShader(Cn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>et.createShader(Cn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>et.createShader(Cn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},Cn="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var Rn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Rn||(Rn={}));let An=null,Fn=0;function In(e){An=e,Fn=An._malloc(64)}function kn(){An&&Fn&&(An._free(Fn),Fn=0),An=null}const Bn={init(e,t){An?.renderer_init(e,t)},resize(e,t){An?.renderer_resize(e,t)},begin(e,t){if(An&&Fn)try{An.HEAPF32.set(e,Fn/4),An.renderer_begin(Fn,t??0)}catch(e){Oe(e,"Renderer.begin")}},flush(){try{An?.renderer_flush()}catch(e){Oe(e,"Renderer.flush")}},end(){try{An?.renderer_end()}catch(e){Oe(e,"Renderer.end")}},submitSprites(e){if(An)try{An.renderer_submitSprites(e._cpp)}catch(e){Oe(e,"Renderer.submitSprites")}},submitBitmapText(e){if(An)try{An.renderer_submitBitmapText(e._cpp)}catch(e){Oe(e,"Renderer.submitBitmapText")}},submitSpine(e){if(An)try{An.renderer_submitSpine?.(e._cpp)}catch(e){Oe(e,"Renderer.submitSpine")}},setStage(e){An?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>An?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){An?.renderer_releaseTarget(e)},getTargetTexture:e=>An?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>An?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){An?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){An?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){An?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){An?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>An?An.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>An?{drawCalls:An.renderer_getDrawCalls(),triangles:An.renderer_getTriangles(),sprites:An.renderer_getSprites(),text:An.renderer_getText(),spine:An.renderer_getSpine?.()??0,meshes:An.renderer_getMeshes(),culled:An.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let $n=null;function Dn(e){$n=e}function Un(){$n=null}const zn={enable(){$n?.gl_enableErrorCheck(!0)},disable(){$n?.gl_enableErrorCheck(!1)},check:e=>$n?.gl_checkErrors(e)??0,diagnose(){$n?.renderer_diagnose()}};class Ln{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(Bn.resize(s,r),En.isInitialized()&&En.getPassCount()>0&&En.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),Bn.setViewport(0,0,s,r),Bn.clearBuffers(3),Bn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),Bn.submitSprites(t),Bn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Bn.submitSpine(t),Bn.flush(),this.executeDrawCallbacks(n,o),Bn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;Bn.setViewport(s.x,s.y,s.w,s.h),Bn.setScissor(s.x,s.y,s.w,s.h,!0),Bn.clearBuffers(r),Bn.setScissor(0,0,0,0,!1),Bn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Bn.submitSprites(t),Bn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Bn.submitSpine(t),Bn.flush(),this.executeDrawCallbacks(n,o),Bn.end()}executeDrawCallbacks(e,t){const n=hn;if(n.size>0){on.begin(e);const s=[];for(const[e,r]of n.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}on.end();for(const e of s)dn(e)}}}const Wn="__scene_transition_overlay__";class On{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class Hn{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,se,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),un(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=En.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){En.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,se)){const n=this.app_.world.get(e,se);n.persistent=t,this.app_.world.insert(e,se,n)}}}class jn{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_)return void console.warn(`[SceneManager] Transition already in progress, ignoring switchTo("${e}")`);"fade"!==(t?.transition??"none")?(this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)):await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(n=>{const s=t.duration??_.sceneTransitionDuration,r=t.color??{..._.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:r,targetScene:e,options:t,resolve:n},un(Wn,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;on.setLayer(9999),on.setDepth(9999),on.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{n&&n!==e&&await this.unload(n,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,dn(Wn)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,dn(Wn),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new On(t);this.scenes_.set(e,n);const s=new Hn(n,this.app_);this.contexts_.set(e,s);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Ut)?this.app_.getResource(Ut):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Ut)&&(t.assetServer=this.app_.getResource(Ut));const s=await mt(this.app_.world,r,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,se,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=Yn(this.app_,e,s);this.app_.addSystemToSchedule(n,t)}return t.setup&&await t.setup(s),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new On(t);this.scenes_.set(e,n);const s=new Hn(n,this.app_);this.contexts_.set(e,s);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Ut)?this.app_.getResource(Ut):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Ut)&&(t.assetServer=this.app_.getResource(Ut));const s=await mt(this.app_.world,r,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,se,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=Yn(this.app_,e,s);this.app_.addSystemToSchedule(n,t)}return t.setup&&await t.setup(s),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const r=t?.keepPersistent??!0;for(const e of n.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,se)){if(this.app_.world.get(e,se).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())dn(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{En.removePass(e)}catch{}n.postProcessPasses.length=0,this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(t&&"running"===t.status){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,q)){const n=this.app_.world.get(e,q);t.savedAlphas.set(e,n.color.a),n.color={...n.color,a:0},this.app_.world.insert(e,q,n)}}}wake(e){const t=this.scenes_.get(e);if(t&&"sleeping"===t.status){t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,q)){const n=this.app_.world.get(e,q),s=t.savedAlphas.get(e)??1;n.color={...n.color,a:s},this.app_.world.insert(e,q,n)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{En.setEnabled(n,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,n]of this.scenes_)"running"===n.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const Xn=ue(null,"SceneManager");function Yn(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Xn).getSceneStatus(t)&&n._fn(...s)}}}const Nn=Te([fe(Xn),de(me)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Vn={name:"SceneManager",build(e){const t=new jn(e);e.insertResource(Xn,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Xn),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Pe.Startup,n),e.addSystemToSchedule(Pe.Last,Nn)}};class qn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(Pe.Last);else{this.runSchedule(Pe.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Pe.FixedPreUpdate),this.runSchedule(Pe.FixedUpdate),this.runSchedule(Pe.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(Pe.PreUpdate),this.runSchedule(Pe.Update),this.runSchedule(Pe.PostUpdate),this.runSchedule(Pe.Last),this.step_pending_&&(this.step_pending_=!1)}requestAnimationFrame(this.mainLoop)},this.world_=new je,this.resources_=new ge;for(const e of Object.values(Pe))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new qn}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(Pe.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Pe.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return We(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(Xn).register(e),this}setInitialScene(e){return this.getResource(Xn).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Fe(this.world_,this.resources_),this.resources_.insert(me,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Pe.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,fn();const e=[Un,kn,Mn,xn,Qe,nn];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const r=t.get(s);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,r=new Set,o=i=>{if(s.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&o(n)}r.delete(i),s.add(i),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));for(const e of n)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(me);t.delta=e,t.elapsed+=e,t.frameCount++}}function Gn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Jn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Kn(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case Y.FixedWidth:return o;case Y.FixedHeight:return i;case Y.Expand:return Math.max(o,i);case Y.Shrink:return Math.min(o,i);case Y.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function Qn(e,t,n,s,r,o){if(0===n||0===s)return[];const i=e.registry_getCameraEntities(t);if(0===i.length)return[];const a=o&&r?i.filter(e=>{const t=r.tryGet(e,se);return!t||""===t.scene||o.has(t.scene)}):i;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const r=t.getCamera(e),o=t.getLocalTransform(e),i={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=i.w*n/(i.h*s);let h,u=0,d=0;if(r.projectionType===j.Orthographic){if(d=r.orthoSize,l){d=Kn(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}u=d*a,h=es(-u,u,-d,d,-r.farPlane,r.farPlane)}else h=ns(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=rs(o.position.x,o.position.y,o.position.z);c.push({entity:e,viewProjection:new Float32Array(is(h,f)),viewportRect:i,clearFlags:r.clearFlags,priority:r.priority,halfW:u,halfH:d,cameraX:o.position.x,cameraY:o.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const Zn=new Float32Array(16);function es(e,t,n,s,r,o){const i=Zn;i.fill(0);const a=t-e,l=s-n,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+n)/l,i[14]=-(o+r)/c,i[15]=1,i}const ts=new Float32Array(16);function ns(e,t,n,s){const r=ts;r.fill(0);const o=1/Math.tan(e/2),i=n-s;return r[0]=o/t,r[5]=o,r[10]=(s+n)/i,r[11]=-1,r[14]=2*s*n/i,r}const ss=new Float32Array(16);function rs(e,t,n){const s=ss;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}const os=new Float32Array(16);function is(e,t){const n=os;for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}var as,ls,cs;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(as||(as={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(ls||(ls={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(cs||(cs={}));const hs=I("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:as.Left,verticalAlign:ls.Top,wordWrap:!0,overflow:cs.Visible,lineHeight:1.2}),us=I("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class ds{constructor(e){this.cache=new Map,this.module=e,this.canvas=u(_.textCanvasSize,_.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),h=Math.ceil(.2*e.fontSize),u=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=r?Math.ceil(o):u+2*h,p=r?Math.ceil(i):d+2*h;if(r&&e.overflow===cs.Ellipsis&&d>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const g=Math.round(255*e.color.r),m=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${g}, ${m}, ${y}, ${_})`,r&&e.overflow===cs.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(r)switch(e.verticalAlign){case ls.Top:x=h;break;case ls.Middle:x=(p-w)/2;break;case ls.Bottom:x=p-w-h;break;default:x=h}else x=h;let v=x;for(const t of l){let s;switch(e.align){case as.Left:s=h;break;case as.Center:s=f/2;break;case as.Right:s=f-h;break;default:s=h}n.fillText(t,s,v),v+=c}r&&e.overflow===cs.Clip&&n.restore();const b=n.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(f,p,M,S.length,1,!0);return this.module._free(M),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const r=this.renderText(t,n);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case as.Left:return"left";case as.Center:return"center";case as.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function fs(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function ps(e,t,n){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(n?n.size.x:0)||e.containerHeight!==(n?n.size.y:0)}class gs{build(e){W("Text",hs);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new ds(t),s=e.world,r=new Map;e.addSystemToSchedule(Pe.PreUpdate,Te([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,hs));for(const e of r.keys())s.valid(e)&&s.has(e,hs)||r.delete(e);const e=s.getEntitiesWithComponents([hs]);for(const t of e){const e=s.get(t,hs),o=s.has(t,us)?s.get(t,us):null,i=r.get(t);if(i&&!ps(i,e,o))continue;s.has(t,q)||s.insert(t,q,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=n.renderForEntity(t,e,o),l=s.get(t,q);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,q,l),r.set(t,fs(e,o))}}))}}const ms=new gs,ys=I("UIMask",{enabled:!0,mode:"scissor"});function _s(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,o-s)}}function ws(e,t,n,s,r,o,i,a,l,c,h){const u=e-n*r,d=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function g(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*h]}const[m,y]=g(u,f),[_,w]=g(d,p),x=Math.min(m,_),v=Math.max(m,_),b=Math.min(y,w),S=Math.max(y,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function xs(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],h=e[7],u=e[8],d=e[9],f=e[10],p=e[11],g=e[12],m=e[13],y=e[14],_=e[15],w=s*l-r*a,x=s*c-o*a,v=s*h-i*a,b=r*c-o*l,S=r*h-i*l,P=o*h-i*c,M=u*m-d*g,T=u*y-f*g,E=u*_-p*g,C=d*y-f*m,R=d*_-p*m,A=f*_-p*y;let F=w*A-x*R+v*C+b*E-S*T+P*M;return 0===F||(F=1/F,n[0]=(l*A-c*R+h*C)*F,n[1]=(o*R-r*A-i*C)*F,n[2]=(m*P-y*S+_*b)*F,n[3]=(f*S-d*P-p*b)*F,n[4]=(c*E-a*A-h*T)*F,n[5]=(s*A-o*E+i*T)*F,n[6]=(y*v-g*P-_*x)*F,n[7]=(u*P-f*v+p*x)*F,n[8]=(a*R-l*E+h*M)*F,n[9]=(r*E-s*R-i*M)*F,n[10]=(g*S-m*v+_*w)*F,n[11]=(d*v-u*S-p*w)*F,n[12]=(l*T-a*C-c*M)*F,n[13]=(s*C-r*T+o*M)*F,n[14]=(m*x-g*b-y*w)*F,n[15]=(u*b-d*x+f*w)*F),n}function vs(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],h=n[1]*a+n[5]*l+n[13],u=n[3]*a+n[7]*l+n[15];return{x:c/u,y:h/u}}function bs(e,t,n,s,r,o,i,a){return e>=n-r*i&&e<=n+r*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function Ss(e,t,n,s,r,o,i,a,l,c){const h=2*Math.atan2(l,c),u=Math.sin(-h),d=Math.cos(-h),f=e-n,p=t-s,g=f*d-p*u+n,m=f*u+p*d+s;return g>=n-r*i&&g<=n+r*(1-i)&&m>=s-o*a&&m<=s+o*(1-a)}function Ps(e,t,n,s,r,o,i){if(!e.has(t,us)||!e.has(t,V))return null;const a=e.get(t,us),l=e.get(t,V),c=a.size.x*l.scale.x,h=a.size.y*l.scale.y;return ws(l.position.x,l.position.y,c,h,a.pivot.x,a.pivot.y,n,s,r,o,i)}function Ms(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([ys]);if(0===l.length)return;const c=[],h=[],u=new Set,d=new Set;for(const e of l){const n=t.get(e,ys);n.enabled&&(u.add(e),"stencil"===n.mode?(h.push(e),d.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,r,o,i,a,l,c){const h=[];for(const e of s){let n=!0,s=e;for(;t.has(s,Q);){const e=t.get(s,Q);if(r.has(e.entity)){if("scissor"===t.get(e.entity,ys).mode){n=!1;break}}s=e.entity}n&&h.push(e)}function u(s,h){const d=e.getChildEntities(n,s);for(const n of d){let s=h;if(r.has(n)){if("scissor"===t.get(n,ys).mode){const e=Ps(t,n,o,i,a,l,c);e&&(s=_s(h,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),u(n,s)}}for(const e of h){const n=Ps(t,e,o,i,a,l,c);n&&u(e,n)}}(e,t,n,c,u,s,r,o,i,a),h.length>0&&function(e,t,n,s,r){e.renderer_clearStencil();const o=[];for(const e of s){let n=!0,s=e;for(;t.has(s,Q);){const e=t.get(s,Q);if(r.has(e.entity)){n=!1;break}s=e.entity}n&&o.push(e)}let i=1;function a(t,s){e.renderer_setEntityStencilMask(t,s);const o=e.getChildEntities(n,t);for(const t of o)if(r.has(t)){a(t,i++)}else e.renderer_setEntityStencilTest(t,s),l(t,s)}function l(t,s){const o=e.getChildEntities(n,t);for(const t of o)if(r.has(t)){a(t,i++)}else e.renderer_setEntityStencilTest(t,s),l(t,s)}for(const e of o){a(e,i++)}}(e,t,n,h,d)}catch(t){e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class Ts{build(e){if(W("UIMask",ys),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Ms(e.wasmModule,e.world))}}const Es=new Ts,Cs=I("Interactable",{enabled:!0,blockRaycast:!0}),Rs=I("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var As;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(As||(As={}));const Fs=I("Button",{state:As.Normal,transition:null,enabled:!0});class Is{constructor(){this.events_=[]}emit(e,t,n){const s=n??e;this.events_.push({entity:e,type:t,target:s,currentTarget:e})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const ks=ue(new Is,"UIEvents"),Bs=k("ScreenSpace");function $s(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,h=o.bottom+e.y*a,u=o.bottom+t.y*a;let d,f,p,g;if(e.x===t.x){const e=l+n.x,t=.5*r.x;d=e-t,p=e+t}else d=l+n.x,p=c+s.x;if(e.y===t.y){const e=h+n.y,t=.5*r.y;f=e-t,g=e+t}else f=h+n.y,g=u+s.y;return{centerX:.5*(d+p),centerY:.5*(f+g),width:p-d,height:g-f,rect:{left:d,bottom:f,right:p,top:g}}}function Ds(e){return{anchorMinX:e.anchorMin.x,anchorMinY:e.anchorMin.y,anchorMaxX:e.anchorMax.x,anchorMaxY:e.anchorMax.y,offsetMinX:e.offsetMin.x,offsetMinY:e.offsetMin.y,offsetMaxX:e.offsetMax.x,offsetMaxY:e.offsetMax.y,sizeX:e.size.x,sizeY:e.size.y}}function Us(e,t){return e.anchorMinX!==t.anchorMin.x||e.anchorMinY!==t.anchorMin.y||e.anchorMaxX!==t.anchorMax.x||e.anchorMaxY!==t.anchorMax.y||e.offsetMinX!==t.offsetMin.x||e.offsetMinY!==t.offsetMin.y||e.offsetMaxX!==t.offsetMax.x||e.offsetMaxY!==t.offsetMax.y||e.sizeX!==t.size.x||e.sizeY!==t.size.y}function zs(e,t){let n=t;for(;;){if(e.has(n,Bs))return n;if(!e.has(n,Q))return null;const t=e.get(n,Q);if(!e.valid(t.entity))return null;n=t.entity}}function Ls(e,t,n,s,r,o){if(!e.has(t,us))return;const i=e.get(t,us),a=$s(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,N);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,N,l),!e.has(t,Z))return;const c=e.get(t,Z);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&Ls(e,t,a.rect,a.centerX,a.centerY,!1)}class Ws{build(e){W("UIRect",us);const t=e.world,n=new Map;let s=NaN,r=NaN,o=NaN,i=NaN;e.addSystemToSchedule(Pe.PreUpdate,Te([de(Xe)],e=>{if(!e.valid)return;const a={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},l=.5*(a.left+a.right),c=.5*(a.bottom+a.top),h=s!==e.worldLeft||r!==e.worldBottom||o!==e.worldRight||i!==e.worldTop;s=e.worldLeft,r=e.worldBottom,o=e.worldRight,i=e.worldTop;const u=new Set;if(h){const e=t.getEntitiesWithComponents([Bs,us,N]);for(const t of e)u.add(t)}const d=t.getEntitiesWithComponents([us]);for(const e of d){const s=t.get(e,us),r=n.get(e);if(!r||Us(r,s)){const n=zs(t,e);null!==n&&u.add(n)}}for(const e of n.keys())if(!t.valid(e)||!t.has(e,us)){n.delete(e);const s=zs(t,e);null!==s&&u.add(s)}for(const e of u)Ls(t,e,a,l,c,!0);for(const e of d){const s=t.get(e,us);n.set(e,Ds(s))}},{name:"UILayoutSystem"}))}}const Os=new Ws,Hs=new Float32Array(16),js=new Float32Array(16);let Xs=!0,Ys=1;function Ns(e,t,n,s){t.emit(n,s,n);let r=n;for(;e.has(r,Q);){const o=e.get(r,Q).entity;if(!e.valid(o))break;if(!e.has(o,Cs)){r=o;continue}const i=e.get(o,Cs);if(i.enabled&&t.emit(o,s,n),i.blockRaycast)break;r=o}}class Vs{build(e){W("Interactable",Cs),W("Button",Fs);const t=e.world,n=new Is;e.insertResource(ks,n);let s=null,r=null;Ys="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Pe.PreUpdate,Te([de(ke),de(Xe)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([Rs]);for(const e of i){const n=t.get(e,Rs);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a=e.mouseX*Ys,l=o.screenH-e.mouseY*Ys;!function(e){let t=!1;for(let n=0;n<16;n++)if(js[n]!==e[n]){t=!0;break}t&&(js.set(e),Xs=!0)}(o.viewProjection),Xs&&(xs(o.viewProjection,Hs),Xs=!1);const c=vs(a,l,Hs,o.vpX,o.vpY,o.vpW,o.vpH),h=t.getEntitiesWithComponents([Cs,us,V]);let u=null,d=-1/0;for(const e of h){t.has(e,Rs)||t.insert(e,Rs);if(!t.get(e,Cs).enabled)continue;const n=t.get(e,V),s=t.get(e,us),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(Ss(c.x,c.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y,n.rotation.z,n.rotation.w)){let n=0;t.has(e,q)&&(n=t.get(e,q).layer),n>=d&&(d=n,u=e)}}if(s!==u){if(null!==s&&t.valid(s)&&t.has(s,Rs)){t.get(s,Rs).hovered=!1,n.emit(s,"hover_exit")}if(null!==u){t.get(u,Rs).hovered=!0,n.emit(u,"hover_enter")}s=u}if(e.isMouseButtonPressed(0)&&null!==u){const e=t.get(u,Rs);e.pressed=!0,e.justPressed=!0,r=u,Ns(t,n,u,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Rs)){const e=t.get(r,Rs);e.pressed=!1,e.justReleased=!0,Ns(t,n,r,"release"),r===s&&Ns(t,n,r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Pe.Update,Te([],()=>{const e=t.getEntitiesWithComponents([Fs]);for(const n of e){if(t.has(n,Cs)||t.insert(n,Cs,{enabled:!0}),!t.has(n,Rs))continue;const e=t.get(n,Rs),s=t.get(n,Fs),r=t.get(n,Cs),o=s.state;if(r.enabled?e.pressed?s.state=As.Pressed:e.hovered?s.state=As.Hovered:s.state=As.Normal:s.state=As.Disabled,o!==s.state&&s.transition&&t.has(n,q)){const e=t.get(n,q),r=s.transition;switch(s.state){case As.Normal:e.color={...r.normalColor};break;case As.Hovered:e.color={...r.hoveredColor};break;case As.Pressed:e.color={...r.pressedColor};break;case As.Disabled:e.color={...r.disabledColor}}t.insert(n,q,e)}}},{name:"ButtonSystem"}))}}const qs=new Vs,Gs=I("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class Js{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){W("TextInput",Gs);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=u(_.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,h=0;const d=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!d)return;const f=d,p=()=>{a||null===i||x()},g=()=>{a=!0},m=()=>{a=!1,x()},y=t=>{if(null===i)return;if("Escape"===t.key)return void S();const s=n.get(i,Gs);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(ks).emit(i,"submit"),void S()}let r=s.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?r=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=s.value.length),r!==s.cursorPos&&(s.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,s.dirty=!0,P())},w=()=>{if(null!==i&&n.valid(i)&&n.has(i,Gs)){const e=n.get(i,Gs);e.focused=!1,e.dirty=!0}i=null};function x(){if(null===i||!n.valid(i))return;const t=n.get(i,Gs);if(t.readOnly)return;let s=f.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),f.value=s),s!==t.value){t.value=s;e.getResource(ks).emit(i,"change")}t.cursorPos=f.selectionStart??s.length,t.dirty=!0,P()}function b(e){if(i===e)return;S();const t=n.get(e,Gs);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),P())}function S(){if(null!==i&&n.valid(i)&&n.has(i,Gs)){const e=n.get(i,Gs);e.focused=!1,e.dirty=!0}i=null,f.blur()}function P(){l=!0,c=0}function M(e,i,a,c){(r.width<a||r.height<c)&&(r.width=Qs(Math.max(r.width,a)),r.height=Qs(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const h=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const u=0===i.value.length,d=u?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=u?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),g=i.padding;if(i.multiline){const e=Ks(o,d,a-2*g);let t=g;for(const n of e)o.fillText(n,g,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(d,g,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=Ks(o,i.value.substring(0,i.cursorPos),a-2*g),r=e.length>0?e[e.length-1]:"";t=g+o.measureText(r).width,n=g+(e.length-1)*p,s=p}else t=g+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const m=o.getImageData(0,0,a,c),y=new Uint8Array(m.data.buffer),_=t.getResourceManager(),w=t._malloc(y.length);t.HEAPU8.set(y,w);const x=s.get(e);void 0!==x&&_.releaseTexture(x);const v=_.createTexture(a,c,w,y.length,1,!0);s.set(e,v),t._free(w);const b=n.get(e,q);b.texture=v,b.size.x=a,b.size.y=c,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},n.insert(e,q,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",g),f.addEventListener("compositionend",m),f.addEventListener("keydown",y),f.addEventListener("blur",w),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",g),f.removeEventListener("compositionend",m),f.removeEventListener("keydown",y),f.removeEventListener("blur",w),f.remove()},e.addSystemToSchedule(Pe.PreUpdate,Te([de(ks)],e=>{const t=n.getEntitiesWithComponents([Gs,Cs]);for(const e of t){if(!n.has(e,Rs))continue;if(n.get(e,Rs).justPressed)return void b(e)}if(null!==i){const e=n.getEntitiesWithComponents([Cs]);for(const t of e){if(n.has(t,Gs))continue;if(!n.has(t,Rs))continue;if(n.get(t,Rs).justPressed)return void S()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Pe.PreUpdate,Te([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===h?0:(e-h)/1e3;if(h=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,Gs)))){n.get(i,Gs).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Gs)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([Gs,us]);for(const e of a){const t=n.get(e,Gs);if(!t.dirty)continue;const s=n.get(e,us),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,q)||n.insert(e,q,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),M(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Ks(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function Qs(e){let t=1;for(;t<e;)t*=2;return t}const Zs=new Js,er={Simple:0,Sliced:1,Tiled:2,Filled:3},tr={Horizontal:0,Vertical:1},nr={Left:0,Right:1,Bottom:2,Top:3},sr=I("Image",{texture:v,color:{r:1,g:1,b:1,a:1},imageType:er.Simple,fillMethod:tr.Horizontal,fillOrigin:nr.Left,fillAmount:1,preserveAspect:!1,layer:0,material:0,enabled:!0});const rr=new class{build(e){W("Image",sr);const t=e.world;e.addSystemToSchedule(Pe.PreUpdate,Te([],()=>{const e=t.getEntitiesWithComponents([sr]);for(const n of e){const e=t.get(n,sr);t.has(n,q)||t.insert(n,q,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const s=t.get(n,q);if(s.texture=e.texture,s.color.r=e.color.r,s.color.g=e.color.g,s.color.b=e.color.b,s.color.a=e.color.a,s.layer=e.layer,s.material=e.material,t.has(n,us)){const e=t.get(n,us);s.size.x=e.size.x,s.size.y=e.size.y}if(s.uvOffset.x=0,s.uvOffset.y=0,s.uvScale.x=1,s.uvScale.y=1,e.imageType===er.Filled){const t=Math.max(0,Math.min(1,e.fillAmount));e.fillMethod===tr.Horizontal?e.fillOrigin===nr.Left?(s.uvScale.x=t,s.size.x*=t):(s.uvOffset.x=1-t,s.uvScale.x=t,s.size.x*=t):e.fillOrigin===nr.Bottom?(s.uvScale.y=t,s.size.y*=t):(s.uvOffset.y=1-t,s.uvScale.y=t,s.size.y*=t)}t.insert(n,q,s)}},{name:"ImageSystem"}))}},or=I("Toggle",{isOn:!0,graphicEntity:0,transition:null,enabled:!0});const ir=new class{build(e){W("Toggle",or);const t=e.world;e.addSystemToSchedule(Pe.Update,Te([de(ks)],e=>{const n=t.getEntitiesWithComponents([or]);for(const s of n){if(t.has(s,Cs)||t.insert(s,Cs,{enabled:!0}),!t.has(s,Rs))continue;const n=t.get(s,Rs),r=t.get(s,or),o=t.get(s,Cs);if(n.justPressed&&o.enabled&&(r.isOn=!r.isOn,e.emit(s,"change")),r.graphicEntity&&t.valid(r.graphicEntity)){const e=r.graphicEntity;if(t.has(e,q)){const n=t.get(e,q);n.color.a=r.isOn?1:0,t.insert(e,q,n)}}if(r.transition&&t.has(s,q)){const e=t.get(s,q),i=r.transition;o.enabled?n.pressed?e.color={...i.pressedColor}:n.hovered?e.color={...i.hoveredColor}:e.color={...i.normalColor}:e.color={...i.disabledColor},t.insert(s,q,e)}}},{name:"ToggleSystem"}))}};var ar;!function(e){e[e.LeftToRight=0]="LeftToRight",e[e.RightToLeft=1]="RightToLeft",e[e.BottomToTop=2]="BottomToTop",e[e.TopToBottom=3]="TopToBottom"}(ar||(ar={}));const lr=I("ProgressBar",{value:0,fillEntity:0,direction:ar.LeftToRight});const cr=new class{build(e){W("ProgressBar",lr);const t=e.world;e.addSystemToSchedule(Pe.PreUpdate,Te([],()=>{const e=t.getEntitiesWithComponents([lr,us]);for(const n of e){const e=t.get(n,lr);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=e.fillEntity;if(!t.has(s,us))continue;const r=t.get(s,us),o=Math.max(0,Math.min(1,e.value));switch(e.direction){case ar.LeftToRight:r.anchorMin={x:0,y:0},r.anchorMax={x:o,y:1};break;case ar.RightToLeft:r.anchorMin={x:1-o,y:0},r.anchorMax={x:1,y:1};break;case ar.BottomToTop:r.anchorMin={x:0,y:0},r.anchorMax={x:1,y:o};break;case ar.TopToBottom:r.anchorMin={x:0,y:1-o},r.anchorMax={x:1,y:1}}r.offsetMin={x:0,y:0},r.offsetMax={x:0,y:0},t.insert(s,us,r)}},{name:"ProgressBarSystem"}))}},hr=I("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),ur=I("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}}),dr=new Float32Array(16),fr=new Float32Array(16);let pr=!0;function gr(e,t,n){const s=e.mouseX*n,r=t.screenH-e.mouseY*n;return function(e){let t=!1;for(let n=0;n<16;n++)if(fr[n]!==e[n]){t=!0;break}t&&(fr.set(e),pr=!0)}(t.viewProjection),pr&&(xs(t.viewProjection,dr),pr=!1),vs(s,r,dr,t.vpX,t.vpY,t.vpW,t.vpH)}const mr=new class{build(e){W("Draggable",hr),W("DragState",ur);const t=e.world,n=e.getResource(ks);let s=null,r={x:0,y:0},o=null;const i="undefined"!=typeof window&&window.devicePixelRatio||1;e.addSystemToSchedule(Pe.PreUpdate,Te([de(ke),de(Xe)],(e,a)=>{if(!a.valid)return;const l=gr(e,a,i);if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([hr,Rs]);let n=null;for(const s of e){if(!t.get(s,hr).enabled)continue;t.get(s,Rs).hovered&&(n=s)}if(null!==n){s=n,r={x:l.x,y:l.y},t.has(n,ur)||t.insert(n,ur);const e=t.get(n,ur),o=t.get(n,V);e.startWorldPos={x:o.position.x,y:o.position.y},e.currentWorldPos={x:o.position.x,y:o.position.y},e.pointerStartWorld={x:l.x,y:l.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,ur)){t.get(s,ur).isDragging=!1}s=null}if(null!==s&&null===o){if(!t.valid(s))return void(s=null);const e=l.x-r.x,i=l.y-r.y,c=Math.sqrt(e*e+i*i),h=t.get(s,hr);if(c*(a.vpW/(a.worldRight-a.worldLeft))>=h.dragThreshold){o=s,s=null;t.get(o,ur).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,ur))return void(o=null);const s=t.get(o,ur),r=t.get(o,hr),i=l.x-s.pointerStartWorld.x,a=l.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+i,h=s.startWorldPos.y+a;const u=function(e,t,n,s){let r=e.lockX?t.startWorldPos.x:n,o=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(r=Math.max(r,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(r=Math.min(r,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:r,y:o}}(r,s,c,h);c=u.x,h=u.y;const d=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-d,y:h-f},s.currentWorldPos={x:c,y:h},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:h-s.startWorldPos.y},t.has(o,N)){const e=function(e,t,n,s){if(!e.has(t,Q))return{x:n,y:s};const r=e.get(t,Q).entity;if(!e.valid(r)||!e.has(r,V))return{x:n,y:s};const o=e.get(r,V),i=0!==o.scale.x?o.scale.x:1,a=0!==o.scale.y?o.scale.y:1,l=2*Math.atan2(o.rotation.z,o.rotation.w),c=Math.sin(-l),h=Math.cos(-l);return{x:(n*h-s*c)/i,y:(n*c+s*h)/a}}(t,o,s.deltaWorld.x,s.deltaWorld.y),n=t.get(o,N);n.position.x+=e.x,n.position.y+=e.y,t.insert(o,N,n)}n.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},yr=I("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135});const _r=new class{build(e){W("ScrollView",yr);const t=e.world,n=new Map,s=new Float32Array(16),r="undefined"!=typeof window&&window.devicePixelRatio||1;let o=0;e.addSystemToSchedule(Pe.PreUpdate,Te([de(ke),de(Xe)],(e,i)=>{const a=performance.now()/1e3,l=o>0?Math.min(a-o,.05):0;if(o=a,!i.valid)return;const c=e.mouseX*r,h=i.screenH-e.mouseY*r;xs(i.viewProjection,s);const u=vs(c,h,s,i.vpX,i.vpY,i.vpW,i.vpH),d=t.getEntitiesWithComponents([yr,us]);for(const s of d){t.has(s,Cs)||t.insert(s,Cs,{enabled:!0,blockRaycast:!0}),t.has(s,ys)||t.insert(s,ys,{enabled:!0,mode:"scissor"});const r=t.get(s,yr),o=t.get(s,us);let i=n.get(s);i||(i={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0},n.set(s,i));const a=t.has(s,Rs)?t.get(s,Rs):null;if(a?.justPressed&&(i.isDragging=!0,i.lastWorldX=u.x,i.lastWorldY=u.y,i.velocityX=0,i.velocityY=0),i.isDragging&&e.isMouseButtonDown(0)){const e=u.x-i.lastWorldX,t=u.y-i.lastWorldY;r.horizontalEnabled&&(r.scrollX-=e,i.velocityX=l>0?-e/l:0),r.verticalEnabled&&(r.scrollY-=t,i.velocityY=l>0?-t/l:0),i.lastWorldX=u.x,i.lastWorldY=u.y}if(i.isDragging&&e.isMouseButtonReleased(0)&&(i.isDragging=!1),a?.hovered){const t=e.getScrollDelta();r.verticalEnabled&&0!==t.y&&(r.scrollY+=.1*t.y,i.velocityY=0),r.horizontalEnabled&&0!==t.x&&(r.scrollX+=.1*t.x,i.velocityX=0)}if(!i.isDragging&&r.inertia&&l>0){const e=Math.pow(r.decelerationRate,l);r.horizontalEnabled&&Math.abs(i.velocityX)>.1?(r.scrollX+=i.velocityX*l,i.velocityX*=e):i.velocityX=0,r.verticalEnabled&&Math.abs(i.velocityY)>.1?(r.scrollY+=i.velocityY*l,i.velocityY*=e):i.velocityY=0}const c=o.size.x,h=o.size.y,d=Math.max(0,r.contentWidth-c),f=Math.max(0,r.contentHeight-h);if(r.scrollX=Math.max(0,Math.min(r.scrollX,d)),r.scrollY=Math.max(0,Math.min(r.scrollY,f)),0!==r.contentEntity&&t.valid(r.contentEntity)){const e=r.contentEntity;if(t.has(e,N)){const n=t.get(e,N);n.position.x=-r.scrollX,n.position.y=r.scrollY,t.insert(e,N,n)}}}},{name:"ScrollViewSystem"}))}};var wr;!function(e){e[e.LeftToRight=0]="LeftToRight",e[e.RightToLeft=1]="RightToLeft",e[e.BottomToTop=2]="BottomToTop",e[e.TopToBottom=3]="TopToBottom"}(wr||(wr={}));const xr=I("Slider",{value:0,minValue:0,maxValue:1,direction:wr.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1,enabled:!0});const vr=new class{build(e){W("Slider",xr);const t=e.world,n=new Float32Array(16),s="undefined"!=typeof window&&window.devicePixelRatio||1;let r=null;e.addSystemToSchedule(Pe.PreUpdate,Te([de(ke),de(Xe)],(e,o)=>{if(!o.valid)return;const i=e.mouseX*s,a=o.screenH-e.mouseY*s;xs(o.viewProjection,n);const l=vs(i,a,n,o.vpX,o.vpY,o.vpW,o.vpH),c=t.getEntitiesWithComponents([xr,us,V]);for(const n of c){t.has(n,Cs)||t.insert(n,Cs,{enabled:!0,blockRaycast:!0});const s=t.get(n,xr),o=t.get(n,us),i=t.get(n,V),a=t.has(n,Rs)?t.get(n,Rs):null;if(a?.justPressed&&(r=n),r===n&&e.isMouseButtonDown(0)){const e=o.size.x*i.scale.x,t=o.size.y*i.scale.y,n=i.position.x-o.pivot.x*e,r=i.position.y-o.pivot.y*t;let a;switch(s.direction){case wr.LeftToRight:a=e>0?(l.x-n)/e:0;break;case wr.RightToLeft:a=e>0?1-(l.x-n)/e:0;break;case wr.BottomToTop:a=t>0?(l.y-r)/t:0;break;case wr.TopToBottom:a=t>0?1-(l.y-r)/t:0}a=Math.max(0,Math.min(1,a));let c=s.minValue+a*(s.maxValue-s.minValue);s.wholeNumbers&&(c=Math.round(c)),s.value=Math.max(s.minValue,Math.min(s.maxValue,c))}r===n&&e.isMouseButtonReleased(0)&&(r=null);const c=s.maxValue-s.minValue,h=c>0?(s.value-s.minValue)/c:0;if(0!==s.fillEntity&&t.valid(s.fillEntity)){const e=s.fillEntity;if(t.has(e,us)){const n=t.get(e,us);switch(s.direction){case wr.LeftToRight:n.anchorMin={x:0,y:0},n.anchorMax={x:h,y:1};break;case wr.RightToLeft:n.anchorMin={x:1-h,y:0},n.anchorMax={x:1,y:1};break;case wr.BottomToTop:n.anchorMin={x:0,y:0},n.anchorMax={x:1,y:h};break;case wr.TopToBottom:n.anchorMin={x:0,y:1-h},n.anchorMax={x:1,y:1}}t.insert(e,us,n)}}if(0!==s.handleEntity&&t.valid(s.handleEntity)){const e=s.handleEntity;if(t.has(e,us)){const n=t.get(e,us);switch(s.direction){case wr.LeftToRight:n.anchorMin={x:h,y:0},n.anchorMax={x:h,y:1};break;case wr.RightToLeft:n.anchorMin={x:1-h,y:0},n.anchorMax={x:1-h,y:1};break;case wr.BottomToTop:n.anchorMin={x:0,y:h},n.anchorMax={x:1,y:h};break;case wr.TopToBottom:n.anchorMin={x:0,y:1-h},n.anchorMax={x:1,y:1-h}}t.insert(e,us,n)}}}},{name:"SliderSystem"}))}},br=I("Focusable",{tabIndex:0,isFocused:!1});class Sr{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Pr=ue(new Sr,"FocusManager");const Mr=new class{build(e){W("Focusable",br);const t=e.world,n=new Sr;e.insertResource(Pr,n),e.addSystemToSchedule(Pe.Update,Te([de(ke),de(ks)],(e,s)=>{const r=t.getEntitiesWithComponents([br]);for(const e of r){if(!t.has(e,Rs))continue;t.get(e,Rs).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of r){const s=t.get(n,br);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const i=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===i?a?s.length-1:0:a?(i-1+s.length)%s.length:(i+1)%s.length,o(s[l])}function o(e){const r=n.focusedEntity;if(r===e)return;if(null!==r&&t.valid(r)&&t.has(r,br)){t.get(r,br).isFocused=!1,s.emit(r,"hover_exit",r)}n.focus(e);t.get(e,br).isFocused=!0,s.emit(e,"hover_enter",e)}},{name:"FocusSystem"}))}},Tr=I("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});const Er=new class{build(e){W("SafeArea",Tr);const t=e.world;let n={top:0,bottom:0,left:0,right:0},s=0;e.addSystemToSchedule(Pe.PreUpdate,Te([],()=>{s++%60==0&&(n=function(){if("undefined"==typeof document)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}());const e=t.getEntitiesWithComponents([Tr,us]);for(const s of e){const e=t.get(s,Tr),r=t.get(s,us);let o=!1;const i=e.applyTop?n.top:0,a=e.applyBottom?n.bottom:0,l=e.applyLeft?n.left:0,c=e.applyRight?n.right:0;r.offsetMin.x===l&&r.offsetMin.y===a||(r.offsetMin={x:l,y:a},o=!0),r.offsetMax.x===-c&&r.offsetMax.y===-i||(r.offsetMax={x:-c,y:-i},o=!0),o&&t.insert(s,us,r)}},{name:"SafeAreaSystem"}))}},Cr=I("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2}),Rr=new Map;function Ar(e,t){const n=Rr.get(e);n&&(n.renderer=t)}const Fr=new class{build(e){W("ListView",Cr);const t=e.world;e.addSystemToSchedule(Pe.PreUpdate,Te([de(ke)],e=>{const n=t.getEntitiesWithComponents([Cr,us]);for(const s of n){t.has(s,Cs)||t.insert(s,Cs,{enabled:!0,blockRaycast:!0}),t.has(s,ys)||t.insert(s,ys,{enabled:!0,mode:"scissor"});let n=Rr.get(s);n||(n={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},Rr.set(s,n));const r=t.get(s,Cr),o=t.get(s,us),i=o.size.y,a=t.has(s,Rs)?t.get(s,Rs):null;if(a?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}const l=Math.max(0,r.itemCount*r.itemHeight-i);r.scrollY=Math.max(0,Math.min(r.scrollY,l));const c=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),h=Math.min(r.itemCount,Math.ceil((r.scrollY+i)/r.itemHeight)+r.overscan);for(const[e,s]of n.itemEntities)(e<c||e>=h)&&(t.valid(s)&&t.despawn(s),n.itemEntities.delete(e));for(let e=c;e<h;e++){let i=n.itemEntities.get(e);if(i&&t.valid(i)||(i=t.spawn(),t.insert(i,ne,{value:`ListItem_${e}`}),t.insert(i,us,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o.size.x,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(i,s),n.itemEntities.set(e,i),n.renderer&&n.renderer(e,i)),t.has(i,N)){const n=t.get(i,N);n.position.y=-(e*r.itemHeight-r.scrollY),t.insert(i,N,n)}}n.visibleStart=c,n.visibleEnd=h}},{name:"ListViewSystem"}))}},Ir=I("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const kr=new class{build(e){W("Dropdown",Ir);const t=e.world;e.addSystemToSchedule(Pe.Update,Te([de(ke),de(ks)],(e,n)=>{const s=t.getEntitiesWithComponents([Ir]);for(const o of s){t.has(o,Cs)||t.insert(o,Cs,{enabled:!0,blockRaycast:!0});const s=t.get(o,Ir),i=t.has(o,Rs)?t.get(o,Rs):null;if(i?.justPressed&&(s.isOpen=!s.isOpen,r(s.listEntity,s.isOpen),n.emit(o,"change",o)),s.isOpen&&e.isMouseButtonPressed(0)&&!i?.hovered){0!==s.listEntity&&t.valid(s.listEntity)&&t.has(s.listEntity,Rs)&&t.get(s.listEntity,Rs).hovered||(s.isOpen=!1,r(s.listEntity,!1))}}function r(e,n){if(0===e)return;const s=e;if(!t.valid(s)||!t.has(s,N))return;const r=t.get(s,N),o=n?1:0;r.scale={x:o,y:o,z:o},t.insert(s,N,r)}},{name:"DropdownSystem"}))}};async function Br(e,t,n){const s=e.getResource(Xn);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function $r(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const Dr=ue({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Ur=ue(null,"PhysicsAPI");function zr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Lr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Wr{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Dr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=$r(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([J]);for(const n of t){const t=e.world.get(n,J);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(Pe.PostUpdate,Te([de(me)],a=>{const l=i.getEntitiesWithComponents([oe,N,V]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,oe),l=i.get(r,V);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=zr(l.rotation);s._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Or(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===ce.Kinematic){const e=zr(l.rotation);s._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const h=e.world.get(i,N);if(!h)continue;let u=a,d=l,f=c;if(e.world.has(i,Q)){const t=e.world.get(i,Q);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,V)){const n=e.world.get(t.entity,V),s=zr(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),h=Math.sin(-s);u=(r*i-o*h)/(0!==n.scale.x?n.scale.x:1),d=(r*h+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}h.position.x=u,h.position.y=d;const p=Lr(f);h.rotation.w=p.w,h.rotation.x=p.x,h.rotation.y=p.y,h.rotation.z=p.z,e.world.insert(i,N,h)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],h=t._physics_getSensorExitCount();if(h>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<h;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Dr,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(Ur,Hr._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function Or(e,t,n){const s=e.world;if(s.has(n,ie)){const e=s.get(n,ie);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,ae)){const e=s.get(n,ae);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,le)){const e=s.get(n,le);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Hr{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(Hr.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function jr(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function Xr(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function Yr(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,h=e.rotation.w,u=a+a,d=l+l,f=c+c,p=a*u,g=a*d,m=a*f,y=l*d,_=l*f,w=c*f,x=h*u,v=h*d,b=h*f;return new Float32Array([(1-(y+w))*r,(g+b)*r,(m-v)*r,0,(g-b)*o,(1-(p+w))*o,(_+x)*o,0,(m+v)*i,(_-x)*i,(1-(p+y))*i,0,e.position.x,e.position.y,e.position.z,1])}async function Nr(e,t,n,s,r,o,i,a,l){const c=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=jr(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,c);let h={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),h=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=await r.readText(a),h="binary"===Mt(l)?.contentType;let u,d;if(h){const e=await r.readBinary(i);d=e.length,u=t._malloc(d),t.HEAPU8.set(e,u)}else{const e=await r.readText(i),n=(new TextEncoder).encode(e);d=n.length,u=t._malloc(d+1),t.HEAPU8.set(n,u),t.HEAPU8[u+d]=0}const f=n.loadSkeleton(u,d,s,s.length,h);if(t._free(u),f<0)continue;o[i]=f;const p=Xr(s),g=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=g+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=jr(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,n,s)),o){new Wr("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;const i=Mt(r);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[r]=0;continue}const l=o?`${o}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),h=jr(e,c,!1),u=e.getResourceManager();s[r]=u.loadBitmapFont(t,h,c.width,c.height)}catch{s[r]=0}}return s}(t,n,s),f=await async function(e,t){const n={},s={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===n[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=et.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=et.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s);!function(e,t,n,s){const r={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=pt(e.type);if(0===t.length)continue;const n=e.data;for(const e of t)"string"==typeof n[e.field]&&(n[e.field]=r[e.type][n[e.field]]||0)}}(n,c,d,f);const p=gt(e.world,n);if(l&&e.hasResource(Xn))for(const t of p.values())e.world.insert(t,se,{scene:l,persistent:!1});if(r&&u){const s=function(e,t,n,s){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,n,h,p);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,te)?c.get(o,te):null,h=!1!==a?.playing,u=a?.timeScale??1;h&&s.update(i,l*u);let d=0;if(c.has(o,V)){const e=Yr(c.get(o,V),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),h=n._malloc(l),u=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,h,u,f);const p=n.HEAPU32[u>>2],g=n.HEAPU32[f>>2],m=new Float32Array(n.HEAPF32.buffer,c,8*r),y=new Uint16Array(n.HEAPU8.buffer,h,o),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(m,_>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(y),t.renderer_submitTriangles(_,r,w,o,p,g,d),t._free(_),t._free(w),n._free(c),n._free(h),n._free(u),n._free(f)}d&&t._free(d)}})}(e,t,r,u,s)}if(a){const t=e.getResource(Ut);t&&t.setAddressableManifest(a)}}function Vr(e,t,n){return{name:e,data:t,async setup(){await Nr(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class qr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&("binary"===Mt(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of s){const t=Mt(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Gr="__preview__";class Jr{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(Xn);t.register({name:Gr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Gr),this.loadPromise_=t.load(Gr).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new qr(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.spineInitPromise;if(r){s=(await r).controller.raw}await Nr(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,Gr)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([G]);for(const s of n){if(e.get(s,G).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([J]);for(const r of s){const s=e.get(r,J);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=this.app_.getResource(Xn).getScene(Gr),o=r?r.spawn():e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(o,N,i);const a={isActive:!0,projectionType:j.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:X.ColorAndDepth};e.insert(o,G,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(Xn);await e.switchTo(Gr),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}}const Kr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Bn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Bn.getTargetTexture(n),width:e.width,height:e.height}},release(e){Bn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Bn.releaseRenderTarget(e._handle),Kr.create({width:t,height:n,depth:!0})),begin(e,t){Bn.begin(t,e._handle)},end(){Bn.end()},getDepthTexture:e=>Bn.getTargetDepthTexture(e._handle)};let Qr=!1;function Zr(e){Qr=e}function eo(){return Qr}function to(){return!Qr}var no;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(no||(no={}));class so{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${no[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case no.Debug:console.debug(t,n);break;case no.Info:console.log(t,n);break;case no.Warn:console.warn(t,n);break;case no.Error:console.error(t,n)}}}class ro{constructor(){this.handlers_=[],this.minLevel_=no.Info,this.addHandler(new so)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log(no.Debug,e,t,n)}info(e,t,n){this.log(no.Info,e,t,n)}warn(e,t,n){this.log(no.Warn,e,t,n)}error(e,t,n){this.log(no.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const oo=new ro;function io(){return oo}function ao(e){oo.setMinLevel(e)}function lo(e,t,n){oo.debug(e,t,n)}function co(e,t,n){oo.info(e,t,n)}function ho(e,t,n){oo.warn(e,t,n)}function uo(e,t,n){oo.error(e,t,n)}const fo=[ms,Es,Os,rr,cr,qs,mr,_r,vr,ir,Zs,Mr,Er,Fr,kr];function po(e,t){return function(e,t){const n=qn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),tn(e),Ke(e),wn(e),Pn(e),In(e),Dn(e);const r=new Ln;n.setPipeline(r);let o=d();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,o){o||(o=Qn(e,s,t,r));const i=n.getResource(Xe);if(o.length>0){const e=o[0],n=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(n.x*t),i.vpY=Math.round((1-n.y-n.h)*r),i.vpW=Math.round(n.w*t),i.vpH=Math.round(n.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}n.insertResource(Xe,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=i();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;Bn.setClearColor(e.x,e.y,e.z,e.w)}const h=(d()-o)/1e3;let u;if(Bn.resize(t,l),En.isInitialized()&&En.getPassCount()>0&&!En.isBypassed()&&En.resize(t,l),n.hasResource(Xn)){const e=n.getResource(Xn).getActiveScenes();e.length>0&&(u=new Set(e))}r.setActiveScenes(u??null);const f=Qn(e,s,t,l,n.world,u);if(a(t,l,f),0===f.length)r.render({registry:{_cpp:s},viewProjection:Jn,width:t,height:l,elapsed:h});else{for(const e of f){const n=e.viewportRect,o=Math.round(n.x*t),i=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:c},clearFlags:e.clearFlags,elapsed:h})}Bn.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(Pe.First,l),n.addSystemToSchedule(Pe.Last,c),n.addPlugin(Lt),n.addPlugin(Gt),n.addPlugin($e),n.addPlugin(Vn),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:fo,...t})}e=f;export{qn as App,zt as AssetPlugin,Wt as AssetRefCounter,Dt as AssetServer,Ut as Assets,ct as AsyncCache,ee as BitmapText,Ye as BlendMode,ce as BodyType,ie as BoxCollider,Fs as Button,As as ButtonState,G as Camera,J as Canvas,le as CapsuleCollider,Z as Children,ae as CircleCollider,X as ClearFlags,ve as Commands,Se as CommandsInstance,g as DEFAULT_DESIGN_HEIGHT,p as DEFAULT_DESIGN_WIDTH,m as DEFAULT_PIXELS_PER_UNIT,y as DEFAULT_TEXT_CANVAS_SIZE,pn as DataType,ur as DragState,hr as Draggable,on as Draw,Ir as Dropdown,be as EntityCommands,tr as FillMethod,nr as FillOrigin,Pr as FocusManager,Sr as FocusManagerState,br as Focusable,zn as GLDebug,bn as Geometry,x as INVALID_ENTITY,b as INVALID_FONT,v as INVALID_TEXTURE,sr as Image,er as ImageType,ke as Input,Be as InputPlugin,Ie as InputState,Cs as Interactable,Cr as ListView,N as LocalTransform,no as LogLevel,ro as Logger,et as Material,ht as MaterialLoader,ye as Mut,ne as Name,Q as Parent,Hr as Physics,Dr as PhysicsEvents,Wr as PhysicsPlugin,En as PostProcess,Nt as PrefabServer,Vt as Prefabs,qt as PrefabsPlugin,Jr as PreviewPlugin,lr as ProgressBar,ar as ProgressBarDirection,j as ProjectionType,we as Query,xe as QueryInstance,Ln as RenderPipeline,Rn as RenderStage,Kr as RenderTexture,Bn as Renderer,de as Res,fe as ResMut,oe as RigidBody,_ as RuntimeConfig,Tr as SafeArea,Y as ScaleMode,Xn as SceneManager,jn as SceneManagerState,se as SceneOwner,Pe as Schedule,Bs as ScreenSpace,yr as ScrollView,lt as ShaderSources,xr as Slider,wr as SliderDirection,te as SpineAnimation,q as Sprite,Fe as SystemRunner,hs as Text,as as TextAlign,Gs as TextInput,Js as TextInputPlugin,cs as TextOverflow,gs as TextPlugin,ds as TextRenderer,ls as TextVerticalAlign,me as Time,or as Toggle,Xe as UICameraInfo,Is as UIEventQueue,ks as UIEvents,Rs as UIInteraction,Vs as UIInteractionPlugin,Ws as UILayoutPlugin,ys as UIMask,Ts as UIMaskPlugin,us as UIRect,K as Velocity,qr as WebAssetProvider,je as World,V as WorldTransform,Re as addStartupSystem,Ce as addSystem,Ae as addSystemToSchedule,w as applyRuntimeConfig,Lt as assetPlugin,fn as clearDrawCallbacks,$ as clearUserComponents,T as color,$s as computeUIRectLayout,Ms as createMaskProcessor,Vr as createRuntimeSceneConfig,po as createWebApp,lo as debug,I as defineComponent,ue as defineResource,Te as defineSystem,k as defineTag,uo as error,wt as findEntityByName,Gn as flushPendingSystems,Et as getAddressableType,Ct as getAddressableTypeByEditorType,At as getAllAssetExtensions,Bt as getAssetMimeType,Mt as getAssetTypeEntry,O as getComponent,ft as getComponentAssetFields,re as getComponentDefaults,It as getCustomExtensions,Tt as getEditorType,io as getLogger,t as getPlatform,s as getPlatformType,B as getUserComponent,kt as getWeChatPackOptions,co as info,tn as initDrawAPI,Dn as initGLDebugAPI,wn as initGeometryAPI,Ke as initMaterialAPI,Pn as initPostProcessAPI,In as initRendererAPI,$e as inputPlugin,Ht as instantiatePrefab,_s as intersectRects,xs as invertMatrix4,z as isBuiltinComponent,$t as isCustomExtension,eo as isEditor,Rt as isKnownAssetExtension,n as isPlatformInitialized,to as isRuntime,Ne as isTextureRef,r as isWeChat,o as isWeb,yt as loadComponent,$r as loadPhysicsModule,Nr as loadRuntimeScene,gt as loadSceneData,mt as loadSceneWithAssets,Ft as looksLikeAssetPath,i as platformFetch,c as platformFileExists,h as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Ss as pointInOBB,bs as pointInWorldRect,Gt as prefabsPlugin,E as quat,W as registerComponent,dt as registerComponentAssetFields,un as registerDrawCallback,Ot as registerEmbeddedAssets,at as registerMaterialCallback,Vn as sceneManagerPlugin,vs as screenToWorld,Zr as setEditorMode,Ar as setListViewRenderer,ao as setLogLevel,We as setWasmErrorHandler,nn as shutdownDrawAPI,Un as shutdownGLDebugAPI,xn as shutdownGeometryAPI,Qe as shutdownMaterialAPI,Mn as shutdownPostProcessAPI,kn as shutdownRendererAPI,Zs as textInputPlugin,ms as textPlugin,Br as transitionTo,qs as uiInteractionPlugin,Os as uiLayoutPlugin,Es as uiMaskPlugin,fo as uiPlugins,D as unregisterComponent,dn as unregisterDrawCallback,_t as updateCameraAspectRatio,S as vec2,P as vec3,M as vec4,ho as warn,ws as worldRectToScreen,Yn as wrapSceneSystem};
//# 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 647751133..53b0cf001 100644
--- a/desktop/public/sdk/esm/physics/index.d.ts
+++ b/desktop/public/sdk/esm/physics/index.d.ts
@@ -59,6 +59,7 @@ interface BoxColliderData {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
interface CircleColliderData {
radius: number;
@@ -67,6 +68,7 @@ interface CircleColliderData {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
interface CapsuleColliderData {
radius: number;
@@ -76,6 +78,7 @@ interface CapsuleColliderData {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
declare const RigidBody$1: BuiltinComponentDef<RigidBodyData>;
declare const BoxCollider$1: BuiltinComponentDef<BoxColliderData>;
@@ -127,6 +130,7 @@ interface BoxCollider {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
interface CircleCollider {
radius: number;
@@ -135,6 +139,7 @@ interface CircleCollider {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
interface CapsuleCollider {
radius: number;
@@ -144,6 +149,7 @@ interface CapsuleCollider {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
interface LocalTransform {
position: Vec3;
@@ -173,6 +179,7 @@ interface SpineAnimation {
layer: number;
skeletonScale: number;
material: number;
+ enabled: boolean;
}
interface RigidBody {
bodyType: number;
@@ -191,6 +198,7 @@ interface BitmapText {
spacing: number;
layer: number;
font: number;
+ enabled: boolean;
}
interface Sprite {
texture: number;
@@ -202,6 +210,7 @@ interface Sprite {
flipX: boolean;
flipY: boolean;
material: number;
+ enabled: boolean;
}
interface Parent {
entity: number;
diff --git a/desktop/public/sdk/esm/physics/index.js b/desktop/public/sdk/esm/physics/index.js
index d30f2ab31..d063d0ca9 100644
--- a/desktop/public/sdk/esm/physics/index.js
+++ b/desktop/public/sdk/esm/physics/index.js
@@ -1,2 +1,2 @@
-function e(t){if(null===t||"object"!=typeof t)return t;if(Array.isArray(t))return t.map(e);const n={};for(const i in t)n[i]=e(t[i]);return n}let t=0;const n=new Map;function i(e,t){const i={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return n.set(e,i),i}const s=i("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),o=i("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}});i("Sprite",{texture:4294967295,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),i("Camera",{projectionType:1,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3});const r=i("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}});i("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}});const a=i("Parent",{entity:0});i("Children",{entities:[]}),i("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:4294967295}),i("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0});const l={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};var c,u;!function(n,i){const s="undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map),o=s.get(n);if(o)return o;const r=function(n,i){const s=++t;return{_id:Symbol(`Component_${s}_${n}`),_name:n,_default:i,_builtin:!1,create:t=>t?{...e(i),...t}:e(i)}}(n,i);s.set(n,r),function(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}(n,i,!1)}("SceneOwner",{scene:"",persistent:!1}),c="Name",u=l,n.set(c,u);let y=0;function p(e,t){const n=++y;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}const _=p({delta:0,elapsed:0,frameCount:0},"Time");var m;!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(m||(m={}));let d=0;async function h(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}async function f(e,t){await t.loadDynamicLibrary(new Uint8Array(e),{loadAsync:!0,allowUndefined:!0});const n=t.cwrap.bind(t);return{_physics_init:n("physics_init",null,["number","number","number","number"]),_physics_shutdown:n("physics_shutdown",null,[]),_physics_createBody:n("physics_createBody",null,["number","number","number","number","number","number","number","number","number","number"]),_physics_destroyBody:n("physics_destroyBody",null,["number"]),_physics_hasBody:n("physics_hasBody","number",["number"]),_physics_addBoxShape:n("physics_addBoxShape",null,["number","number","number","number","number","number","number","number","number"]),_physics_addCircleShape:n("physics_addCircleShape",null,["number","number","number","number","number","number","number","number"]),_physics_addCapsuleShape:n("physics_addCapsuleShape",null,["number","number","number","number","number","number","number","number","number"]),_physics_step:n("physics_step",null,["number"]),_physics_setBodyTransform:n("physics_setBodyTransform",null,["number","number","number","number"]),_physics_getDynamicBodyCount:n("physics_getDynamicBodyCount","number",[]),_physics_getDynamicBodyTransforms:n("physics_getDynamicBodyTransforms","number",[]),_physics_collectEvents:n("physics_collectEvents",null,[]),_physics_getCollisionEnterCount:n("physics_getCollisionEnterCount","number",[]),_physics_getCollisionEnterBuffer:n("physics_getCollisionEnterBuffer","number",[]),_physics_getCollisionExitCount:n("physics_getCollisionExitCount","number",[]),_physics_getCollisionExitBuffer:n("physics_getCollisionExitBuffer","number",[]),_physics_getSensorEnterCount:n("physics_getSensorEnterCount","number",[]),_physics_getSensorEnterBuffer:n("physics_getSensorEnterBuffer","number",[]),_physics_getSensorExitCount:n("physics_getSensorExitCount","number",[]),_physics_getSensorExitBuffer:n("physics_getSensorExitBuffer","number",[]),_physics_applyForce:n("physics_applyForce",null,["number","number","number"]),_physics_applyImpulse:n("physics_applyImpulse",null,["number","number","number"]),_physics_setLinearVelocity:n("physics_setLinearVelocity",null,["number","number","number"]),_physics_getLinearVelocity:n("physics_getLinearVelocity","number",["number"]),_physics_setGravity:n("physics_setGravity",null,["number","number"]),_physics_getGravity:n("physics_getGravity","number",[]),_physics_setAngularVelocity:n("physics_setAngularVelocity",null,["number","number"]),_physics_getAngularVelocity:n("physics_getAngularVelocity","number",["number"]),_physics_applyTorque:n("physics_applyTorque",null,["number","number"]),_physics_applyAngularImpulse:n("physics_applyAngularImpulse",null,["number","number"]),_physics_updateBodyProperties:n("physics_updateBodyProperties",null,["number","number","number","number","number","number","number"]),get HEAPF32(){return t.HEAPF32},get HEAPU8(){return t.HEAPU8},get HEAPU32(){return t.HEAPU32},_malloc:t._malloc.bind(t),_free:t._free.bind(t)}}const g=i("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),b=i("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),x=i("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),E=i("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),S={Static:0,Kinematic:1,Dynamic:2},P=p({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),w=p(null,"PhysicsAPI");function C(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function A(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class v{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(P,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,i=h(this.wasmUrl_,this.factory_).then(i=>{i._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const l=function(e){const t=e.world.getEntitiesWithComponents([r]);for(const n of t){const t=e.world.get(n,r);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),c=1/l,u=e.world;var y;e.addSystemToSchedule(m.PostUpdate,function(e,t,n){const i=++d;return{_id:Symbol(`System_${i}_${n?.name}`),_params:e,_fn:t,_name:n?.name??`System_${i}`}}([(y=_,{_type:"res",_resource:y})],r=>{const y=u.getEntitiesWithComponents([g,s,o]),p=new Set;for(const s of y){p.add(s);const r=u.get(s,g),a=u.get(s,o);if(t.has(s)){const e=n.get(s);!e||e.bodyType===r.bodyType&&e.gravityScale===r.gravityScale&&e.linearDamping===r.linearDamping&&e.angularDamping===r.angularDamping&&e.fixedRotation===r.fixedRotation&&e.bullet===r.bullet||(i._physics_updateBodyProperties(s,r.bodyType,r.gravityScale,r.linearDamping,r.angularDamping,r.fixedRotation?1:0,r.bullet?1:0),e.bodyType=r.bodyType,e.gravityScale=r.gravityScale,e.linearDamping=r.linearDamping,e.angularDamping=r.angularDamping,e.fixedRotation=r.fixedRotation,e.bullet=r.bullet)}else{if(!r.enabled)continue;const o=C(a.rotation);i._physics_createBody(s,r.bodyType,a.position.x*c,a.position.y*c,o,r.gravityScale,r.linearDamping,r.angularDamping,r.fixedRotation?1:0,r.bullet?1:0),B(e,i,s),t.add(s),n.set(s,{bodyType:r.bodyType,gravityScale:r.gravityScale,linearDamping:r.linearDamping,angularDamping:r.angularDamping,fixedRotation:r.fixedRotation,bullet:r.bullet})}if(r.bodyType===S.Kinematic){const e=C(a.rotation);i._physics_setBodyTransform(s,a.position.x*c,a.position.y*c,e)}}for(const e of t)p.has(e)||(i._physics_destroyBody(e),t.delete(e),n.delete(e));i._physics_step(r.delta),function(e,t,n){const i=t._physics_getDynamicBodyCount();if(0===i)return;const r=t._physics_getDynamicBodyTransforms(),l=r>>2;for(let r=0;r<i;r++){const i=l+4*r,c=t.HEAPU32[i],u=t.HEAPF32[i+1]*n,y=t.HEAPF32[i+2]*n,p=t.HEAPF32[i+3];if(!e.world.valid(c))continue;const _=e.world.get(c,s);if(!_)continue;let m=u,d=y,h=p;if(e.world.has(c,a)){const t=e.world.get(c,a);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,o)){const n=e.world.get(t.entity,o),i=C(n.rotation),s=u-n.position.x,r=y-n.position.y,a=Math.cos(-i),l=Math.sin(-i);m=(s*a-r*l)/(0!==n.scale.x?n.scale.x:1),d=(s*l+r*a)/(0!==n.scale.y?n.scale.y:1),h=p-i}}_.position.x=m,_.position.y=d;const f=A(h);_.rotation.w=f.w,_.rotation.x=f.x,_.rotation.y=f.y,_.rotation.z=f.z,e.world.insert(c,s,_)}}(e,i,l),function(e,t,n){t._physics_collectEvents();const i=[],s=t._physics_getCollisionEnterCount();if(s>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<s;o++){const s=e+6*o;i.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1],normalX:t.HEAPF32[s+2],normalY:t.HEAPF32[s+3],contactX:t.HEAPF32[s+4]*n,contactY:t.HEAPF32[s+5]*n})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<r;n++){const i=e+2*n;o.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const i=e+2*n;a.push({sensorEntity:t.HEAPU32[i],visitorEntity:t.HEAPU32[i+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const i=e+2*n;c.push({sensorEntity:t.HEAPU32[i],visitorEntity:t.HEAPU32[i+1]})}}e.insertResource(P,{collisionEnters:i,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,i,l)},{name:"PhysicsSystem"})),e.physicsModule=i,e.insertResource(w,U._fromModule(i)),e.setFixedTimestep(this.config_.fixedTimestep)});i.catch(()=>{}),e.physicsInitPromise=i}}function B(e,t,n){const i=e.world;if(i.has(n,b)){const e=i.get(n,b);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(i.has(n,x)){const e=i.get(n,x);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(i.has(n,E)){const e=i.get(n,E);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class U{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(U.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}export{S as BodyType,b as BoxCollider,E as CapsuleCollider,x as CircleCollider,U as Physics,w as PhysicsAPI,P as PhysicsEvents,v as PhysicsPlugin,g as RigidBody,h as loadPhysicsModule,f as loadPhysicsSideModule};
+function e(t){if(null===t||"object"!=typeof t)return t;if(Array.isArray(t))return t.map(e);const n={};for(const i in t)n[i]=e(t[i]);return n}let t=0;const n=new Map;function i(e,t){const i={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return n.set(e,i),i}const s=i("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),o=i("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}});i("Sprite",{texture:4294967295,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),i("Camera",{projectionType:1,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3});const r=i("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}});i("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}});const a=i("Parent",{entity:0});i("Children",{entities:[]}),i("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:4294967295,enabled:!0}),i("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0});const l={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};var c,u;!function(n,i){const s="undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map),o=s.get(n);if(o)return o;const r=function(n,i){const s=++t;return{_id:Symbol(`Component_${s}_${n}`),_name:n,_default:i,_builtin:!1,create:t=>t?{...e(i),...t}:e(i)}}(n,i);s.set(n,r),function(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}(n,i,!1)}("SceneOwner",{scene:"",persistent:!1}),c="Name",u=l,n.set(c,u);let y=0;function p(e,t){const n=++y;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}const _=p({delta:0,elapsed:0,frameCount:0},"Time");var m;!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(m||(m={}));let d=0;async function h(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}async function f(e,t){await t.loadDynamicLibrary(new Uint8Array(e),{loadAsync:!0,allowUndefined:!0});const n=t.cwrap.bind(t);return{_physics_init:n("physics_init",null,["number","number","number","number"]),_physics_shutdown:n("physics_shutdown",null,[]),_physics_createBody:n("physics_createBody",null,["number","number","number","number","number","number","number","number","number","number"]),_physics_destroyBody:n("physics_destroyBody",null,["number"]),_physics_hasBody:n("physics_hasBody","number",["number"]),_physics_addBoxShape:n("physics_addBoxShape",null,["number","number","number","number","number","number","number","number","number"]),_physics_addCircleShape:n("physics_addCircleShape",null,["number","number","number","number","number","number","number","number"]),_physics_addCapsuleShape:n("physics_addCapsuleShape",null,["number","number","number","number","number","number","number","number","number"]),_physics_step:n("physics_step",null,["number"]),_physics_setBodyTransform:n("physics_setBodyTransform",null,["number","number","number","number"]),_physics_getDynamicBodyCount:n("physics_getDynamicBodyCount","number",[]),_physics_getDynamicBodyTransforms:n("physics_getDynamicBodyTransforms","number",[]),_physics_collectEvents:n("physics_collectEvents",null,[]),_physics_getCollisionEnterCount:n("physics_getCollisionEnterCount","number",[]),_physics_getCollisionEnterBuffer:n("physics_getCollisionEnterBuffer","number",[]),_physics_getCollisionExitCount:n("physics_getCollisionExitCount","number",[]),_physics_getCollisionExitBuffer:n("physics_getCollisionExitBuffer","number",[]),_physics_getSensorEnterCount:n("physics_getSensorEnterCount","number",[]),_physics_getSensorEnterBuffer:n("physics_getSensorEnterBuffer","number",[]),_physics_getSensorExitCount:n("physics_getSensorExitCount","number",[]),_physics_getSensorExitBuffer:n("physics_getSensorExitBuffer","number",[]),_physics_applyForce:n("physics_applyForce",null,["number","number","number"]),_physics_applyImpulse:n("physics_applyImpulse",null,["number","number","number"]),_physics_setLinearVelocity:n("physics_setLinearVelocity",null,["number","number","number"]),_physics_getLinearVelocity:n("physics_getLinearVelocity","number",["number"]),_physics_setGravity:n("physics_setGravity",null,["number","number"]),_physics_getGravity:n("physics_getGravity","number",[]),_physics_setAngularVelocity:n("physics_setAngularVelocity",null,["number","number"]),_physics_getAngularVelocity:n("physics_getAngularVelocity","number",["number"]),_physics_applyTorque:n("physics_applyTorque",null,["number","number"]),_physics_applyAngularImpulse:n("physics_applyAngularImpulse",null,["number","number"]),_physics_updateBodyProperties:n("physics_updateBodyProperties",null,["number","number","number","number","number","number","number"]),get HEAPF32(){return t.HEAPF32},get HEAPU8(){return t.HEAPU8},get HEAPU32(){return t.HEAPU32},_malloc:t._malloc.bind(t),_free:t._free.bind(t)}}const g=i("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),b=i("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),x=i("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),E=i("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 l=function(e){const t=e.world.getEntitiesWithComponents([r]);for(const n of t){const t=e.world.get(n,r);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),c=1/l,u=e.world;var y;e.addSystemToSchedule(m.PostUpdate,function(e,t,n){const i=++d;return{_id:Symbol(`System_${i}_${n?.name}`),_params:e,_fn:t,_name:n?.name??`System_${i}`}}([(y=_,{_type:"res",_resource:y})],r=>{const y=u.getEntitiesWithComponents([g,s,o]),p=new Set;for(const s of y){p.add(s);const r=u.get(s,g),a=u.get(s,o);if(t.has(s)){const e=n.get(s);!e||e.bodyType===r.bodyType&&e.gravityScale===r.gravityScale&&e.linearDamping===r.linearDamping&&e.angularDamping===r.angularDamping&&e.fixedRotation===r.fixedRotation&&e.bullet===r.bullet||(i._physics_updateBodyProperties(s,r.bodyType,r.gravityScale,r.linearDamping,r.angularDamping,r.fixedRotation?1:0,r.bullet?1:0),e.bodyType=r.bodyType,e.gravityScale=r.gravityScale,e.linearDamping=r.linearDamping,e.angularDamping=r.angularDamping,e.fixedRotation=r.fixedRotation,e.bullet=r.bullet)}else{if(!r.enabled)continue;const o=C(a.rotation);i._physics_createBody(s,r.bodyType,a.position.x*c,a.position.y*c,o,r.gravityScale,r.linearDamping,r.angularDamping,r.fixedRotation?1:0,r.bullet?1:0),B(e,i,s),t.add(s),n.set(s,{bodyType:r.bodyType,gravityScale:r.gravityScale,linearDamping:r.linearDamping,angularDamping:r.angularDamping,fixedRotation:r.fixedRotation,bullet:r.bullet})}if(r.bodyType===S.Kinematic){const e=C(a.rotation);i._physics_setBodyTransform(s,a.position.x*c,a.position.y*c,e)}}for(const e of t)p.has(e)||(i._physics_destroyBody(e),t.delete(e),n.delete(e));i._physics_step(r.delta),function(e,t,n){const i=t._physics_getDynamicBodyCount();if(0===i)return;const r=t._physics_getDynamicBodyTransforms(),l=r>>2;for(let r=0;r<i;r++){const i=l+4*r,c=t.HEAPU32[i],u=t.HEAPF32[i+1]*n,y=t.HEAPF32[i+2]*n,p=t.HEAPF32[i+3];if(!e.world.valid(c))continue;const _=e.world.get(c,s);if(!_)continue;let m=u,d=y,h=p;if(e.world.has(c,a)){const t=e.world.get(c,a);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,o)){const n=e.world.get(t.entity,o),i=C(n.rotation),s=u-n.position.x,r=y-n.position.y,a=Math.cos(-i),l=Math.sin(-i);m=(s*a-r*l)/(0!==n.scale.x?n.scale.x:1),d=(s*l+r*a)/(0!==n.scale.y?n.scale.y:1),h=p-i}}_.position.x=m,_.position.y=d;const f=A(h);_.rotation.w=f.w,_.rotation.x=f.x,_.rotation.y=f.y,_.rotation.z=f.z,e.world.insert(c,s,_)}}(e,i,l),function(e,t,n){t._physics_collectEvents();const i=[],s=t._physics_getCollisionEnterCount();if(s>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<s;o++){const s=e+6*o;i.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1],normalX:t.HEAPF32[s+2],normalY:t.HEAPF32[s+3],contactX:t.HEAPF32[s+4]*n,contactY:t.HEAPF32[s+5]*n})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<r;n++){const i=e+2*n;o.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const i=e+2*n;a.push({sensorEntity:t.HEAPU32[i],visitorEntity:t.HEAPU32[i+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const i=e+2*n;c.push({sensorEntity:t.HEAPU32[i],visitorEntity:t.HEAPU32[i+1]})}}e.insertResource(P,{collisionEnters:i,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,i,l)},{name:"PhysicsSystem"})),e.physicsModule=i,e.insertResource(w,U._fromModule(i)),e.setFixedTimestep(this.config_.fixedTimestep)});i.catch(()=>{}),e.physicsInitPromise=i}}function B(e,t,n){const i=e.world;if(i.has(n,b)){const e=i.get(n,b);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(i.has(n,x)){const e=i.get(n,x);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(i.has(n,E)){const e=i.get(n,E);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class U{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(U.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}export{S as BodyType,b as BoxCollider,E as CapsuleCollider,x as CircleCollider,U as Physics,w as PhysicsAPI,P as PhysicsEvents,v as PhysicsPlugin,g as RigidBody,h as loadPhysicsModule,f as loadPhysicsSideModule};
//# sourceMappingURL=index.js.map
diff --git a/desktop/public/sdk/esm/spine/index.d.ts b/desktop/public/sdk/esm/spine/index.d.ts
index 58bac76a2..21e5afddd 100644
--- a/desktop/public/sdk/esm/spine/index.d.ts
+++ b/desktop/public/sdk/esm/spine/index.d.ts
@@ -82,6 +82,7 @@ interface BoxCollider {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
interface CircleCollider {
radius: number;
@@ -90,6 +91,7 @@ interface CircleCollider {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
interface CapsuleCollider {
radius: number;
@@ -99,6 +101,7 @@ interface CapsuleCollider {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
interface LocalTransform {
position: Vec3;
@@ -128,6 +131,7 @@ interface SpineAnimation {
layer: number;
skeletonScale: number;
material: number;
+ enabled: boolean;
}
interface RigidBody {
bodyType: number;
@@ -146,6 +150,7 @@ interface BitmapText {
spacing: number;
layer: number;
font: number;
+ enabled: boolean;
}
interface Sprite {
texture: number;
@@ -157,6 +162,7 @@ interface Sprite {
flipX: boolean;
flipY: boolean;
material: number;
+ enabled: boolean;
}
interface Parent {
entity: number;
diff --git a/desktop/public/sdk/esm/spine/index.js b/desktop/public/sdk/esm/spine/index.js
index 0aef1c8f5..be5796df5 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 s=++e;return{_id:Symbol(`Resource_${s}_${n??""}`),_name:n??`Resource_${s}`,_default:t}}t({delta:0,elapsed:0,frameCount:0},"Time");function n(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(n);const t={};for(const s in e)t[s]=n(e[s]);return t}let s=0;const a=new Map;function i(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return a.set(e,n),n}i("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}});const r=i("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}});i("Sprite",{texture:4294967295,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),i("Camera",{projectionType:1,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),i("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),i("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),i("Parent",{entity:0}),i("Children",{entities:[]}),i("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:4294967295});const o=i("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),l={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};var c,u,p,d;!function(e,t){const a="undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map),i=a.get(e);if(i)return i;const r=function(e,t){const a=++s;return{_id:Symbol(`Component_${a}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...n(t),...e}:n(t)}}(e,t);a.set(e,r),function(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}(e,t,!1)}("SceneOwner",{scene:"",persistent:!1}),c="Name",u=l,a.set(c,u),function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(p||(p={})),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"}(d||(d={}));const h=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],m=new Map,_=new Set;for(const e of h)for(const t of e.extensions)m.set(t,e),_.add(t);const g=t(null,"Assets");function y(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 b(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:y(n)}}class f{constructor(e,t){this.raw_=e,this.api_=t,this.listeners_=new Map}get raw(){return this.raw_}loadSkeleton(e,t,n){let s,a;if("string"==typeof e){const t=(new TextEncoder).encode(e);a=t.length,s=this.raw_._malloc(a+1),this.raw_.HEAPU8.set(t,s),this.raw_.HEAPU8[s+a]=0}else a=e.length,s=this.raw_._malloc(a),this.raw_.HEAPU8.set(e,s);const i=this.api_.loadSkeleton(s,a,t,t.length,n);return this.raw_._free(s),i}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,s,a){this.api_.setAtlasPageTexture(e,t,n,s,a)}createInstance(e){return this.api_.createInstance(e)}destroyInstance(e){this.api_.destroyInstance(e),this.listeners_.delete(e)}play(e,t,n=!0,s=0){return!!this.api_.playAnimation(e,t,n,s)}addAnimation(e,t,n=!0,s=0,a=0){return!!this.api_.addAnimation(e,t,n,s,a)}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),s=this.raw_._malloc(4);if(!this.api_.getBonePosition(e,t,n,s))return this.raw_._free(n),this.raw_._free(s),null;const a=this.raw_.HEAPF32[n>>2],i=this.raw_.HEAPF32[s>>2];return this.raw_._free(n),this.raw_._free(s),{x:a,y:i}}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,s=t>>2,a={x:n[s],y:n[s+1],width:n[s+2],height:n[s+3]};return this.raw_._free(t),a}extractMeshBatches(e){const t=this.api_.getMeshBatchCount(e),n=[],s=this.raw_._malloc(8),a=s,i=s+4;for(let s=0;s<t;s++){const t=this.api_.getMeshBatchVertexCount(e,s),r=this.api_.getMeshBatchIndexCount(e,s);if(t<=0||r<=0)continue;const o=8*t*4,l=2*r,c=this.raw_._malloc(o),u=this.raw_._malloc(l);this.api_.getMeshBatchData(e,s,c,u,a,i);const p=new Float32Array(this.raw_.HEAPF32.buffer,c,8*t),d=new Uint16Array(this.raw_.HEAPU8.buffer,u,r);n.push({vertices:new Float32Array(p),indices:new Uint16Array(d),textureId:this.raw_.HEAPU32[a>>2],blendMode:this.raw_.HEAPU32[i>>2]}),this.raw_._free(c),this.raw_._free(u)}return this.raw_._free(s),n}on(e,t,n){this.listeners_.has(e)||this.listeners_.set(e,new Map);const s=this.listeners_.get(e);s.has(t)||s.set(t,new Set),s.get(t).add(n)}off(e,t,n){const s=this.listeners_.get(e);if(!s)return;const a=s.get(t);a&&a.delete(n)}removeAllListeners(e){this.listeners_.delete(e)}}const w=t(null,"SpineController"),x=new Float32Array(16);function P(e,t,n,s){const a=e.scale.x*t*(n?-1:1),i=e.scale.y*t*(s?-1:1),r=e.scale.z,o=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,p=o+o,d=l+l,h=c+c,m=o*p,_=o*d,g=o*h,y=l*d,b=l*h,f=c*h,w=u*p,P=u*d,T=u*h;return x[0]=(1-(y+f))*a,x[1]=(_+T)*a,x[2]=(g-P)*a,x[3]=0,x[4]=(_-T)*i,x[5]=(1-(m+f))*i,x[6]=(b+w)*i,x[7]=0,x[8]=(g+P)*r,x[9]=(b-w)*r,x[10]=(1-(m+y))*r,x[11]=0,x[12]=e.position.x,x[13]=e.position.y,x[14]=e.position.z,x[15]=1,x}class T{constructor(e,t){this.wasmUrl_=e,this.factory_=t}build(e){const t=e.wasmModule,n=b(this.wasmUrl_,this.factory_).then(({raw:n,api:s})=>{const a=new f(n,s);e.insertResource(w,a),e.hasResource(g)&&e.getResource(g).setSpineController(a);const i=new Map,l=new Map,c=new Map,u={_id:Symbol("SpineAutoSystem"),_name:"SpineAutoSystem",_params:[],_fn:()=>{const t=e.world,n=e.hasResource(g)?e.getResource(g):null;if(!n)return;const s=t.getEntitiesWithComponents([o]),r=new Set;for(const e of s){r.add(e);const s=t.get(e,o),u=`${s.skeletonPath}:${s.atlasPath}`;if(!i.has(e)||l.get(e)!==u){i.has(e)&&(a.destroyInstance(i.get(e)),i.delete(e),l.delete(e),c.delete(e));const t=n.getSpineSkeletonHandle(s.skeletonPath,s.atlasPath);if(void 0===t)continue;const r=a.createInstance(t);if(r<0)continue;i.set(e,r),l.set(e,u),s.skin&&a.setSkin(r,s.skin),s.animation&&a.play(r,s.animation,s.loop),c.set(e,{animation:s.animation,skin:s.skin,loop:s.loop});continue}const p=c.get(e);if(!p)continue;const d=i.get(e);p.skin!==s.skin&&(a.setSkin(d,s.skin),p.skin=s.skin),p.animation===s.animation&&p.loop===s.loop||(s.animation&&a.play(d,s.animation,s.loop),p.animation=s.animation,p.loop=s.loop)}for(const[e,t]of i)r.has(e)||(a.destroyInstance(t),i.delete(e),l.delete(e),c.delete(e))}};if(e.addSystemToSchedule(p.PreUpdate,u),!e.pipeline?.spineRenderer){let n=0;e.setSpineRenderer((s,l)=>{let c=l-n;n=l,(c<=0||c>.5)&&(c=1/60);const u=e.world;for(const[e,n]of i){const s=u.has(e,o)?u.get(e,o):null,i=!1!==s?.playing,l=s?.timeScale??1;let p;if(i&&a.update(n,c*l),u.has(e,r)){p=P(u.get(e,r),s?.skeletonScale??1,s?.flipX??!1,s?.flipY??!1)}const d=s?.color;C(t,a,n,p,d)}})}return{controller:a,coreModule:t}});e.insertResource(w,null),n.catch(()=>{}),e.spineInitPromise=n}}let A=new Float32Array(0),S=0,k=0,M=0,v=0,B=0,I=null;function U(e,t,n,s){if(t&&n>=s)return[t,n];t&&e._free(t);const a=2*s;return[e._malloc(a),a]}function C(e,t,n,s,a){I&&I!==e&&I&&(S&&(I._free(S),S=0,k=0),M&&(I._free(M),M=0,v=0),B&&(I._free(B),B=0),I=null),I=e;const i=t.extractMeshBatches(n);s&&(B||(B=e._malloc(64)),e.HEAPF32.set(s,B>>2));const r=a&&(1!==a.r||1!==a.g||1!==a.b||1!==a.a);for(const t of i){let n=t.vertices;if(r){const e=t.blendMode>=4;A.length<n.length&&(A=new Float32Array(2*n.length)),A.set(n);const s=A.subarray(0,n.length);for(let t=0;t<s.length;t+=8)e?(s[t+4]*=a.r*a.a,s[t+5]*=a.g*a.a,s[t+6]*=a.b*a.a):(s[t+4]*=a.r,s[t+5]*=a.g,s[t+6]*=a.b),s[t+7]*=a.a;n=s}const i=n.byteLength,o=t.indices.byteLength;[S,k]=U(e,S,k,i),[M,v]=U(e,M,v,o),e.HEAPF32.set(n,S>>2),new Uint16Array(e.HEAPU8.buffer,M,t.indices.length).set(t.indices),e.renderer_submitTriangles(S,n.length/8,M,t.indices.length,t.textureId,t.blendMode,s?B:0)}}export{f as SpineModuleController,T as SpinePlugin,w as SpineResource,b as loadSpineModule,C as submitSpineMeshesToCore,y as wrapSpineModule};
+let e=0;function t(t,n){const s=++e;return{_id:Symbol(`Resource_${s}_${n??""}`),_name:n??`Resource_${s}`,_default:t}}t({delta:0,elapsed:0,frameCount:0},"Time");function n(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(n);const t={};for(const s in e)t[s]=n(e[s]);return t}let s=0;const a=new Map;function i(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return a.set(e,n),n}i("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}});const r=i("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}});i("Sprite",{texture:4294967295,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),i("Camera",{projectionType:1,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),i("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),i("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),i("Parent",{entity:0}),i("Children",{entities:[]}),i("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:4294967295,enabled:!0});const o=i("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),l={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};var c,u,p,d;!function(e,t){const a="undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map),i=a.get(e);if(i)return i;const r=function(e,t){const a=++s;return{_id:Symbol(`Component_${a}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...n(t),...e}:n(t)}}(e,t);a.set(e,r),function(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}(e,t,!1)}("SceneOwner",{scene:"",persistent:!1}),c="Name",u=l,a.set(c,u),function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(p||(p={})),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"}(d||(d={}));const h=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],m=new Map,_=new Set;for(const e of h)for(const t of e.extensions)m.set(t,e),_.add(t);const g=t(null,"Assets");function b(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 y(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:b(n)}}class f{constructor(e,t){this.raw_=e,this.api_=t,this.listeners_=new Map}get raw(){return this.raw_}loadSkeleton(e,t,n){let s,a;if("string"==typeof e){const t=(new TextEncoder).encode(e);a=t.length,s=this.raw_._malloc(a+1),this.raw_.HEAPU8.set(t,s),this.raw_.HEAPU8[s+a]=0}else a=e.length,s=this.raw_._malloc(a),this.raw_.HEAPU8.set(e,s);const i=this.api_.loadSkeleton(s,a,t,t.length,n);return this.raw_._free(s),i}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,s,a){this.api_.setAtlasPageTexture(e,t,n,s,a)}createInstance(e){return this.api_.createInstance(e)}destroyInstance(e){this.api_.destroyInstance(e),this.listeners_.delete(e)}play(e,t,n=!0,s=0){return!!this.api_.playAnimation(e,t,n,s)}addAnimation(e,t,n=!0,s=0,a=0){return!!this.api_.addAnimation(e,t,n,s,a)}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),s=this.raw_._malloc(4);if(!this.api_.getBonePosition(e,t,n,s))return this.raw_._free(n),this.raw_._free(s),null;const a=this.raw_.HEAPF32[n>>2],i=this.raw_.HEAPF32[s>>2];return this.raw_._free(n),this.raw_._free(s),{x:a,y:i}}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,s=t>>2,a={x:n[s],y:n[s+1],width:n[s+2],height:n[s+3]};return this.raw_._free(t),a}extractMeshBatches(e){const t=this.api_.getMeshBatchCount(e),n=[],s=this.raw_._malloc(8),a=s,i=s+4;for(let s=0;s<t;s++){const t=this.api_.getMeshBatchVertexCount(e,s),r=this.api_.getMeshBatchIndexCount(e,s);if(t<=0||r<=0)continue;const o=8*t*4,l=2*r,c=this.raw_._malloc(o),u=this.raw_._malloc(l);this.api_.getMeshBatchData(e,s,c,u,a,i);const p=new Float32Array(this.raw_.HEAPF32.buffer,c,8*t),d=new Uint16Array(this.raw_.HEAPU8.buffer,u,r);n.push({vertices:new Float32Array(p),indices:new Uint16Array(d),textureId:this.raw_.HEAPU32[a>>2],blendMode:this.raw_.HEAPU32[i>>2]}),this.raw_._free(c),this.raw_._free(u)}return this.raw_._free(s),n}on(e,t,n){this.listeners_.has(e)||this.listeners_.set(e,new Map);const s=this.listeners_.get(e);s.has(t)||s.set(t,new Set),s.get(t).add(n)}off(e,t,n){const s=this.listeners_.get(e);if(!s)return;const a=s.get(t);a&&a.delete(n)}removeAllListeners(e){this.listeners_.delete(e)}}const w=t(null,"SpineController"),x=new Float32Array(16);function P(e,t,n,s){const a=e.scale.x*t*(n?-1:1),i=e.scale.y*t*(s?-1:1),r=e.scale.z,o=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,p=o+o,d=l+l,h=c+c,m=o*p,_=o*d,g=o*h,b=l*d,y=l*h,f=c*h,w=u*p,P=u*d,T=u*h;return x[0]=(1-(b+f))*a,x[1]=(_+T)*a,x[2]=(g-P)*a,x[3]=0,x[4]=(_-T)*i,x[5]=(1-(m+f))*i,x[6]=(y+w)*i,x[7]=0,x[8]=(g+P)*r,x[9]=(y-w)*r,x[10]=(1-(m+b))*r,x[11]=0,x[12]=e.position.x,x[13]=e.position.y,x[14]=e.position.z,x[15]=1,x}class T{constructor(e,t){this.wasmUrl_=e,this.factory_=t}build(e){const t=e.wasmModule,n=y(this.wasmUrl_,this.factory_).then(({raw:n,api:s})=>{const a=new f(n,s);e.insertResource(w,a),e.hasResource(g)&&e.getResource(g).setSpineController(a);const i=new Map,l=new Map,c=new Map,u={_id:Symbol("SpineAutoSystem"),_name:"SpineAutoSystem",_params:[],_fn:()=>{const t=e.world,n=e.hasResource(g)?e.getResource(g):null;if(!n)return;const s=t.getEntitiesWithComponents([o]),r=new Set;for(const e of s){r.add(e);const s=t.get(e,o),u=`${s.skeletonPath}:${s.atlasPath}`;if(!i.has(e)||l.get(e)!==u){i.has(e)&&(a.destroyInstance(i.get(e)),i.delete(e),l.delete(e),c.delete(e));const t=n.getSpineSkeletonHandle(s.skeletonPath,s.atlasPath);if(void 0===t)continue;const r=a.createInstance(t);if(r<0)continue;i.set(e,r),l.set(e,u),s.skin&&a.setSkin(r,s.skin),s.animation&&a.play(r,s.animation,s.loop),c.set(e,{animation:s.animation,skin:s.skin,loop:s.loop});continue}const p=c.get(e);if(!p)continue;const d=i.get(e);p.skin!==s.skin&&(a.setSkin(d,s.skin),p.skin=s.skin),p.animation===s.animation&&p.loop===s.loop||(s.animation&&a.play(d,s.animation,s.loop),p.animation=s.animation,p.loop=s.loop)}for(const[e,t]of i)r.has(e)||(a.destroyInstance(t),i.delete(e),l.delete(e),c.delete(e))}};if(e.addSystemToSchedule(p.PreUpdate,u),!e.pipeline?.spineRenderer){let n=0;e.setSpineRenderer((s,l)=>{let c=l-n;n=l,(c<=0||c>.5)&&(c=1/60);const u=e.world;for(const[e,n]of i){const s=u.has(e,o)?u.get(e,o):null,i=!1!==s?.playing,l=s?.timeScale??1;let p;if(i&&a.update(n,c*l),u.has(e,r)){p=P(u.get(e,r),s?.skeletonScale??1,s?.flipX??!1,s?.flipY??!1)}const d=s?.color;C(t,a,n,p,d)}})}return{controller:a,coreModule:t}});e.insertResource(w,null),n.catch(()=>{}),e.spineInitPromise=n}}let A=new Float32Array(0),S=0,k=0,M=0,v=0,B=0,I=null;function U(e,t,n,s){if(t&&n>=s)return[t,n];t&&e._free(t);const a=2*s;return[e._malloc(a),a]}function C(e,t,n,s,a){I&&I!==e&&I&&(S&&(I._free(S),S=0,k=0),M&&(I._free(M),M=0,v=0),B&&(I._free(B),B=0),I=null),I=e;const i=t.extractMeshBatches(n);s&&(B||(B=e._malloc(64)),e.HEAPF32.set(s,B>>2));const r=a&&(1!==a.r||1!==a.g||1!==a.b||1!==a.a);for(const t of i){let n=t.vertices;if(r){const e=t.blendMode>=4;A.length<n.length&&(A=new Float32Array(2*n.length)),A.set(n);const s=A.subarray(0,n.length);for(let t=0;t<s.length;t+=8)e?(s[t+4]*=a.r*a.a,s[t+5]*=a.g*a.a,s[t+6]*=a.b*a.a):(s[t+4]*=a.r,s[t+5]*=a.g,s[t+6]*=a.b),s[t+7]*=a.a;n=s}const i=n.byteLength,o=t.indices.byteLength;[S,k]=U(e,S,k,i),[M,v]=U(e,M,v,o),e.HEAPF32.set(n,S>>2),new Uint16Array(e.HEAPU8.buffer,M,t.indices.length).set(t.indices),e.renderer_submitTriangles(S,n.length/8,M,t.indices.length,t.textureId,t.blendMode,s?B:0)}}export{f as SpineModuleController,T as SpinePlugin,w as SpineResource,y as loadSpineModule,C as submitSpineMeshesToCore,b 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 3fc3c60b3..9f55f3761 100644
--- a/desktop/public/sdk/esm/wasm.d.ts
+++ b/desktop/public/sdk/esm/wasm.d.ts
@@ -42,6 +42,7 @@ interface BoxCollider {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
interface CircleCollider {
radius: number;
@@ -50,6 +51,7 @@ interface CircleCollider {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
interface CapsuleCollider {
radius: number;
@@ -59,6 +61,7 @@ interface CapsuleCollider {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
interface LocalTransform {
position: Vec3;
@@ -88,6 +91,7 @@ interface SpineAnimation {
layer: number;
skeletonScale: number;
material: number;
+ enabled: boolean;
}
interface RigidBody {
bodyType: number;
@@ -106,6 +110,7 @@ interface BitmapText {
spacing: number;
layer: number;
font: number;
+ enabled: boolean;
}
interface Sprite {
texture: number;
@@ -117,6 +122,7 @@ interface Sprite {
flipX: boolean;
flipY: boolean;
material: number;
+ enabled: boolean;
}
interface Parent {
entity: number;
diff --git a/desktop/public/wasm/esengine.single.js b/desktop/public/wasm/esengine.single.js
index e9d40b029..db0d5b44a 100644
Binary files a/desktop/public/wasm/esengine.single.js and b/desktop/public/wasm/esengine.single.js differ
diff --git a/editor/src/panels/inspector/EntityInspector.ts b/editor/src/panels/inspector/EntityInspector.ts
index d68b9fd95..88fe997b0 100644
--- a/editor/src/panels/inspector/EntityInspector.ts
+++ b/editor/src/panels/inspector/EntityInspector.ts
@@ -177,15 +177,34 @@ export function renderComponent(
const icon = getComponentIcon(component.type);
const removable = isComponentRemovable(component.type);
+ const hasEnabled = 'enabled' in defaults;
+ const isEnabled = hasEnabled ? (component.data.enabled ?? defaults.enabled) !== false : true;
+
+ if (hasEnabled && !isEnabled) {
+ section.dataset.enabled = 'false';
+ }
+
const header = document.createElement('div');
header.className = 'es-component-header es-collapsible-header';
header.innerHTML = `
<span class="es-collapse-icon">${icons.chevronDown(12)}</span>
<span class="es-component-icon">${icon}</span>
<span class="es-component-title">${component.type}</span>
+ ${hasEnabled ? `<input type="checkbox" class="es-component-enabled-toggle" title="Enable/Disable component" ${isEnabled ? 'checked' : ''}>` : ''}
${removable ? `<button class="es-btn es-btn-icon es-btn-remove">${icons.x(12)}</button>` : ''}
`;
+ if (hasEnabled) {
+ const toggle = header.querySelector('.es-component-enabled-toggle') as HTMLInputElement;
+ toggle?.addEventListener('click', (e) => {
+ e.stopPropagation();
+ });
+ toggle?.addEventListener('change', () => {
+ const oldValue = component.data.enabled ?? defaults.enabled;
+ store.updateProperty(entity, component.type, 'enabled', oldValue, toggle.checked);
+ });
+ }
+
if (removable) {
const removeBtn = header.querySelector('.es-btn-remove');
removeBtn?.addEventListener('click', () => {
@@ -195,6 +214,7 @@ export function renderComponent(
header.addEventListener('click', (e) => {
if ((e.target as HTMLElement).closest('.es-btn-remove')) return;
+ if ((e.target as HTMLElement).closest('.es-component-enabled-toggle')) return;
section.classList.toggle('es-expanded');
});
diff --git a/editor/src/scene/EditorSceneManager.ts b/editor/src/scene/EditorSceneManager.ts
index 383f3861d..b39082267 100644
--- a/editor/src/scene/EditorSceneManager.ts
+++ b/editor/src/scene/EditorSceneManager.ts
@@ -429,6 +429,7 @@ export class EditorSceneManager {
const spineComp = entityData.components.find(c => c.type === 'SpineAnimation');
const spineData = spineComp?.data as Record<string, unknown> | undefined;
+ if (spineData?.enabled === false) continue;
const skeletonScale = (spineData?.skeletonScale as number) ?? 1;
const flipX = (spineData?.flipX as boolean) ?? false;
@@ -677,6 +678,7 @@ export class EditorSceneManager {
flipX: data.flipX ?? false,
flipY: data.flipY ?? false,
material: materialHandle,
+ enabled: data.enabled ?? true,
});
}
@@ -801,6 +803,7 @@ export class EditorSceneManager {
spacing: data.spacing ?? 0,
layer: data.layer ?? 0,
font: fontHandle,
+ enabled: data.enabled ?? true,
});
}
@@ -931,6 +934,7 @@ export class EditorSceneManager {
layer: data.layer ?? 0,
skeletonScale: data.skeletonScale ?? 1,
material: materialHandle,
+ enabled: data.enabled ?? true,
},
});
}
diff --git a/editor/src/styles/inspector.css b/editor/src/styles/inspector.css
index a3b4ae240..3d9b46bda 100644
--- a/editor/src/styles/inspector.css
+++ b/editor/src/styles/inspector.css
@@ -273,6 +273,20 @@
white-space: nowrap;
}
+.es-component-enabled-toggle {
+ flex-shrink: 0;
+ width: 13px;
+ height: 13px;
+ margin: 0;
+ cursor: pointer;
+ accent-color: var(--es-accent);
+}
+
+.es-component-section[data-enabled="false"] > .es-collapsible-content {
+ opacity: 0.5;
+ pointer-events: none;
+}
+
.es-collapsible-content {
display: block;
}
diff --git a/sdk/src/component.ts b/sdk/src/component.ts
index ddec26bed..ba4a39c5d 100644
--- a/sdk/src/component.ts
+++ b/sdk/src/component.ts
@@ -209,6 +209,7 @@ export interface SpriteData {
flipX: boolean;
flipY: boolean;
material: number;
+ enabled: boolean;
}
export interface CameraData {
@@ -263,6 +264,7 @@ export interface SpineAnimationData {
layer: number;
skeletonScale: number;
material: number;
+ enabled: boolean;
}
export interface BitmapTextData {
@@ -273,6 +275,7 @@ export interface BitmapTextData {
spacing: number;
layer: number;
font: number;
+ enabled: boolean;
}
export interface NameData {
@@ -309,7 +312,8 @@ export const Sprite = defineBuiltin<SpriteData>('Sprite', {
layer: 0,
flipX: false,
flipY: false,
- material: 0
+ material: 0,
+ enabled: true
});
export const Camera = defineBuiltin<CameraData>('Camera', {
@@ -358,6 +362,7 @@ export const BitmapText = defineBuiltin<BitmapTextData>('BitmapText', {
spacing: 0,
layer: 0,
font: INVALID_FONT,
+ enabled: true,
});
export const SpineAnimation = defineBuiltin<SpineAnimationData>('SpineAnimation', {
@@ -373,7 +378,8 @@ export const SpineAnimation = defineBuiltin<SpineAnimationData>('SpineAnimation'
color: { r: 1, g: 1, b: 1, a: 1 },
layer: 0,
skeletonScale: 1.0,
- material: 0
+ material: 0,
+ enabled: true
});
export const Name: ComponentDef<NameData> = {
diff --git a/sdk/src/physics/PhysicsComponents.ts b/sdk/src/physics/PhysicsComponents.ts
index 6a71c62ff..f510ccb20 100644
--- a/sdk/src/physics/PhysicsComponents.ts
+++ b/sdk/src/physics/PhysicsComponents.ts
@@ -27,6 +27,7 @@ export interface BoxColliderData {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
export interface CircleColliderData {
@@ -36,6 +37,7 @@ export interface CircleColliderData {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
export interface CapsuleColliderData {
@@ -46,6 +48,7 @@ export interface CapsuleColliderData {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
// =============================================================================
@@ -68,7 +71,8 @@ export const BoxCollider = defineBuiltin<BoxColliderData>('BoxCollider', {
density: 1.0,
friction: 0.3,
restitution: 0.0,
- isSensor: false
+ isSensor: false,
+ enabled: true
});
export const CircleCollider = defineBuiltin<CircleColliderData>('CircleCollider', {
@@ -77,7 +81,8 @@ export const CircleCollider = defineBuiltin<CircleColliderData>('CircleCollider'
density: 1.0,
friction: 0.3,
restitution: 0.0,
- isSensor: false
+ isSensor: false,
+ enabled: true
});
export const CapsuleCollider = defineBuiltin<CapsuleColliderData>('CapsuleCollider', {
@@ -87,7 +92,8 @@ export const CapsuleCollider = defineBuiltin<CapsuleColliderData>('CapsuleCollid
density: 1.0,
friction: 0.3,
restitution: 0.0,
- isSensor: false
+ isSensor: false,
+ enabled: true
});
// =============================================================================
diff --git a/sdk/src/ui/Button.ts b/sdk/src/ui/Button.ts
index fc34bbfb8..129a5d1b2 100644
--- a/sdk/src/ui/Button.ts
+++ b/sdk/src/ui/Button.ts
@@ -18,9 +18,11 @@ export interface ButtonTransition {
export interface ButtonData {
state: ButtonState;
transition: ButtonTransition | null;
+ enabled: boolean;
}
export const Button = defineComponent<ButtonData>('Button', {
state: ButtonState.Normal,
transition: null,
+ enabled: true,
});
diff --git a/sdk/src/ui/Image.ts b/sdk/src/ui/Image.ts
index c07f5125c..37c4e336a 100644
--- a/sdk/src/ui/Image.ts
+++ b/sdk/src/ui/Image.ts
@@ -37,6 +37,7 @@ export interface ImageData {
preserveAspect: boolean;
layer: number;
material: number;
+ enabled: boolean;
}
export const Image = defineComponent<ImageData>('Image', {
@@ -49,4 +50,5 @@ export const Image = defineComponent<ImageData>('Image', {
preserveAspect: false,
layer: 0,
material: 0,
+ enabled: true,
});
diff --git a/sdk/src/ui/Slider.ts b/sdk/src/ui/Slider.ts
index 53e8fc205..f668aadb4 100644
--- a/sdk/src/ui/Slider.ts
+++ b/sdk/src/ui/Slider.ts
@@ -15,6 +15,7 @@ export interface SliderData {
fillEntity: number;
handleEntity: number;
wholeNumbers: boolean;
+ enabled: boolean;
}
export const Slider = defineComponent<SliderData>('Slider', {
@@ -25,4 +26,5 @@ export const Slider = defineComponent<SliderData>('Slider', {
fillEntity: 0,
handleEntity: 0,
wholeNumbers: false,
+ enabled: true,
});
diff --git a/sdk/src/ui/Toggle.ts b/sdk/src/ui/Toggle.ts
index 6a118fc6e..57687a132 100644
--- a/sdk/src/ui/Toggle.ts
+++ b/sdk/src/ui/Toggle.ts
@@ -12,10 +12,12 @@ export interface ToggleData {
isOn: boolean;
graphicEntity: Entity;
transition: ToggleTransition | null;
+ enabled: boolean;
}
export const Toggle = defineComponent<ToggleData>('Toggle', {
isOn: true,
graphicEntity: 0 as Entity,
transition: null,
+ enabled: true,
});
diff --git a/sdk/src/wasm.generated.ts b/sdk/src/wasm.generated.ts
index fcfc7855f..6a830de7f 100644
--- a/sdk/src/wasm.generated.ts
+++ b/sdk/src/wasm.generated.ts
@@ -46,6 +46,7 @@ export interface BoxCollider {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
export interface CircleCollider {
@@ -55,6 +56,7 @@ export interface CircleCollider {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
export interface CapsuleCollider {
@@ -65,6 +67,7 @@ export interface CapsuleCollider {
friction: number;
restitution: number;
isSensor: boolean;
+ enabled: boolean;
}
export interface LocalTransform {
@@ -98,6 +101,7 @@ export interface SpineAnimation {
layer: number;
skeletonScale: number;
material: number;
+ enabled: boolean;
}
export interface RigidBody {
@@ -118,6 +122,7 @@ export interface BitmapText {
spacing: number;
layer: number;
font: number;
+ enabled: boolean;
}
export interface Sprite {
@@ -130,6 +135,7 @@ export interface Sprite {
flipX: boolean;
flipY: boolean;
material: number;
+ enabled: boolean;
}
export interface Parent {
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index 02961a160..0bbf81fc2 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -132,6 +132,7 @@ struct BitmapTextJS {
f32 spacing;
i32 layer;
u32 font;
+ bool enabled;
};
esengine::ecs::BitmapText bitmaptextFromJS(const BitmapTextJS& js) {
@@ -143,6 +144,7 @@ esengine::ecs::BitmapText bitmaptextFromJS(const BitmapTextJS& js) {
c.spacing = js.spacing;
c.layer = js.layer;
c.font = resource::BitmapFontHandle(js.font);
+ c.enabled = js.enabled;
return c;
}
@@ -155,6 +157,7 @@ BitmapTextJS bitmaptextToJS(const esengine::ecs::BitmapText& c) {
js.spacing = c.spacing;
js.layer = c.layer;
js.font = c.font.id();
+ js.enabled = c.enabled;
return js;
}
@@ -168,6 +171,7 @@ struct SpriteJS {
bool flipX;
bool flipY;
u32 material;
+ bool enabled;
};
esengine::ecs::Sprite spriteFromJS(const SpriteJS& js) {
@@ -181,6 +185,7 @@ esengine::ecs::Sprite spriteFromJS(const SpriteJS& js) {
c.flipX = js.flipX;
c.flipY = js.flipY;
c.material = js.material;
+ c.enabled = js.enabled;
return c;
}
@@ -195,6 +200,7 @@ SpriteJS spriteToJS(const esengine::ecs::Sprite& c) {
js.flipX = c.flipX;
js.flipY = c.flipY;
js.material = c.material;
+ js.enabled = c.enabled;
return js;
}
@@ -285,7 +291,8 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("density", &esengine::ecs::BoxCollider::density)
.field("friction", &esengine::ecs::BoxCollider::friction)
.field("restitution", &esengine::ecs::BoxCollider::restitution)
- .field("isSensor", &esengine::ecs::BoxCollider::isSensor);
+ .field("isSensor", &esengine::ecs::BoxCollider::isSensor)
+ .field("enabled", &esengine::ecs::BoxCollider::enabled);
value_object<esengine::ecs::CircleCollider>("CircleCollider")
.field("radius", &esengine::ecs::CircleCollider::radius)
@@ -293,7 +300,8 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("density", &esengine::ecs::CircleCollider::density)
.field("friction", &esengine::ecs::CircleCollider::friction)
.field("restitution", &esengine::ecs::CircleCollider::restitution)
- .field("isSensor", &esengine::ecs::CircleCollider::isSensor);
+ .field("isSensor", &esengine::ecs::CircleCollider::isSensor)
+ .field("enabled", &esengine::ecs::CircleCollider::enabled);
value_object<esengine::ecs::CapsuleCollider>("CapsuleCollider")
.field("radius", &esengine::ecs::CapsuleCollider::radius)
@@ -302,7 +310,8 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("density", &esengine::ecs::CapsuleCollider::density)
.field("friction", &esengine::ecs::CapsuleCollider::friction)
.field("restitution", &esengine::ecs::CapsuleCollider::restitution)
- .field("isSensor", &esengine::ecs::CapsuleCollider::isSensor);
+ .field("isSensor", &esengine::ecs::CapsuleCollider::isSensor)
+ .field("enabled", &esengine::ecs::CapsuleCollider::enabled);
value_object<esengine::ecs::LocalTransform>("LocalTransform")
.field("position", &esengine::ecs::LocalTransform::position)
@@ -331,7 +340,8 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("color", &esengine::ecs::SpineAnimation::color)
.field("layer", &esengine::ecs::SpineAnimation::layer)
.field("skeletonScale", &esengine::ecs::SpineAnimation::skeletonScale)
- .field("material", &esengine::ecs::SpineAnimation::material);
+ .field("material", &esengine::ecs::SpineAnimation::material)
+ .field("enabled", &esengine::ecs::SpineAnimation::enabled);
value_object<RigidBodyJS>("RigidBody")
.field("bodyType", &RigidBodyJS::bodyType)
@@ -349,7 +359,8 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("align", &BitmapTextJS::align)
.field("spacing", &BitmapTextJS::spacing)
.field("layer", &BitmapTextJS::layer)
- .field("font", &BitmapTextJS::font);
+ .field("font", &BitmapTextJS::font)
+ .field("enabled", &BitmapTextJS::enabled);
value_object<SpriteJS>("Sprite")
.field("texture", &SpriteJS::texture)
@@ -360,7 +371,8 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("layer", &SpriteJS::layer)
.field("flipX", &SpriteJS::flipX)
.field("flipY", &SpriteJS::flipY)
- .field("material", &SpriteJS::material);
+ .field("material", &SpriteJS::material)
+ .field("enabled", &SpriteJS::enabled);
value_object<esengine::ecs::Parent>("Parent")
.field("entity", &esengine::ecs::Parent::entity);
diff --git a/src/esengine/ecs/components/BitmapText.hpp b/src/esengine/ecs/components/BitmapText.hpp
index 4c635286e..9fba9a1b2 100644
--- a/src/esengine/ecs/components/BitmapText.hpp
+++ b/src/esengine/ecs/components/BitmapText.hpp
@@ -38,6 +38,9 @@ struct BitmapText {
ES_PROPERTY()
resource::BitmapFontHandle font;
+
+ ES_PROPERTY()
+ bool enabled{true};
};
} // namespace esengine::ecs
diff --git a/src/esengine/ecs/components/Collider.hpp b/src/esengine/ecs/components/Collider.hpp
index 467a4dd2b..c6e66cb6f 100644
--- a/src/esengine/ecs/components/Collider.hpp
+++ b/src/esengine/ecs/components/Collider.hpp
@@ -26,6 +26,9 @@ struct BoxCollider {
ES_PROPERTY()
bool isSensor{false};
+ ES_PROPERTY()
+ bool enabled{true};
+
BoxCollider() = default;
};
@@ -49,6 +52,9 @@ struct CircleCollider {
ES_PROPERTY()
bool isSensor{false};
+ ES_PROPERTY()
+ bool enabled{true};
+
CircleCollider() = default;
};
@@ -75,6 +81,9 @@ struct CapsuleCollider {
ES_PROPERTY()
bool isSensor{false};
+ ES_PROPERTY()
+ bool enabled{true};
+
CapsuleCollider() = default;
};
diff --git a/src/esengine/ecs/components/SpineAnimation.hpp b/src/esengine/ecs/components/SpineAnimation.hpp
index a6561d196..4806d273b 100644
--- a/src/esengine/ecs/components/SpineAnimation.hpp
+++ b/src/esengine/ecs/components/SpineAnimation.hpp
@@ -98,6 +98,9 @@ struct SpineAnimation {
ES_PROPERTY()
u32 material{0};
+ ES_PROPERTY()
+ bool enabled{true};
+
/** @brief Handle to cached skeleton data (runtime, not serialized) */
resource::SpineDataHandle skeletonData;
diff --git a/src/esengine/ecs/components/Sprite.hpp b/src/esengine/ecs/components/Sprite.hpp
index e24781005..3c9665fde 100644
--- a/src/esengine/ecs/components/Sprite.hpp
+++ b/src/esengine/ecs/components/Sprite.hpp
@@ -79,6 +79,9 @@ struct Sprite {
ES_PROPERTY()
u32 material{0};
+ ES_PROPERTY()
+ bool enabled{true};
+
/** @brief Default constructor (white, no texture) */
Sprite() = default;
diff --git a/src/esengine/renderer/RenderFrame.cpp b/src/esengine/renderer/RenderFrame.cpp
index 62ba690f8..7dddaa043 100644
--- a/src/esengine/renderer/RenderFrame.cpp
+++ b/src/esengine/renderer/RenderFrame.cpp
@@ -405,6 +405,7 @@ void RenderFrame::submitSprites(ecs::Registry& registry) {
for (auto entity : spriteView) {
const auto& sprite = spriteView.get<ecs::Sprite>(entity);
+ if (!sprite.enabled) continue;
glm::vec3 position;
glm::quat rotation;
@@ -502,6 +503,7 @@ void RenderFrame::submitBitmapText(ecs::Registry& registry) {
for (auto entity : textView) {
const auto& bt = textView.get<ecs::BitmapText>(entity);
+ if (!bt.enabled) continue;
if (bt.text.empty() || !bt.font.isValid()) {
continue;
}
@@ -581,6 +583,7 @@ void RenderFrame::submitSpine(ecs::Registry& registry, spine::SpineSystem& spine
for (auto entity : view) {
auto& comp = registry.get<ecs::SpineAnimation>(entity);
+ if (!comp.enabled) continue;
auto* instance = spine_system.getInstance(entity);
if (!instance || !instance->skeleton) continue;