A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
chore: sync SDK build artifacts
esengine85781cdc4118
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.jsindex bad7da077..bd809daf4 100644--- a/desktop/public/sdk/cjs/esengine.wechat.js+++ b/desktop/public/sdk/cjs/esengine.wechat.js@@ -1,2 +1,2 @@-"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function s(){return"wechat"===e?.name}async function n(e,s){return t().fetch(e,s)}async function r(e){return t().readFile(e)}async function o(e){return t().readTextFile(e)}async function i(e){return t().fileExists(e)}function a(e,s){return t().createCanvas(e,s)}function l(){return t().now()}function c(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 d(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const s=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(s,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${s}": ${t}`)}}const u=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],h={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"},f=new Map,p=new Set;for(const e of u)for(const t of e.extensions)f.set(t,e),p.add(t);function g(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function y(e){return f.get(g(e))}function m(e){return p.has(e.toLowerCase())}function _(){const e=[];for(const t of u)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function x(e){const t=y(e);return t?.wechatPackInclude??!1}let w=null;function v(){return w||(w=wx.getFileSystemManager()),w}function b(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 S(e){return new Promise((t,s)=>{v().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(b(e,t.errMsg)))}})})}function P(e,t="utf-8"){return new Promise((s,n)=>{v().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(b(e,t.errMsg)))}})})}function M(e){return new Promise(t=>{v().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 E(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 C=!1;const A=new class{constructor(){this.name="wechat"}async fetch(e,t){return c(e,t)}async readFile(e){return S(e)}async readTextFile(e){return P(e)}async fileExists(e){return M(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return d(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)})}},R=1920,I=1080,F=1/60,k={x:0,y:-9.81},D=1/60,B={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};const L=4294967295,U=4294967295;function W(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(W);const t={};for(const s in e)t[s]=W(e[s]);return t}let $=0;function z(e,t){const s=++$;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...W(t),...e}:W(t)}}const O=new Map;function H(){return"undefined"==typeof window?O:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function j(e,t){const s=G.get(e)??H().get(e);if(s)return s;const n=z(e,t);return H().set(e,n),G.set(e,n),V(e,t,!1),n}function X(e){const t=G.get(e)??H().get(e);if(t)return t;const s=z(e,{});return H().set(e,s),G.set(e,s),V(e,{},!0),s}function N(e){return H().get(e)}function V(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function Y(e){return!0===e._builtin}const G=new Map;function q(e,t){G.set(e,t)}function J(e){return G.get(e)??N(e)}function K(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return G.set(e,s),s}const Q={Perspective:0,Orthographic:1},Z={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ee={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},te=K("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=K("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),ne=K("Sprite",{texture:L,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}),re=K("Camera",{projectionType:Q.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:Z.ColorAndDepth}),oe=K("Canvas",{designResolution:{x:R,y:I},pixelsPerUnit:100,scaleMode:ee.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),ie=K("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),ae=K("Parent",{entity:0}),le=K("Children",{entities:[]}),ce=K("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:U,enabled:!0}),de=K("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}),ue={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},he=j("SceneOwner",{scene:"",persistent:!1});q("Name",ue);const fe=K("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),pe=K("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ge=K("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ye=K("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),me={Static:0,Kinematic:1,Dynamic:2};let _e=0;function xe(e,t){const s=++_e;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function we(e){return{_type:"res",_resource:e}}function ve(e){return{_type:"res_mut",_resource:e}}class be{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 Se{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 be(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Pe=xe({delta:0,elapsed:0,frameCount:0},"Time");function Me(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}class Te{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>Me(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 Ee{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=Y(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 Ce{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Ee(this,null);return this.spawned_.push(e),e}entity(e){return new Ee(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 Ae;exports.Schedule=void 0,(Ae=exports.Schedule||(exports.Schedule={}))[Ae.Startup=0]="Startup",Ae[Ae.First=1]="First",Ae[Ae.PreUpdate=2]="PreUpdate",Ae[Ae.Update=3]="Update",Ae[Ae.PostUpdate=4]="PostUpdate",Ae[Ae.Last=5]="Last",Ae[Ae.FixedPreUpdate=10]="FixedPreUpdate",Ae[Ae.FixedUpdate=11]="FixedUpdate",Ae[Ae.FixedPostUpdate=12]="FixedPostUpdate";let Re=0;function Ie(e,t,s){const n=++Re;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Fe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class ke{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 Ce&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new Te(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Ce(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class De{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 Be=xe(new De,"Input");class Le{constructor(e){this.target_=e??null}build(e){const s=new De;e.insertResource(Be,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,Ie([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Ue=new Le;function We(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=$e(t[e]),o=$e(r);"null"!==s&&"undefined"!==s&&(s!==o&&null!=r&&n.push({field:e,expected:s,actual:o,value:r}))}return n}function $e(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ze(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}let Oe=null;function He(e){Oe=e}function je(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Oe&&Oe(e,t)}function Xe(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}:Xe(e)}}return t}class Ne{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,this.nextEntityId_=0}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw je(e,"spawn"),e}else e=++this.nextEntityId_;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){je(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){je(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){je(t,`removeParent(entity=${e})`)}}insert(e,t,s){return Y(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return Y(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return Y(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(Y(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return je(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.");Y(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const s=this.cppRegistry_,n=s[`add${e}`],r=s[`get${e}`],o=s[`has${e}`],i=s[`remove${e}`];if("function"!=typeof n||"function"!=typeof r||"function"!=typeof o||"function"!=typeof i)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:n.bind(s),get:r.bind(s),has:o.bind(s),remove:i.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=We(t._name,t._default,n);if(e.length>0)throw new Error(ze(t._name,e))}const r={...t._default,...n};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,Xe(r))}catch(s){je(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 je(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 je(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){je(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=We(t._name,t._default,e);if(r.length>0)throw new Error(ze(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 G)if(Y(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=H();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(!Y(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 Ve=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,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var Ye;function Ge(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(Ye=exports.BlendMode||(exports.BlendMode={}))[Ye.Normal=0]="Normal",Ye[Ye.Additive=1]="Additive",Ye[Ye.Multiply=2]="Multiply",Ye[Ye.Screen=3]="Screen",Ye[Ye.PremultipliedAlpha=4]="PremultipliedAlpha";let qe=null,Je=null,Ke=1;const Qe=new Map;function Ze(e){qe=e,Je=e.getResourceManager(),ct()}function et(){0!==rt&&qe&&(qe._free(rt),rt=0),Qe.clear(),Ke=1,nt=!1,it.clear(),at=null,Je=null,qe=null}function tt(){if(!Je)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Je}const st={createShader:(e,t)=>tt().createShader(e,t),releaseShader(e){e>0&&tt().releaseShader(e)},create(e){const t=Ke++,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 Qe.set(t,s),t},get:e=>Qe.get(e),setUniform(e,t,s){const n=Qe.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Qe.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Qe.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Qe.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=Qe.get(e);s&&(s.depthTest=t)},getShader(e){const t=Qe.get(e);return t?.shader??0},release(e){Qe.delete(e)},isValid:e=>Qe.has(e),releaseAll(){Qe.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=Qe.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Ke++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Qe.set(s,n),s},toAssetData(e,t){const s=Qe.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=Qe.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let nt=!1,rt=0;const ot=4096,it=new Map;let at=null;function lt(e){const t=(0===rt&&qe&&(rt=qe._malloc(ot)),rt);if(0===t||!qe)return{ptr:0,count:0};let s=0,n=0;const r=qe.HEAPU8,o=qe.HEAPU32,i=qe.HEAPF32;for(const[a,l]of e){if(s+128>ot)break;let e=it.get(a);e||(at||(at=new TextEncoder),e=at.encode(a),it.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 ct(){if(!qe||nt)return;qe.materialDataProvider=(e,t,s,n,r)=>{const o=Qe.get(e);if(!o)return qe.HEAPU32[t>>2]=0,qe.HEAPU32[s>>2]=0,qe.HEAPU32[n>>2]=0,void(qe.HEAPU32[r>>2]=0);qe.HEAPU32[t>>2]=o.shader,qe.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=lt(o.uniforms);qe.HEAPU32[n>>2]=i,qe.HEAPU32[r>>2]=a},nt=!0}const dt={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class ut{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const 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 ht{constructor(e,t=""){this.cache_=new ut,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(st.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())st.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await i(t))throw new Error(`Material file not found: ${t}`);const s=await o(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const r=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(r);return{handle:st.createFromAsset(n,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const ft=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 pt(e){return ft.get(e)?.fields??[]}function gt(e){return ft.get(e)?.spine??null}const yt=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function mt(e,t){const s=yt.get(e.type);if(!s)return;const n=e.data;for(const e of s){const s=n[e];if("number"==typeof s&&0!==s){const r=t.get(s);n[e]=void 0!==r?r:0}}}function _t(e,t){const s=new Map;for(const n of t.entities){const t=e.spawn();s.set(n.id,t),e.insert(t,ue,{value:n.name})}for(const n of t.entities){if(!1===n.visible)continue;const t=s.get(n.id);for(const r of n.components)mt(r,s),vt(e,t,r,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}function xt(e,t){return _t(e,t)}async function wt(e,t,s){const n=s?.assetServer,r=s?.assetBaseUrl,o=new Map;n&&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=ft.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=ft.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,n,r,o);const i=_t(e,t);if(n&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&n.setTextureMetadataByPath(t,s.sliceBorder)}return i}function vt(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=J(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 bt{constructor(e){this.textureCache_=new ut,this.shaderCache_=new ut,this.jsonCache_=new ut,this.textCache_=new ut,this.binaryCache_=new ut,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new ut,this.prefabCache_=new ut,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.module_=e,this.canvas_=a(B.textCanvasSize,B.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,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(),st.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const 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"===y(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=y(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 wt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),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 st.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await i(t))throw new Error(`Shader file not found: ${e}`);const n=await o(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:a}=this.parseEsShader(n);if(!r||!a)throw new Error(`Invalid shader format: ${e}`);return st.createShader(r,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 o(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return o(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(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 s=await n(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let 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 St=xe(null,"Assets");class Pt{build(e){const t=e.wasmModule;t?e.insertResource(St,new bt(t)):console.warn("AssetPlugin: No WASM module available")}}const Mt=new Pt;async function Tt(e,t,s){const{entities:n,rootId:r}=await Ct(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 wt(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 Et=10;async function Ct(e,t,s,n,r,o=0){if(o>Et)throw new Error(`Prefab nesting depth exceeded ${Et}. 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 Ct(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};At(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 At(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 Rt{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 Tt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const It=xe(null,"Prefabs");class Ft{constructor(){this.name="PrefabsPlugin",this.dependencies=[St]}build(e){const t=e.getResource(St);e.insertResource(It,new Rt(e.world,t))}}const kt=new Ft;let Dt=null,Bt=0,Lt=0,Ut=0;const Wt=new Float32Array(256);function $t(e){Dt=e,Bt=Dt._malloc(64),Lt=Dt._malloc(64),Ut=Dt._malloc(1024)}function zt(){Dt&&(Bt&&(Dt._free(Bt),Bt=0),Lt&&(Dt._free(Lt),Lt=0),Ut&&(Dt._free(Ut),Ut=0)),Dt=null}function Ot(){if(!Dt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Dt}const Ht={r:1,g:1,b:1,a:1},jt={begin(e){const t=Ot();try{t.HEAPF32.set(e,Bt/4),t.draw_begin(Bt)}catch(e){je(e,"Draw.begin")}},end(){try{Ot().draw_end()}catch(e){je(e,"Draw.end")}},line(e,t,s,n=1){try{Ot().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){je(e,"Draw.line")}},rect(e,t,s,n=!0){try{Ot().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){je(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{Ot().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){je(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,r=32){try{Ot().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){je(e,"Draw.circle")}},circleOutline(e,t,s,n=1,r=32){try{Ot().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){je(e,"Draw.circleOutline")}},texture(e,t,s,n=Ht){try{Ot().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){je(e,"Draw.texture")}},textureRotated(e,t,s,n,r=Ht){try{Ot().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)}catch(e){je(e,"Draw.textureRotated")}},setLayer(e){Ot().draw_setLayer(e)},setDepth(e){Ot().draw_setDepth(e)},getDrawCallCount:()=>Dt?Dt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Dt?Dt.draw_getPrimitiveCount():0,setBlendMode(e){Ot().draw_setBlendMode(e)},setDepthTest(e){Ot().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=Ot();n.HEAPF32.set(s,Lt/4),n.draw_mesh(e,t,Lt)}catch(s){je(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=Ot(),r=st.get(t);if(!r)return;if(jt.setBlendMode(r.blendMode),jt.setDepthTest(r.depthTest),0===r.uniforms.size)return void jt.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,Lt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=Vt(t);if(!(n<0)){if(Ge(s))Wt[o++]=10,Wt[o++]=n,Wt[o++]=s.slot??e++,Wt[o++]=s.textureId;else if("number"==typeof s)Wt[o++]=1,Wt[o++]=n,Wt[o++]=s;else if(Array.isArray(s)){Wt[o++]=s.length,Wt[o++]=n;for(let e=0;e<s.length;e++)Wt[o++]=s[e]}else"w"in s?(Wt[o++]=4,Wt[o++]=n,Wt[o++]=s.x,Wt[o++]=s.y,Wt[o++]=s.z,Wt[o++]=s.w):"z"in s?(Wt[o++]=3,Wt[o++]=n,Wt[o++]=s.x,Wt[o++]=s.y,Wt[o++]=s.z):(Wt[o++]=2,Wt[o++]=n,Wt[o++]=s.x,Wt[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(Wt.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void n.draw_mesh(e,r.shader,Lt);n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),Ut/4),n.draw_meshWithUniforms(e,r.shader,Lt,Ut,o)}catch(s){je(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Xt={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},Nt=new Set;function Vt(e){const t=Xt[e];return void 0!==t?t:(Nt.has(e)||(Nt.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Xt).join(", ")}`)),-1)}const Yt=new Map;function Gt(e,t,s){Yt.set(e,{fn:t,scene:s??""})}function qt(e){Yt.delete(e)}function Jt(){Yt.clear()}var Kt;exports.DataType=void 0,(Kt=exports.DataType||(exports.DataType={}))[Kt.Float=1]="Float",Kt[Kt.Float2=2]="Float2",Kt[Kt.Float3=3]="Float3",Kt[Kt.Float4=4]="Float4",Kt[Kt.Int=5]="Int",Kt[Kt.Int2=6]="Int2",Kt[Kt.Int3=7]="Int3",Kt[Kt.Int4=8]="Int4";let Qt=null,Zt=0,es=0,ts=0;function ss(e){Qt=e,Zt=Qt._malloc(262144),es=Qt._malloc(65536),ts=Qt._malloc(256)}function ns(){Qt&&(Zt&&Qt._free(Zt),es&&Qt._free(es),ts&&Qt._free(ts),Zt=0,es=0,ts=0),Qt=null}function rs(){if(!Qt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Qt}const os={create(e){const t=rs(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,Zt/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,ts,r).set(o),t.geometry_init(s,Zt,n,ts,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,es,n).set(e.indices),t.geometry_setIndices16(s,es,n)}else{new Uint32Array(t.HEAPU8.buffer,es,n).set(e.indices),t.geometry_setIndices32(s,es,n)}}return s},updateVertices(e,t,s=0){const n=rs(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,Zt/4),n.geometry_updateVertices(e,Zt,r,s)},release(e){e>0&&rs().geometry_release(e)},isValid:e=>!(!Qt||e<=0)&&Qt.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return os.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 os.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 os.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 is=null;function as(e){is=e}function ls(){is&&ds.isInitialized()&&ds.shutdown(),is=null}function cs(){if(!is)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return is}const ds={init(e,t){try{return cs().postprocess_init(e,t)}catch(s){return je(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{cs().postprocess_shutdown()}catch(e){je(e,"PostProcess.shutdown")}},resize(e,t){try{cs().postprocess_resize(e,t)}catch(s){je(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return cs().postprocess_addPass(e,t)}catch(t){return je(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{cs().postprocess_removePass(e)}catch(t){je(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{cs().postprocess_setPassEnabled(e,t)}catch(t){je(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return cs().postprocess_isPassEnabled(e)}catch(t){return je(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{cs().postprocess_setUniformFloat(e,t,s)}catch(s){je(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{cs().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){je(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{cs().postprocess_begin()}catch(e){je(e,"PostProcess.begin")}},end(){try{cs().postprocess_end()}catch(e){je(e,"PostProcess.end")}},getPassCount(){try{return cs().postprocess_getPassCount()}catch(e){return je(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!is)return!1;try{return is.postprocess_isInitialized()}catch(e){return je(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{cs().postprocess_setBypass(e)}catch(e){je(e,"PostProcess.setBypass")}},isBypassed(){if(!is)return!0;try{return is.postprocess_isBypassed()}catch(e){return je(e,"PostProcess.isBypassed"),!0}},createBlur:()=>st.createShader(us,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>st.createShader(us,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>st.createShader(us,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>st.createShader(us,"#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")},us="#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 hs;exports.RenderStage=void 0,(hs=exports.RenderStage||(exports.RenderStage={}))[hs.Background=0]="Background",hs[hs.Opaque=1]="Opaque",hs[hs.Transparent=2]="Transparent",hs[hs.Overlay=3]="Overlay";let fs=null,ps=0;function gs(e){fs=e,ps=fs._malloc(64)}function ys(){fs&&ps&&(fs._free(ps),ps=0),fs=null}const ms={init(e,t){fs?.renderer_init(e,t)},resize(e,t){fs?.renderer_resize(e,t)},begin(e,t){if(fs&&ps)try{fs.HEAPF32.set(e,ps/4),fs.renderer_begin(ps,t??0)}catch(e){je(e,"Renderer.begin")}},flush(){try{fs?.renderer_flush()}catch(e){je(e,"Renderer.flush")}},end(){try{fs?.renderer_end()}catch(e){je(e,"Renderer.end")}},submitSprites(e){if(fs)try{fs.renderer_submitSprites(e._cpp)}catch(e){je(e,"Renderer.submitSprites")}},submitBitmapText(e){if(fs)try{fs.renderer_submitBitmapText(e._cpp)}catch(e){je(e,"Renderer.submitBitmapText")}},submitSpine(e){if(fs)try{fs.renderer_submitSpine?.(e._cpp)}catch(e){je(e,"Renderer.submitSpine")}},setStage(e){fs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>fs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){fs?.renderer_releaseTarget(e)},getTargetTexture:e=>fs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>fs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){fs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){fs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){fs?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){fs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>fs?fs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>fs?{drawCalls:fs.renderer_getDrawCalls(),triangles:fs.renderer_getTriangles(),sprites:fs.renderer_getSprites(),text:fs.renderer_getText(),spine:fs.renderer_getSpine?.()??0,meshes:fs.renderer_getMeshes(),culled:fs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let _s=null;function xs(e){_s=e}function ws(){_s=null}const vs={enable(){_s?.gl_enableErrorCheck(!0)},disable(){_s?.gl_enableErrorCheck(!1)},check:e=>_s?.gl_checkErrors(e)??0,diagnose(){_s?.renderer_diagnose()}};class bs{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_||(ms.resize(n,r),ds.isInitialized()&&ds.getPassCount()>0&&ds.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),ms.setViewport(0,0,n,r),ms.clearBuffers(3),ms.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),ms.submitSprites(t),ms.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):ms.submitSpine(t),ms.flush(),this.executeDrawCallbacks(s,o),ms.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;ms.setViewport(n.x,n.y,n.w,n.h),ms.setScissor(n.x,n.y,n.w,n.h,!0),ms.clearBuffers(r),ms.setScissor(0,0,0,0,!1),ms.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),ms.submitSprites(t),ms.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):ms.submitSpine(t),ms.flush(),this.executeDrawCallbacks(s,o),ms.end()}executeDrawCallbacks(e,t){const s=Yt;if(s.size>0){jt.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)}jt.end();for(const e of n)qt(e)}}}const Ss="__scene_transition_overlay__";class Ps{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,he,{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),Gt(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=ds.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){ds.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,he)){const s=this.app_.world.get(e,he);s.persistent=t,this.app_.world.insert(e,he,s)}}}class Ts{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??B.sceneTransitionDuration,r=t.color??{...B.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},Gt(Ss,()=>{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;jt.setLayer(9999),jt.setDepth(9999),jt.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()=>{try{s&&s!==e&&await this.unload(s,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,qt(Ss),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,qt(Ss),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 Ps(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(St)?this.app_.getResource(St):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(St)&&(t.assetServer=this.app_.getResource(St));const n=await wt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,he,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=Cs(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 Ps(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(St)?this.app_.getResource(St):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(St)&&(t.assetServer=this.app_.getResource(St));const n=await wt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,he,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=Cs(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,he)){if(this.app_.world.get(e,he).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())qt(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{ds.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)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n={};let r=!1;if(s.has(e,ne)){const t=s.get(e,ne);n.sprite=t.color.a,t.color={...t.color,a:0},s.insert(e,ne,t),r=!0}if(s.has(e,de)){const t=s.get(e,de);n.spine=t.color.a,t.color={...t.color,a:0},s.insert(e,de,t),r=!0}if(s.has(e,ce)){const t=s.get(e,ce);n.bitmapText=t.color.a,t.color={...t.color,a:0},s.insert(e,ce,t),r=!0}r&&t.savedAlphas.set(e,n)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n=t.savedAlphas.get(e);if(n){if(void 0!==n.sprite&&s.has(e,ne)){const t=s.get(e,ne);t.color={...t.color,a:n.sprite},s.insert(e,ne,t)}if(void 0!==n.spine&&s.has(e,de)){const t=s.get(e,de);t.color={...t.color,a:n.spine},s.insert(e,de,t)}if(void 0!==n.bitmapText&&s.has(e,ce)){const t=s.get(e,ce);t.color={...t.color,a:n.bitmapText},s.insert(e,ce,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{ds.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 Es=xe(null,"SceneManager");function Cs(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Es).getSceneStatus(t)&&s._fn(...n)}}}const As=Ie([ve(Es),we(Pe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Rs={name:"SceneManager",build(e){const t=new Ts(e);e.insertResource(Es,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Es),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,As)}};class Is{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=l(),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 Ne,this.resources_=new Se;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Is}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 He(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(Es).register(e),this}setInitialScene(e){return this.getResource(Es).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new ke(this.world_,this.resources_),this.resources_.insert(Pe,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=l(),this.mainLoop())}quit(){this.running_=!1,Jt();const e=[ws,ys,ls,ns,et,zt];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(Pe);t.delta=e,t.elapsed+=e,t.frameCount++}}const Fs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ks(e,t,s,n,r){const o=e*t/s,i=e;switch(n){case ee.FixedWidth:return o;case ee.FixedHeight:return i;case ee.Expand:return Math.max(o,i);case ee.Shrink:return Math.min(o,i);case ee.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function Ds(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,he);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===Q.Orthographic){if(h=r.orthoSize,l){h=ks(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}u=h*a,d=Ls(-u,u,-h,h,-r.farPlane,r.farPlane)}else d=Ws(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=zs(o.position.x,o.position.y,o.position.z);c.push({entity:e,viewProjection:new Float32Array(Hs(d,f)),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 Bs=new Float32Array(16);function Ls(e,t,s,n,r,o){const i=Bs;i.fill(0);const a=t-e,l=n-s,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(n+s)/l,i[14]=-(o+r)/c,i[15]=1,i}const Us=new Float32Array(16);function Ws(e,t,s,n){const r=Us;r.fill(0);const o=1/Math.tan(e/2),i=s-n;return r[0]=o/t,r[5]=o,r[10]=(n+s)/i,r[11]=-1,r[14]=2*n*s/i,r}const $s=new Float32Array(16);function zs(e,t,s){const n=$s;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 Os=new Float32Array(16);function Hs(e,t){const s=Os;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}const js={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function Xs(e,t,s,n,r,o,i={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,d=o.left+t.x*a,u=o.bottom+e.y*l,h=o.bottom+t.y*l;let f,p,g,y;e.x===t.x?(f=c+s.x-r.x*i.x,g=f+r.x):(f=c+s.x,g=d+n.x),e.y===t.y?(p=u+s.y-r.y*i.y,y=p+r.y):(p=u+s.y,y=h+n.y);const m=Math.max(0,g-f),_=Math.max(0,y-p);return{originX:f+i.x*m,originY:p+i.y*_,width:m,height:_,rect:{left:f,bottom:p,right:g,top:y}}}const Ns=j("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},_dirty:!0,_computedWidth:void 0,_computedHeight:void 0,_layoutManaged:void 0});function Vs(e,t){e.has(t,ne)||e.insert(t,ne,{texture:L,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0})}function Ys(e,t){switch(e){case js.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case js.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case js.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function Gs(e,t,s,n){if(!e.has(t,Ns))return;const r=e.get(t,Ns),o=Ys(s,n);r.anchorMin=o.anchorMin,r.anchorMax=o.anchorMax,r.offsetMin=o.offsetMin,r.offsetMax=o.offsetMax,e.insert(t,Ns,r)}function qs(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Js(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Ks(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(let o=0;o<t.length;o++){const i=t[o],a=n+i;if(e.measureText(a).width>s&&n){if(Js(i.charCodeAt(0))&&n.length>0&&Js(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!Js(n.charCodeAt(t))){e=t;break}e>=0?(r.push(n.substring(0,e+1)),n=n.substring(e+1)+i):(r.push(n),n=i)}else r.push(n),n=i}else n=a}n&&r.push(n)}return r.length>0?r:[""]}function Qs(e){let t=1;for(;t<e;)t*=2;return t}function Zs(e,t){let s=0,n=t;for(;e.has(n,ae);){const t=e.get(n,ae).entity;if(!e.valid(t))break;s++,n=t}return s}function en(e){return e._computedWidth??e.size.x}function tn(e){return e._computedHeight??e.size.y}function sn(e,t,s){let n=t;for(;e.has(n,ae);){const t=e.get(n,ae).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function nn(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function rn(e,t,s,n,r){if(!e.has(t,Ns))return;const o=e.get(t,Ns),i=Xs(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s,o.pivot),a=i.rect.right-i.rect.left,l=i.rect.top-i.rect.bottom;if(o._computedWidth=a,o._computedHeight=l,e.has(t,ne)){const s=e.get(t,ne);s.size.x===a&&s.size.y===l||(s.size.x=a,s.size.y=l,e.insert(t,ne,s))}if(!o._layoutManaged&&e.has(t,te)){const s=e.get(t,te);s.position.x=i.originX-n,s.position.y=i.originY-r,e.insert(t,te,s)}}function on(e){const t=Object.keys(e),s=t.map(t=>e[t]);return{take(e){const n={};for(let r=0;r<t.length;r++)n[t[r]]=s[r](e);return n},changed(e,n){for(let r=0;r<t.length;r++)if(e[t[r]]!==s[r](n))return!0;return!1},update(e,n){for(let r=0;r<t.length;r++)e[t[r]]=s[r](n)}}}const an={r:.3,g:.5,b:.8,a:1},ln={Left:0,Center:1,Right:2},cn={Top:0,Middle:1,Bottom:2},dn={Visible:0,Clip:1,Ellipsis:2},un=j("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:ln.Left,verticalAlign:cn.Top,wordWrap:!0,overflow:dn.Visible,lineHeight:1.2});class hn{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=a(B.textCanvasSize,B.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,Qs(this.frameMaxW_)),e.height=Math.max(e.height,Qs(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Qs(this.frameMaxW_),e.height=Qs(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const 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=Ks(s,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),f=r?Math.ceil(o):u+2*d,p=r?Math.ceil(i):h+2*d;if(r&&e.overflow===dn.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)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(n.width<f||n.height<p)&&(n.width=Math.max(n.width,Qs(f)),n.height=Math.max(n.height,Qs(p)));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;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}, ${y}, ${m}, ${_})`,r&&e.overflow===dn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const x=l.length*c;let w;if(r)switch(e.verticalAlign){case cn.Top:w=d;break;case cn.Middle:w=d+(p-2*d-x)/2;break;case cn.Bottom:w=p-x-d;break;default:w=d}else w=d;let v=w;for(const t of l){let n;switch(e.align){case ln.Left:n=d;break;case ln.Center:n=f/2;break;case ln.Right:n=f-d;break;default:n=d}s.fillText(t,n,v),v+=c}r&&e.overflow===dn.Clip&&s.restore();const b=s.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 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()}measureWidth(e){let t=0;for(const s of e)t=Math.max(t,this.ctx.measureText(s).width);return t}mapAlign(e){switch(e){case ln.Left:return"left";case ln.Center:return"center";case ln.Right:return"right"}}}const fn=on({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?en(e.uiRect):0,containerHeight:e=>e.uiRect?tn(e.uiRect):0});class pn{build(e){q("Text",un);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new hn(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ie([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,un));for(const e of r.keys())if(!n.valid(e)||!n.has(e,un)){if(n.valid(e)&&n.has(e,ne)){const t=n.get(e,ne);t.texture=L,n.insert(e,ne,t)}r.delete(e)}const e=n.getEntitiesWithComponents([un]);for(const t of e){const e=n.get(t,un),o=n.has(t,Ns)?n.get(t,Ns):null,i={text:e,uiRect:o},a=r.get(t);if(a&&!fn.changed(a,i))continue;Vs(n,t);const l=s.renderForEntity(t,e,o),c=n.get(t,ne);c.texture=l.textureHandle,c.size.x=l.width,c.size.y=l.height,c.uvOffset.x=0,c.uvOffset.y=0,c.uvScale.x=1,c.uvScale.y=1,n.insert(t,ne,c),r.set(t,fn.take(i))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const gn=new pn,yn=j("UIMask",{enabled:!0,mode:"scissor"});function mn(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 _n(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],f=e[10],p=e[11],g=e[12],y=e[13],m=e[14],_=e[15],x=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,M=u*y-h*g,T=u*m-f*g,E=u*_-p*g,C=h*m-f*y,A=h*_-p*y,R=f*_-p*m;let I=x*R-w*A+v*C+b*E-S*T+P*M;return 0===I||(I=1/I,s[0]=(l*R-c*A+d*C)*I,s[1]=(o*A-r*R-i*C)*I,s[2]=(y*P-m*S+_*b)*I,s[3]=(f*S-h*P-p*b)*I,s[4]=(c*E-a*R-d*T)*I,s[5]=(n*R-o*E+i*T)*I,s[6]=(m*v-g*P-_*w)*I,s[7]=(u*P-f*v+p*w)*I,s[8]=(a*A-l*E+d*M)*I,s[9]=(r*E-n*A-i*M)*I,s[10]=(g*S-y*v+_*x)*I,s[11]=(h*v-u*S-p*x)*I,s[12]=(l*T-a*C-c*M)*I,s[13]=(n*C-r*T+o*M)*I,s[14]=(y*w-g*b-m*x)*I,s[15]=(u*b-h*w+f*x)*I),s}function xn(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 wn(e,t){return 2*Math.atan2(e,t)}function vn(e,t,s,n,r,o,i){const a=s[0]*e+s[4]*t+s[12],l=s[1]*e+s[5]*t+s[13],c=s[3]*e+s[7]*t+s[15];return[n+(.5*(a/c)+.5)*o,r+(.5*(l/c)+.5)*i]}function bn(e,t,s,n,r,o,i,a,l,c){const d=wn(l,c),u=Math.sin(-d),h=Math.cos(-d),f=e-s,p=t-n,g=f*h-p*u+s,y=f*u+p*h+n;return g>=s-r*i&&g<=s+r*(1-i)&&y>=n-o*a&&y<=n+o*(1-a)}function Sn(e,t,s,n,r,o,i){if(!e.has(t,Ns)||!e.has(t,se))return null;const a=e.get(t,Ns),l=e.get(t,se),c=en(a)*l.scale.x,d=tn(a)*l.scale.y,u=l.position.x,h=l.position.y,f=a.pivot.x,p=a.pivot.y,g=-c*f,y=c*(1-f),m=-d*p,_=d*(1-p),x=wn(l.rotation.z,l.rotation.w),w=Math.cos(x),v=Math.sin(x),b=[[u+g*w-m*v,h+g*v+m*w],[u+y*w-m*v,h+y*v+m*w],[u+y*w-_*v,h+y*v+_*w],[u+g*w-_*v,h+g*v+_*w]];let S=1/0,P=1/0,M=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=vn(e,t,s,n,r,o,i);S=Math.min(S,a),P=Math.min(P,l),M=Math.max(M,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(P),w:Math.round(M-S),h:Math.round(T-P)}}function Pn(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([yn]);if(0===l.length)return;const c=[],d=[],u=new Set,h=new Set;for(const e of l){const s=t.get(e,yn);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;sn(t,e,e=>{if(r.has(e)){if("scissor"===t.get(e,yn).mode)return s=!1,!0}return!1}),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,yn).mode){const e=Sn(t,s,o,i,a,l,c);e&&(n=mn(d,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),u(s,n)}}for(const e of d){const s=Sn(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;sn(t,e,e=>!!r.has(e)&&(s=!1,!0)),s&&o.push(e)}let i=1,a=!1;function l(){return i>255?(a||console.warn("Stencil mask overflow"),a=!0,null):i++}function c(t,n){if(a)return;e.renderer_setEntityStencilMask(t,n);const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),d(t,n)}function d(t,n){if(a)return;const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),d(t,n)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,s,d,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class Mn{build(e){if(q("UIMask",yn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Pn(e.wasmModule,e.world))}}const Tn=new Mn,En=j("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),Cn=j("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),An={Normal:0,Hovered:1,Pressed:2,Disabled:3},Rn=j("Button",{state:An.Normal,transition:null});class In{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 Fn=xe(new In,"UIEvents"),kn=X("ScreenSpace"),Dn=on({anchorMinX:e=>e.anchorMin.x,anchorMinY:e=>e.anchorMin.y,anchorMaxX:e=>e.anchorMax.x,anchorMaxY:e=>e.anchorMax.y,offsetMinX:e=>e.offsetMin.x,offsetMinY:e=>e.offsetMin.y,offsetMaxX:e=>e.offsetMax.x,offsetMaxY:e=>e.offsetMax.y,sizeX:e=>e.size.x,sizeY:e=>e.size.y});function Bn(e,t,s,n,r,o){if(!e.has(t,Ns))return;const i=e.get(t,Ns),a=Xs(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,s,i.pivot),l=a.rect.right-a.rect.left,c=a.rect.top-a.rect.bottom;if(i._computedWidth=l,i._computedHeight=c,e.has(t,ne)){const s=e.get(t,ne);s.size.x===l&&s.size.y===c||(s.size.x=l,s.size.y=c,e.insert(t,ne,s))}if(!i._layoutManaged){const s=e.get(t,te);o?(s.position.x=a.originX,s.position.y=a.originY):(s.position.x=a.originX-n,s.position.y=a.originY-r),e.insert(t,te,s)}if(!e.has(t,le))return;const d=e.get(t,le);if(d&&d.entities)for(const t of d.entities)e.valid(t)&&Bn(e,t,a.rect,a.originX,a.originY,!1)}class Ln{build(e){q("UIRect",Ns);const t=e.world,s=new Map,n=new Map;let r=NaN,o=NaN,i=NaN,a=NaN;function l(e){let s=n.get(e);return void 0!==s||(s=function(e,t){let s=t;for(;;){if(e.has(s,kn))return s;if(!e.has(s,ae))return null;const t=e.get(s,ae);if(!e.valid(t.entity))return null;s=t.entity}}(t,e),n.set(e,s)),s}function c(e){if(n.delete(e),!t.has(e,le))return;const s=t.get(e,le);if(s&&s.entities)for(const e of s.entities)t.valid(e)&&c(e)}e.addSystemToSchedule(exports.Schedule.PreUpdate,Ie([we(Ve)],e=>{if(!e.valid)return;const d={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},u=.5*(d.left+d.right),h=.5*(d.bottom+d.top),f=r!==e.worldLeft||o!==e.worldBottom||i!==e.worldRight||a!==e.worldTop;r=e.worldLeft,o=e.worldBottom,i=e.worldRight,a=e.worldTop;const p=new Set;if(f){n.clear();const e=t.getEntitiesWithComponents([kn,Ns,te]);for(const t of e)p.add(t)}for(const e of s.keys())t.valid(e)&&t.has(e,Ns)||(s.delete(e),n.delete(e));const g=t.getEntitiesWithComponents([Ns]);for(const e of g){const n=t.get(e,Ns),r=s.get(e);if(n._dirty||!r||Dn.changed(r,n)){n._dirty=!1,c(e);const t=l(e);null!==t&&p.add(t)}}for(const e of p)Bn(t,e,d,u,h,!0);for(const e of g){const n=t.get(e,Ns),r=s.get(e);r?Dn.update(r,n):s.set(e,Dn.take(n))}},{name:"UILayoutSystem"}))}}const Un=new Ln,Wn=function(){const e=new Float32Array(16),t=new Float32Array(16);let s=!0;return{update(e){for(let n=0;n<16;n++)if(t[n]!==e[n]){t.set(e),s=!0;break}},getInverse:t=>(s&&(_n(t,e),s=!1),e)}}();function $n(e,t,s,n){let r=!1;return sn(e,t,t=>{if(!e.has(t,yn))return!1;if(!e.get(t,yn).enabled||!e.has(t,Ns)||!e.has(t,se))return!1;const o=e.get(t,se),i=e.get(t,Ns),a=en(i)*o.scale.x,l=tn(i)*o.scale.y;return!bn(s,n,o.position.x,o.position.y,a,l,i.pivot.x,i.pivot.y,o.rotation.z,o.rotation.w)&&(r=!0,!0)}),r}function zn(e,t,s,n){t.emit(s,n,s),sn(e,s,r=>{if(!e.has(r,En))return!1;const o=e.get(r,En);return o.enabled&&t.emit(r,n,s),o.blockRaycast})}class On{build(e){q("Interactable",En),q("Button",Rn);const t=e.world,s=new In;e.insertResource(Fn,s);let n=null,r=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ie([we(Be),we(Ve)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([Cn]);for(const e of i){const s=t.get(e,Cn);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a="undefined"!=typeof window&&window.devicePixelRatio||1,l=e.mouseX*a,c=o.screenH-e.mouseY*a;Wn.update(o.viewProjection);const d=xn(l,c,Wn.getInverse(o.viewProjection),o.vpX,o.vpY,o.vpW,o.vpH);o.worldMouseX=d.x,o.worldMouseY=d.y;const u=t.getEntitiesWithComponents([En,Ns,se]);let h=null,f=-1/0;for(const e of u){nn(t,e,Cn);const s=t.get(e,En);if(!s.enabled)continue;if(!s.raycastTarget)continue;const n=t.get(e,se),r=t.get(e,Ns),o=en(r)*n.scale.x,i=tn(r)*n.scale.y;if(bn(d.x,d.y,n.position.x,n.position.y,o,i,r.pivot.x,r.pivot.y,n.rotation.z,n.rotation.w)){if($n(t,e,d.x,d.y))continue;let s=0;t.has(e,ne)&&(s=t.get(e,ne).layer),s>f&&(f=s,h=e)}}if(null===n||t.valid(n)||(n=null),n!==h){if(null!==n&&t.valid(n)&&t.has(n,Cn)){t.get(n,Cn).hovered=!1,s.emit(n,"hover_exit")}if(null!==h){t.get(h,Cn).hovered=!0,s.emit(h,"hover_enter")}n=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,Cn);e.pressed=!0,e.justPressed=!0,r=h,zn(t,s,h,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Cn)){const e=t.get(r,Cn);e.pressed=!1,e.justReleased=!0,zn(t,s,r,"release"),r===n&&zn(t,s,r,"click")}r=null}},{name:"UIInteractionSystem"}));const o=new Set;e.addSystemToSchedule(exports.Schedule.Update,Ie([],()=>{const e=t.getEntitiesWithComponents([Rn]);for(const s of e){if(nn(t,s,En,{enabled:!0}),!t.has(s,Cn))continue;const e=t.get(s,Cn),n=t.get(s,Rn),r=t.get(s,En),i=!o.has(s),a=n.state;if(r.enabled?e.pressed?n.state=An.Pressed:e.hovered?n.state=An.Hovered:n.state=An.Normal:n.state=An.Disabled,i&&o.add(s),(i||a!==n.state)&&n.transition&&t.has(s,ne)){const o=t.get(s,ne);o.color=qs(n.transition,r.enabled,e.pressed,e.hovered),t.insert(s,ne,o)}}},{name:"ButtonSystem"}))}}const Hn=new On,jn=j("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}),Xn=j("Focusable",{tabIndex:0,isFocused:!1});class Nn{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 Vn=xe(new Nn,"FocusManager");class Yn{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){q("TextInput",jn);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=a(B.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let i=!1,l=!0,c=0,d=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 h=u;function f(){const t=e.getResource(Vn);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,jn)?n:null}const p=()=>{i||null===f()||x()},g=()=>{i=!0},y=()=>{i=!1,x()},m=t=>{const n=f();if(null===n)return;if("Escape"===t.key)return void w();const r=s.get(n,jn);if("Enter"===t.key&&!r.multiline){t.preventDefault();return e.getResource(Fn).emit(n,"submit"),void w()}let o=r.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,r.cursorPos-1):"ArrowRight"===t.key?o=Math.min(r.value.length,r.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=r.value.length),o!==r.cursorPos&&(r.cursorPos=o,h.selectionStart=o,h.selectionEnd=o,r.dirty=!0,v())},_=()=>{const t=f();if(null!==t){const n=s.get(t,jn);n.focused=!1,n.dirty=!0;e.getResource(Vn).blur()}};function x(){const t=f();if(null===t)return;const n=s.get(t,jn);if(n.readOnly)return;let r=h.value;if(n.maxLength>0&&r.length>n.maxLength&&(r=r.substring(0,n.maxLength),h.value=r),r!==n.value){n.value=r;e.getResource(Fn).emit(t,"change")}n.cursorPos=h.selectionStart??r.length,n.dirty=!0,v()}function w(){const t=f();if(null!==t){const e=s.get(t,jn);e.focused=!1,e.dirty=!0}e.getResource(Vn).blur(),h.blur()}function v(){l=!0,c=0}h.addEventListener("input",p),h.addEventListener("compositionstart",g),h.addEventListener("compositionend",y),h.addEventListener("keydown",m),h.addEventListener("blur",_),this.cleanupListeners_=()=>{h.removeEventListener("input",p),h.removeEventListener("compositionstart",g),h.removeEventListener("compositionend",y),h.removeEventListener("keydown",m),h.removeEventListener("blur",_),h.remove();const e=t.getResourceManager();for(const t of n.values())e.releaseTexture(t);n.clear()};let b=null;function S(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 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,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,h=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,h,a-2*g);let t=g;for(const s of e)o.fillText(s,g,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(h,g,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,s,n;if(i.multiline){const e=Ks(o,i.value,a-2*g);let r=0,l=0,c=0;for(let t=0;t<e.length;t++){const s=e[t].length;if(r+s>=i.cursorPos){l=t,c=i.cursorPos-r;break}r+=s,t<e.length-1&&r<i.value.length&&"\n"===i.value[r]&&r++,l=t+1,c=0}const d=l<e.length?e[l].substring(0,c):"";t=g+o.measureText(d).width,s=g+l*p,n=p}else t=g+o.measureText(e).width,s=(c-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 y=o.getImageData(0,0,a,c),m=new Uint8Array(y.data.buffer),_=t.getResourceManager(),x=t._malloc(m.length);t.HEAPU8.set(m,x);const w=n.get(e);void 0!==w&&_.releaseTexture(w);const v=_.createTexture(a,c,x,m.length,1,!0);n.set(e,v),t._free(x);const b=s.get(e,ne);b.texture=v,b.size.x=a,b.size.y=c,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},s.insert(e,ne,b)}e.addSystemToSchedule(exports.Schedule.Update,Ie([we(Vn)],e=>{const t=s.getEntitiesWithComponents([jn]);for(const e of t)nn(s,e,Xn,{tabIndex:0,isFocused:!1}),nn(s,e,En,{enabled:!0,blockRaycast:!0});const n=f();if(n!==b){if(null!==b&&s.valid(b)&&s.has(b,jn)){const e=s.get(b,jn);e.focused=!1,e.dirty=!0,h.blur()}null!==n&&function(e){const t=s.get(e,jn);t.readOnly||(t.focused=!0,t.dirty=!0,h.value=t.value,h.selectionStart=t.cursorPos,h.selectionEnd=t.cursorPos,h.focus(),v())}(n),b=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(exports.Schedule.PreUpdate,Ie([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let r=0===d?0:(e-d)/1e3;d=e,r=Math.min(r,.1);const o=f();if(null!==o&&(c+=r,c>=.5)){c-=.5,l=!l;s.get(o,jn).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,jn)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([jn,Ns]);for(const e of a){const t=s.get(e,jn);if(!t.dirty)continue;const n=s.get(e,Ns),r=Math.ceil(n.size.x),o=Math.ceil(n.size.y);r<=0||o<=0||(Vs(s,e),S(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Gn=new Yn,qn={Simple:0,Sliced:1,Tiled:2,Filled:3},Jn={Horizontal:0,Vertical:1},Kn={Left:0,Right:1,Bottom:2,Top:3},Qn=j("Image",{texture:L,color:{r:1,g:1,b:1,a:1},imageType:qn.Simple,fillMethod:Jn.Horizontal,fillOrigin:Kn.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Zn=on({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,layer:e=>e.image.layer,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?en(e.uiRect):0,rectHeight:e=>e.uiRect?tn(e.uiRect):0,enabled:e=>e.image.enabled});const er=new class{build(e){q("Image",Qn);const t=e.world,s=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ie([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,Qn)||s.delete(e);const e=t.getEntitiesWithComponents([Qn]);for(const n of e){const e=t.get(n,Qn),r=t.has(n,Ns)?t.get(n,Ns):null,o={image:e,uiRect:r},i=s.get(n);if(i&&!Zn.changed(i,o))continue;Vs(t,n);const a=t.get(n,ne);if(e.enabled){if(a.texture=e.texture,a.color.r=e.color.r,a.color.g=e.color.g,a.color.b=e.color.b,a.color.a=e.color.a,a.layer=e.layer,a.material=e.material,r&&(a.size.x=en(r),a.size.y=tn(r)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===qn.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===Jn.Horizontal?e.fillOrigin===Kn.Left?(a.uvScale.x=t,a.size.x=s*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=s*t):e.fillOrigin===Kn.Bottom?(a.uvScale.y=t,a.size.y=n*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=n*t)}else e.imageType===qn.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale.x=a.size.x/e.tileSize.x,a.uvScale.y=a.size.y/e.tileSize.y);t.insert(n,ne,a),s.set(n,Zn.take(o))}else a.color.a=0,t.insert(n,ne,a),s.set(n,Zn.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},tr=j("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),sr=j("ToggleGroup",{allowSwitchOff:!1});const nr=new class{build(e){q("Toggle",tr),q("ToggleGroup",sr);const t=e.world,s=new Set;e.addSystemToSchedule(exports.Schedule.Update,Ie([we(Fn)],e=>{const n=t.getEntitiesWithComponents([tr]),r=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,tr);n.isOn&&0!==n.group&&t.valid(n.group)&&(r.has(n.group)?n.isOn=!1:r.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,tr);if(0!==s.group&&t.valid(s.group)){let t=o.get(s.group);t||(t=[],o.set(s.group,t)),t.push(e)}}for(const s of n){if(nn(t,s,En,{enabled:!0}),!t.has(s,Cn))continue;const n=t.get(s,Cn),r=t.get(s,tr),i=t.get(s,En);if(n.justPressed&&i.enabled){const n=r.group,i=0!==n&&t.valid(n)&&t.has(n,sr);if(r.isOn&&i){if(!t.get(n,sr).allowSwitchOff)continue}if(r.isOn=!r.isOn,r.isOn&&i){const r=o.get(n);if(r)for(const n of r){if(n===s)continue;const r=t.get(n,tr);r.isOn&&(r.isOn=!1,e.emit(n,"change"))}}e.emit(s,"change")}if(r.graphicEntity&&t.valid(r.graphicEntity)&&t.has(r.graphicEntity,ne)){const e=t.get(r.graphicEntity,ne);e.enabled=r.isOn,t.insert(r.graphicEntity,ne,e)}if(r.transition&&t.has(s,ne)){const e=t.get(s,ne);e.color=qs(r.transition,i.enabled,n.pressed,n.hovered),t.insert(s,ne,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},rr=js,or=j("ProgressBar",{value:0,fillEntity:0,direction:js.LeftToRight});const ir=new class{build(e){q("ProgressBar",or);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ie([],()=>{const e=t.getEntitiesWithComponents([or,Ns]);for(const s of e){const e=t.get(s,or);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=Math.max(0,Math.min(1,e.value));Gs(t,e.fillEntity,e.direction,n)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}},ar=j("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),lr=j("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}});const cr=new class{build(e){q("Draggable",ar),q("DragState",lr);const t=e.world,s=e.getResource(Fn);let n=null,r={x:0,y:0},o=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ie([we(Be),we(Ve)],(e,i)=>{if(!i.valid)return;const a={x:i.worldMouseX,y:i.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([ar,Cn]);let s=null,o=-1/0,i=-1;for(const n of e){if(!t.get(n,ar).enabled)continue;if(t.get(n,Cn).hovered){let e=0;t.has(n,ne)&&(e=t.get(n,ne).layer);const r=Zs(t,n);(e>o||e===o&&r>=i)&&(o=e,i=r,s=n)}}if(null!==s){n=s,r={x:a.x,y:a.y},t.has(s,lr)||t.insert(s,lr);const e=t.get(s,lr),o=t.get(s,se);e.startWorldPos={x:o.position.x,y:o.position.y},e.currentWorldPos={x:o.position.x,y:o.position.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==n&&!e.isMouseButtonDown(0)){if(t.valid(n)&&t.has(n,lr)){t.get(n,lr).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=a.x-r.x,l=a.y-r.y,c=Math.sqrt(e*e+l*l),d=t.get(n,ar);if(c*(i.vpW/(i.worldRight-i.worldLeft))>=d.dragThreshold){o=n,n=null;t.get(o,lr).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,lr))return void(o=null);const n=t.get(o,lr),r=t.get(o,ar),i=a.x-n.pointerStartWorld.x,l=a.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+i,d=n.startWorldPos.y+l;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,f=n.currentWorldPos.y;if(n.deltaWorld={x:c-h,y:d-f},n.currentWorldPos={x:c,y:d},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:d-n.startWorldPos.y},t.has(o,te)){const e=function(e,t,s,n){if(!e.has(t,ae))return{x:s,y:n};const r=e.get(t,ae).entity;if(!e.valid(r)||!e.has(r,se))return{x:s,y:n};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=wn(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,te);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,te,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},dr=j("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135});const ur=new class{build(e){q("ScrollView",dr);const t=e.world,s=new Map;let n=0;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ie([we(Be),we(Ve)],(e,r)=>{const o=performance.now()/1e3,i=n>0?Math.min(o-n,.05):0;if(n=o,!r.valid)return;for(const[e]of s)t.valid(e)||s.delete(e);const a={x:r.worldMouseX,y:r.worldMouseY},l=t.getEntitiesWithComponents([dr,Ns]);for(const n of l){nn(t,n,En,{enabled:!0,blockRaycast:!0}),nn(t,n,yn,{enabled:!0,mode:"scissor"});const r=t.get(n,dr),o=t.get(n,Ns);let l=s.get(n);l||(l={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0},s.set(n,l));const c=t.has(n,Cn)?t.get(n,Cn):null;if(c?.justPressed&&(l.isDragging=!0,l.lastWorldX=a.x,l.lastWorldY=a.y,l.velocityX=0,l.velocityY=0),l.isDragging&&e.isMouseButtonDown(0)){const e=a.x-l.lastWorldX,t=a.y-l.lastWorldY;if(r.horizontalEnabled){r.scrollX-=e;const t=i>0?-e/i:0;l.velocityX=.8*l.velocityX+.2*t}if(r.verticalEnabled){r.scrollY-=t;const e=i>0?-t/i:0;l.velocityY=.8*l.velocityY+.2*e}l.lastWorldX=a.x,l.lastWorldY=a.y}if(l.isDragging&&e.isMouseButtonReleased(0)&&(l.isDragging=!1),c?.hovered){const t=e.getScrollDelta();r.verticalEnabled&&0!==t.y&&(r.scrollY+=.1*t.y,l.velocityY=0),r.horizontalEnabled&&0!==t.x&&(r.scrollX+=.1*t.x,l.velocityX=0)}if(!l.isDragging&&r.inertia&&i>0){const e=Math.pow(r.decelerationRate,60*i);r.horizontalEnabled&&Math.abs(l.velocityX)>.1?(r.scrollX+=l.velocityX*i,l.velocityX*=e):l.velocityX=0,r.verticalEnabled&&Math.abs(l.velocityY)>.1?(r.scrollY+=l.velocityY*i,l.velocityY*=e):l.velocityY=0}const d=en(o),u=tn(o),h=Math.max(0,r.contentWidth-d),f=Math.max(0,r.contentHeight-u),p=r.scrollX,g=r.scrollY;if(r.scrollX=Math.max(0,Math.min(r.scrollX,h)),r.scrollY=Math.max(0,Math.min(r.scrollY,f)),r.scrollX!==p&&(l.velocityX=0),r.scrollY!==g&&(l.velocityY=0),0!==r.contentEntity&&t.valid(r.contentEntity)&&t.has(r.contentEntity,te)){const e=t.get(r.contentEntity,te);e.position.x=-r.scrollX,e.position.y=r.scrollY,t.insert(r.contentEntity,te,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UIInteractionSystem"]})}},hr=js,fr=j("Slider",{value:0,minValue:0,maxValue:1,direction:js.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});const pr=new class{build(e){q("Slider",fr);const t=e.world;let s=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ie([we(Be),we(Ve),we(Fn)],(e,n,r)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=n.worldMouseX,i=n.worldMouseY,a=t.getEntitiesWithComponents([fr,Ns,se]);for(const n of a){nn(t,n,En,{enabled:!0,blockRaycast:!0});const a=t.get(n,fr),l=t.get(n,Ns),c=t.get(n,se),d=t.has(n,Cn)?t.get(n,Cn):null,u=a.handleEntity;if(0!==u&&t.valid(u)&&(nn(t,u,En,{enabled:!0,blockRaycast:!1}),t.has(u,En))){const e=t.get(u,En);e.blockRaycast&&(e.blockRaycast=!1,t.insert(u,En,e))}let h=d?.justPressed??!1;if(!h&&0!==u&&t.valid(u)&&t.has(u,Cn)){h=t.get(u,Cn).justPressed}if(h&&(s=n),s===n&&e.isMouseButtonDown(0)){const e=en(l),s=tn(l),d=e*c.scale.x,u=s*c.scale.y,h=wn(c.rotation.z,c.rotation.w),f=Math.sin(-h),p=Math.cos(-h),g=o-c.position.x,y=i-c.position.y,m=g*p-y*f,_=g*f+y*p,x=-l.pivot.x*d,w=-l.pivot.y*u;let v;switch(a.direction){case js.LeftToRight:v=d>0?(m-x)/d:0;break;case js.RightToLeft:v=d>0?1-(m-x)/d:0;break;case js.BottomToTop:v=u>0?(_-w)/u:0;break;case js.TopToBottom:v=u>0?1-(_-w)/u:0}v=Math.max(0,Math.min(1,v));let b=a.minValue+v*(a.maxValue-a.minValue);a.wholeNumbers&&(b=Math.round(b));const S=a.value;a.value=Math.max(a.minValue,Math.min(a.maxValue,b)),t.insert(n,fr,a),a.value!==S&&r.emit(n,"change")}s===n&&e.isMouseButtonReleased(0)&&(s=null);const f=a.maxValue-a.minValue,p=f>0?(a.value-a.minValue)/f:0,g=en(l),y=tn(l),m=l.pivot,_={left:-m.x*g,bottom:-m.y*y,right:(1-m.x)*g,top:(1-m.y)*y};if(0!==a.fillEntity&&t.valid(a.fillEntity)&&(Gs(t,a.fillEntity,a.direction,p),rn(t,a.fillEntity,_,0,0)),0!==a.handleEntity&&t.valid(a.handleEntity)){if(t.has(a.handleEntity,Ns)){const e=t.get(a.handleEntity,Ns);switch(e.offsetMin={x:0,y:0},e.offsetMax={x:0,y:0},a.direction){case js.LeftToRight:e.anchorMin={x:p,y:0},e.anchorMax={x:p,y:1};break;case js.RightToLeft:e.anchorMin={x:1-p,y:0},e.anchorMax={x:1-p,y:1};break;case js.BottomToTop:e.anchorMin={x:0,y:p},e.anchorMax={x:1,y:p};break;case js.TopToBottom:e.anchorMin={x:0,y:1-p},e.anchorMax={x:1,y:1-p}}t.insert(a.handleEntity,Ns,e)}rn(t,a.handleEntity,_,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}};const gr=new class{build(e){q("Focusable",Xn);const t=e.world,s=new Nn;e.insertResource(Vn,s),e.addSystemToSchedule(exports.Schedule.Update,Ie([we(Be),we(Fn)],(e,n)=>{null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const r=t.getEntitiesWithComponents([Xn]);for(const e of r){if(!t.has(e,Cn))continue;t.get(e,Cn).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const n=function(){const e=[];for(const s of r){if(!t.valid(s))continue;if(t.has(s,En)){if(!t.get(s,En).enabled)continue}const n=t.get(s,Xn);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,Xn)){t.get(r,Xn).isFocused=!1,n.emit(r,"blur",r)}s.focus(e);t.get(e,Xn).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}},yr=j("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function mr(){return s()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:s,screenWidth:n,screenHeight:r}=t;return{top:s.top,bottom:r-s.bottom,left:s.left,right:n-s.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}const _r=new class{build(e){q("SafeArea",yr);const t=e.world;let n=mr(),r=!0,o=0,i=0;if(s()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=mr(),r=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=mr(),r=!0});e.addSystemToSchedule(exports.Schedule.PreUpdate,Ie([we(Ve)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===i||(o=e.screenH,i=a,r=!0),!r)return;r=!1;const l="undefined"!=typeof window&&window.devicePixelRatio||1,c=s()?a/e.screenH:l*a/e.screenH,d=t.getEntitiesWithComponents([yr,Ns]);for(const e of d){const s=t.get(e,yr),r=t.get(e,Ns),o=s.applyTop?n.top*c:0,i=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let d=!1;r.offsetMin.x===a&&r.offsetMin.y===i||(r.offsetMin={x:a,y:i},d=!0),r.offsetMax.x===-l&&r.offsetMax.y===-o||(r.offsetMax={x:-l,y:-o},d=!0),d&&t.insert(e,Ns,r)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},xr=j("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let wr=null;const vr=new class{build(e){q("ListView",xr);const t=e.world,s=new Map;wr=s,e.addSystemToSchedule(exports.Schedule.PreUpdate,Ie([we(Be)],e=>{for(const[e,n]of s)if(!t.valid(e)){for(const e of n.itemEntities.values())t.valid(e)&&t.despawn(e);s.delete(e)}const n=t.getEntitiesWithComponents([xr,Ns]);for(const r of n){nn(t,r,En,{enabled:!0,blockRaycast:!0}),nn(t,r,yn,{enabled:!0,mode:"scissor"});let n=s.get(r);n||(n={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},s.set(r,n));const o=t.get(r,xr),i=t.get(r,Ns),a=i._computedHeight??i.size.y,l=i._computedWidth??i.size.x,c=t.has(r,Cn)?t.get(r,Cn):null;if(c?.hovered){const t=e.getScrollDelta();0!==t.y&&(o.scrollY+=.1*t.y)}const d=Math.max(0,o.itemCount*o.itemHeight-a);o.scrollY=Math.max(0,Math.min(o.scrollY,d));const u=Math.max(0,Math.floor(o.scrollY/o.itemHeight)-o.overscan),h=Math.min(o.itemCount,Math.ceil((o.scrollY+a)/o.itemHeight)+o.overscan);for(const[e,s]of n.itemEntities)(e<u||e>=h)&&(t.valid(s)&&t.despawn(s),n.itemEntities.delete(e));for(let e=u;e<h;e++){let s=n.itemEntities.get(e);if(s&&t.valid(s)||(s=t.spawn(),t.insert(s,ue,{value:`ListItem_${e}`}),t.insert(s,Ns,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:l,y:o.itemHeight},pivot:{x:.5,y:1}}),t.setParent(s,r),n.itemEntities.set(e,s),n.renderer&&n.renderer(e,s)),t.has(s,te)){const n=t.get(s,te);n.position.y=-(e*o.itemHeight-o.scrollY),t.insert(s,te,n)}}n.visibleStart=u,n.visibleEnd=h}},{name:"ListViewSystem"}))}},br=j("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const Sr=new class{build(e){q("Dropdown",br);const t=e.world,s=new Map;function n(e,s,n){s.isOpen=!0,n.highlightIndex=s.selectedIndex;const r=s.listEntity;if(0===r||!t.valid(r))return;l(r,!0),t.has(r,yn)||t.insert(r,yn,{enabled:!0,mode:"scissor"}),a(n);const o=t.has(r,Ns)?t.get(r,Ns):null,i=o?o.size.x:160;for(let e=0;e<s.options.length;e++){const o=t.spawn();t.insert(o,ue,{value:`Option_${e}`}),t.insert(o,Ns,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:i,y:30},pivot:{x:.5,y:1}}),t.insert(o,te,{position:{x:0,y:-30*e,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(o,un,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:1,g:1,b:1,a:1},align:ln.Left,verticalAlign:cn.Middle,wordWrap:!1,overflow:dn.Clip,lineHeight:1.2}),t.insert(o,ne,{texture:0,color:{r:1,g:1,b:1,a:0},size:{x:i,y:30},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,En,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,r),n.optionEntities.push(o)}o&&(o.size.y=30*s.options.length,t.insert(r,Ns,o)),c(n)}function r(e,t,s){t.isOpen=!1,a(s),l(t.listEntity,!1)}function o(e,t,s,n,o){t.selectedIndex=n,r(0,t,s),o.emit(e,"change")}function i(e){const s=e.labelEntity;if(0===s||!t.valid(s))return;if(!t.has(s,un))return;const n=t.get(s,un),r=e.selectedIndex>=0&&e.selectedIndex<e.options.length?e.options[e.selectedIndex]:"";n.content!==r&&(n.content=r,t.insert(s,un,n))}function a(e){for(const s of e.optionEntities)t.valid(s)&&t.despawn(s);e.optionEntities=[]}function l(e,s){if(0!==e&&t.valid(e)){if(t.has(e,En)){const n=t.get(e,En);n.enabled=s,t.insert(e,En,n)}if(t.has(e,ne)){const n=t.get(e,ne);n.enabled=s,t.insert(e,ne,n)}}}function c(e){for(let s=0;s<e.optionEntities.length;s++){const n=e.optionEntities[s];if(!t.valid(n)||!t.has(n,ne))continue;const r=t.get(n,ne);s===e.highlightIndex?r.color={...an}:r.color={r:1,g:1,b:1,a:0},t.insert(n,ne,r)}}function d(e){for(const s of e.optionEntities){if(!t.valid(s)||!t.has(s,Cn))continue;if(t.get(s,Cn).hovered)return!0}return!1}e.addSystemToSchedule(exports.Schedule.Update,Ie([we(Be),we(Fn)],(e,a)=>{for(const[e]of s)t.valid(e)||s.delete(e);const l=t.getEntitiesWithComponents([br]);for(const u of l){nn(t,u,En,{enabled:!0,blockRaycast:!0});const l=t.get(u,br),h=t.has(u,Cn)?t.get(u,Cn):null;let f=s.get(u);if(f||(f={optionEntities:[],highlightIndex:-1},s.set(u,f)),h?.justPressed&&(l.isOpen?r(u,l,f):n(u,l,f)),l.isOpen){for(let e=0;e<f.optionEntities.length;e++){const s=f.optionEntities[e];if(!t.valid(s)||!t.has(s,Cn))continue;if(t.get(s,Cn).justPressed){o(u,l,f,e,a);break}}e.isKeyPressed("ArrowDown")?(f.highlightIndex>=l.options.length-1?f.highlightIndex=0:f.highlightIndex++,c(f)):e.isKeyPressed("ArrowUp")?(f.highlightIndex<=0?f.highlightIndex=l.options.length-1:f.highlightIndex--,c(f)):e.isKeyPressed("Enter")&&f.highlightIndex>=0?o(u,l,f,f.highlightIndex,a):e.isKeyPressed("Escape")&&r(u,l,f),e.isMouseButtonPressed(0)&&(h?.hovered||d(f)||r(u,l,f))}i(l)}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},Pr=0,Mr=0,Tr=2,Er=j("LayoutGroup",{direction:Pr,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Mr,reverseOrder:!1});const Cr=new class{build(e){q("LayoutGroup",Er);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ie([],()=>{const e=t.getEntitiesWithComponents([Er,Ns,le]);for(const s of e){const e=t.get(s,Er),n=t.get(s,Ns),r=t.get(s,le);if(!r.entities||0===r.entities.length)continue;const o=[];for(const e of r.entities)t.valid(e)&&t.has(e,Ns)&&t.has(e,te)&&o.push({entity:e,rect:t.get(e,Ns)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const i=n._computedWidth??n.size.x,a=n._computedHeight??n.size.y,l=n.pivot.x,c=n.pivot.y,d=e.padding,u=e.direction===Pr;let h=0;for(let s=0;s<o.length;s++){const n=o[s],r=n.rect._computedWidth??n.rect.size.x,f=n.rect._computedHeight??n.rect.size.y,p=n.rect.pivot.x,g=n.rect.pivot.y;let y,m;u?(y=-l*i+d.left+h+p*r,m=e.childAlignment===Mr?(1-c)*a-d.top-(1-g)*f:e.childAlignment===Tr?-c*a+d.bottom+g*f:(.5-c)*a+.5*(d.bottom-d.top)+(g-.5)*f,h+=r,s<o.length-1&&(h+=e.spacing)):(y=e.childAlignment===Mr?-l*i+d.left+p*r:e.childAlignment===Tr?(1-l)*i-d.right-(1-p)*r:(.5-l)*i+.5*(d.left-d.right)+(p-.5)*r,m=(1-c)*a-d.top-h-(1-g)*f,h+=f,s<o.length-1&&(h+=e.spacing)),n.rect._layoutManaged=!0;const _=t.get(n.entity,te);_.position.x=y,_.position.y=m,t.insert(n.entity,te,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};function Ar(e,t,s){if(e.has(t,ne)&&e.has(t,Ns)){const n=e.get(t,ne);n.layer!==s&&(n.layer=s,e.insert(t,ne,n)),s++}if(!e.has(t,le))return s;const n=e.get(t,le);if(!n||!n.entities)return s;for(const t of n.entities)e.valid(t)&&(s=Ar(e,t,s));return s}const Rr=new class{build(e){const t=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,Ie([],()=>{let e=0;const s=t.getEntitiesWithComponents([kn,Ns]);for(const n of s)e=Ar(t,n,e)},{name:"UIRenderOrderSystem"}))}};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 Fr=xe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),kr=xe(null,"PhysicsAPI");function Dr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Br(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Lr{constructor(e,t={},s){this.wasmUrl_=e,this.factory_=s,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Fr,{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([oe]);for(const s of t){const t=e.world.get(s,oe);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,Ie([we(Pe)],a=>{const l=i.getEntitiesWithComponents([fe,te,se]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,fe),l=i.get(r,se);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=Dr(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),Ur(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===me.Kinematic){const e=Dr(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,te);if(!d)continue;let u=a,h=l,f=c;if(e.world.has(i,ae)){const t=e.world.get(i,ae);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,se)){const s=e.world.get(t.entity,se),n=Dr(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),f=c-n}}d.position.x=u,d.position.y=h;const p=Br(f);d.rotation.w=p.w,d.rotation.x=p.x,d.rotation.y=p.y,d.rotation.z=p.z,e.world.insert(i,te,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(Fr,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(kr,Wr._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function Ur(e,t,s){const n=e.world;if(n.has(s,pe)){const e=n.get(s,pe);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,ge)){const e=n.get(s,ge);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,ye)){const e=n.get(s,ye);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 Wr{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(Wr.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 $r(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 zr(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 Or(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,f=c+c,p=a*u,g=a*h,y=a*f,m=l*h,_=l*f,x=c*f,w=d*u,v=d*h,b=d*f;return new Float32Array([(1-(m+x))*r,(g+b)*r,(y-v)*r,0,(g-b)*o,(1-(p+x))*o,(_+w)*o,0,(y+v)*i,(_-w)*i,(1-(p+m))*i,0,e.position.x,e.position.y,e.position.z,1])}async function Hr(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){const r=pt(t.type);for(const o of r){if("texture"!==o.type)continue;const r=t.data[o.field];if("string"==typeof r&&r&&void 0===n[r])try{n[r]=$r(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){const i=gt(n.type);if(!i||!n.data)continue;const a=n.data[i.skeletonField],l=n.data[i.atlasField];if(!a||!l)continue;const c=r.resolvePath(a),d=r.resolvePath(l);try{const n=await r.readText(l),i="binary"===y(c)?.contentType;let u,h;if(i){const e=await r.readBinary(a);h=e.length,u=t._malloc(h),t.HEAPU8.set(e,u)}else{const e=await r.readText(a),s=(new TextEncoder).encode(e);h=s.length,u=t._malloc(h+1),t.HEAPU8.set(s,u),t.HEAPU8[u+h]=0}const f=s.loadSkeleton(u,h,n,n.length,i);if(t._free(u),f<0)continue;o[a]=f;const p=zr(n),g=d.substring(0,d.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=g+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),i=$r(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,s,n)),o){const t={gravity:i?.gravity??{...k},fixedTimestep:i?.fixedTimestep??D,subStepCount:i?.subStepCount??4};new Lr("",t,()=>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){const r=pt(t.type).find(e=>"font"===e.type);if(!r)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===n[o])try{let t,r;const i=y(o);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await s.readText(o)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){n[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await s.readText(l),r=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(o),r=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[o]=0;continue}const l=r?`${r}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),d=$r(e,c,!1),u=e.getResourceManager();n[o]=u.loadBitmapFont(t,d,c.width,c.height)}catch{n[o]=0}}return n}(t,s,n),f=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data)continue;const r=pt(e.type).find(e=>"material"===e.type);if(!r)continue;const o=e.data[r.field];if("string"==typeof o&&o&&void 0===s[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){s[o]=0;continue}const r=e.vertexSource+e.fragmentSource;let i=n[r];i||(i=st.createShader(e.vertexSource,e.fragmentSource),n[r]=i),s[o]=st.createFromAsset(e,i)}catch{s[o]=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=pt(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,f);const p=xt(e.world,s);if(l&&e.hasResource(Es))for(const t of p.values())e.world.insert(t,he,{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){const i=gt(t.type);if(!i||!t.data)continue;const a=s[t.data[i.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=n.get(o.id);void 0!==c&&(r[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return r}(u,s,d,p);!function(e,t,s,n,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=F);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,de)?c.get(o,de):null,d=!1!==a?.playing,u=a?.timeScale??1;d&&n.update(i,l*u);let h=0;if(c.has(o,se)){const e=Or(c.get(o,se),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=n.getMeshBatchCount(i);for(let e=0;e<f;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),f=s._malloc(4);n.getMeshBatchData(i,e,c,d,u,f);const p=s.HEAPU32[u>>2],g=s.HEAPU32[f>>2],y=new Float32Array(s.HEAPF32.buffer,c,8*r),m=new Uint16Array(s.HEAPU8.buffer,d,o),_=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(y,_>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(m),t.renderer_submitTriangles(_,r,x,o,p,g,h),t._free(_),t._free(x),s._free(c),s._free(d),s._free(u),s._free(f)}h&&t._free(h)}})}(e,t,r,u,n)}if(a){const t=e.getResource(St);t&&t.setAddressableManifest(a)}}class jr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components){if(!e.data)continue;const r=gt(e.type);if(r){const n=e.data[r.skeletonField],o=e.data[r.atlasField];n&&("binary"===y(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=pt(e.type);for(const s of o){const r=e.data[s.field];"string"==typeof r&&r&&("font"===s.type?(n.add(r),t.add(r)):"material"===s.type&&t.add(r))}}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=y(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 Xr="__preview__";const Nr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=ms.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:ms.getTargetTexture(s),width:e.width,height:e.height}},release(e){ms.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(ms.releaseRenderTarget(e._handle),Nr.create({width:t,height:s,depth:!0})),begin(e,t){ms.begin(t,e._handle)},end(){ms.end()},getDepthTexture:e=>ms.getTargetDepthTexture(e._handle)};let Vr=!1;var Yr;exports.LogLevel=void 0,(Yr=exports.LogLevel||(exports.LogLevel={}))[Yr.Debug=0]="Debug",Yr[Yr.Info=1]="Info",Yr[Yr.Warn=2]="Warn",Yr[Yr.Error=3]="Error";class Gr{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 qr{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new Gr)}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 Jr=new qr;const Kr=[gn,Tn,Un,er,ir,Hn,cr,ur,pr,nr,Gn,gr,_r,vr,Sr,Cr,Rr];C||(C=!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 c(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 d(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=A,exports.App=Is,exports.AssetPlugin=Pt,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=bt,exports.Assets=St,exports.AsyncCache=ut,exports.BitmapText=ce,exports.BodyType=me,exports.BoxCollider=pe,exports.Button=Rn,exports.ButtonState=An,exports.Camera=re,exports.Canvas=oe,exports.CapsuleCollider=ye,exports.Children=le,exports.CircleCollider=ge,exports.ClearFlags=Z,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=Ce,exports.DEFAULT_DESIGN_HEIGHT=I,exports.DEFAULT_DESIGN_WIDTH=R,exports.DEFAULT_FALLBACK_DT=F,exports.DEFAULT_FIXED_TIMESTEP=D,exports.DEFAULT_FONT_FAMILY="Arial",exports.DEFAULT_FONT_SIZE=24,exports.DEFAULT_GRAVITY=k,exports.DEFAULT_LINE_HEIGHT=1.2,exports.DEFAULT_MAX_DELTA_TIME=.5,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_SPINE_SKIN="default",exports.DEFAULT_SPRITE_SIZE={x:100,y:100},exports.DEFAULT_TEXT_CANVAS_SIZE=512,exports.DragState=lr,exports.Draggable=ar,exports.Draw=jt,exports.Dropdown=br,exports.EntityCommands=Ee,exports.FillDirection=js,exports.FillMethod=Jn,exports.FillOrigin=Kn,exports.FocusManager=Vn,exports.FocusManagerState=Nn,exports.Focusable=Xn,exports.GLDebug=vs,exports.Geometry=os,exports.INVALID_ENTITY=0,exports.INVALID_FONT=U,exports.INVALID_MATERIAL=0,exports.INVALID_TEXTURE=L,exports.Image=Qn,exports.ImageType=qn,exports.Input=Be,exports.InputPlugin=Le,exports.InputState=De,exports.Interactable=En,exports.ListView=xr,exports.LocalTransform=te,exports.Logger=qr,exports.Material=st,exports.MaterialLoader=ht,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ue,exports.Parent=ae,exports.Physics=Wr,exports.PhysicsEvents=Fr,exports.PhysicsPlugin=Lr,exports.PostProcess=ds,exports.PrefabServer=Rt,exports.Prefabs=It,exports.PrefabsPlugin=Ft,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(Es);t.register({name:Xr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Xr),this.loadPromise_=t.load(Xr).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await n(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new jr(this.baseUrl_);await s.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await Hr(this.app_,this.app_.wasmModule,t,s,r,null,void 0,null,Xr)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([re]);for(const n of s){if(e.get(n,re).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([oe]);for(const r of n){const n=e.get(r,oe);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(Es).getScene(Xr),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,te,i);const a={isActive:!0,projectionType:Q.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Z.ColorAndDepth};e.insert(o,re,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(Es);await e.switchTo(Xr),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=or,exports.ProgressBarDirection=rr,exports.ProjectionType=Q,exports.Query=function(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{Me(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)},exports.QueryInstance=Te,exports.RenderPipeline=bs,exports.RenderTexture=Nr,exports.Renderer=ms,exports.Res=we,exports.ResMut=ve,exports.RigidBody=fe,exports.RuntimeConfig=B,exports.SafeArea=yr,exports.ScaleMode=ee,exports.SceneManager=Es,exports.SceneManagerState=Ts,exports.SceneOwner=he,exports.ScreenSpace=kn,exports.ScrollView=dr,exports.ShaderSources=dt,exports.Slider=fr,exports.SliderDirection=hr,exports.SpineAnimation=de,exports.Sprite=ne,exports.SystemRunner=ke,exports.Text=un,exports.TextAlign=ln,exports.TextInput=jn,exports.TextInputPlugin=Yn,exports.TextOverflow=dn,exports.TextPlugin=pn,exports.TextRenderer=hn,exports.TextVerticalAlign=cn,exports.Time=Pe,exports.Toggle=tr,exports.UICameraInfo=Ve,exports.UIEventQueue=In,exports.UIEvents=Fn,exports.UIInteraction=Cn,exports.UIInteractionPlugin=On,exports.UILayoutPlugin=Ln,exports.UIMask=yn,exports.UIMaskPlugin=Mn,exports.UIRect=Ns,exports.Velocity=ie,exports.WebAssetProvider=jr,exports.World=Ne,exports.WorldTransform=se,exports.addStartupSystem=function(e){Fe().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){Fe().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){Fe().push({schedule:e,system:t})},exports.applyDirectionalFill=Gs,exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=B.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=B.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=B.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=B.canvasMatchWidthOrHeight)},exports.assetPlugin=Mt,exports.clearDrawCallbacks=Jt,exports.clearUserComponents=function(){const e=H();for(const t of e.keys())G.delete(t);e.clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeFillAnchors=Ys,exports.computeFillSize=function(e,t,s,n){switch(e){case js.BottomToTop:case js.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}},exports.computeHandleAnchors=function(e,t){switch(e){case js.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case js.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case js.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1-t}};default:return{anchorMin:{x:t,y:0},anchorMax:{x:t,y:1}}}},exports.computeUIRectLayout=Xs,exports.createMaskProcessor=Pn,exports.createRuntimeSceneConfig=function(e,t,s){return{name:e,data:t,async setup(){await Hr(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=Is.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),$t(e),Ze(e),ss(e),as(e),gs(e),xs(e);const r=new bs;s.setPipeline(r);let o=l();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,o){o||(o=Ds(e,n,t,r));const i=s.getResource(Ve);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(Ve,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(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;ms.setClearColor(e.x,e.y,e.z,e.w)}const u=(l()-o)/1e3;let h;if(ms.resize(t,c),ds.isInitialized()&&ds.getPassCount()>0&&!ds.isBypassed()&&ds.resize(t,c),s.hasResource(Es)){const e=s.getResource(Es).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const f=Ds(e,n,t,c,s.world,h);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:Fs,width:t,height:c,elapsed:u});else{for(const e of f){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})}ms.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(exports.Schedule.First,c),s.addSystemToSchedule(exports.Schedule.Last,d),s.addPlugin(Mt),s.addPlugin(kt),s.addPlugin(Ue),s.addPlugin(Rs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Kr,...t})},exports.debug=function(e,t,s){Jr.debug(e,t,s)},exports.defineComponent=j,exports.defineResource=xe,exports.defineSystem=Ie,exports.defineTag=X,exports.error=function(e,t,s){Jr.error(e,t,s)},exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([ue]);for(const n of s){const s=e.get(n,ue);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 y(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of u)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return p},exports.getAssetMimeType=function(e){return h[e.toLowerCase()]},exports.getAssetTypeEntry=y,exports.getComponent=J,exports.getComponentAssetFields=function(e){const t=ft.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=J(e);return t?W(t._default):null},exports.getCustomExtensions=_,exports.getEditorType=function(e){return y(e)?.editorType??"unknown"},exports.getLogger=function(){return Jr},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=N,exports.getWeChatPackOptions=function(){return _().map(e=>({type:"suffix",value:e}))},exports.info=function(e,t,s){Jr.info(e,t,s)},exports.initDrawAPI=$t,exports.initGLDebugAPI=xs,exports.initGeometryAPI=ss,exports.initMaterialAPI=Ze,exports.initPostProcessAPI=as,exports.initRendererAPI=gs,exports.inputPlugin=Ue,exports.instantiatePrefab=Tt,exports.intersectRects=mn,exports.invertMatrix4=_n,exports.isBuiltinComponent=Y,exports.isCustomExtension=x,exports.isEditor=function(){return Vr},exports.isKnownAssetExtension=m,exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!Vr},exports.isTextureRef=Ge,exports.isWeChat=s,exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=vt,exports.loadPhysicsModule=Ir,exports.loadRuntimeScene=Hr,exports.loadSceneData=xt,exports.loadSceneWithAssets=wt,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&m(g(e)))},exports.platformFetch=n,exports.platformFileExists=i,exports.platformInstantiateWasm=async function(e,s){return t().instantiateWasm(e,s)},exports.platformReadFile=r,exports.platformReadTextFile=o,exports.pointInOBB=bn,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=kt,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerComponent=q,exports.registerComponentAssetFields=function(e,t){ft.set(e,t)},exports.registerComponentEntityFields=function(e,t){yt.set(e,t)},exports.registerDrawCallback=Gt,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(St);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=ct,exports.sceneManagerPlugin=Rs,exports.screenToWorld=xn,exports.setEditorMode=function(e){Vr=e},exports.setListViewRenderer=function(e,t){if(!wr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=wr.get(e);s?s.renderer=t:wr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})},exports.setLogLevel=function(e){Jr.setMinLevel(e)},exports.setWasmErrorHandler=He,exports.shutdownDrawAPI=zt,exports.shutdownGLDebugAPI=ws,exports.shutdownGeometryAPI=ns,exports.shutdownMaterialAPI=et,exports.shutdownPostProcessAPI=ls,exports.shutdownRendererAPI=ys,exports.syncFillSpriteSize=function(e,t,s,n,r,o){if(!e.has(t,ne))return;const i=e.get(t,ne);let a,l;switch(s){case js.BottomToTop:case js.TopToBottom:a=r,l=o*n;break;default:a=r*n,l=o}i.size.x===a&&i.size.y===l||(i.size.x=a,i.size.y=l,e.insert(t,ne,i))},exports.textInputPlugin=Gn,exports.textPlugin=gn,exports.transitionTo=async function(e,t,s){const n=e.getResource(Es);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=Hn,exports.uiLayoutPlugin=Un,exports.uiMaskPlugin=Tn,exports.uiPlugins=Kr,exports.unregisterComponent=function(e){H().delete(e),G.delete(e)},exports.unregisterDrawCallback=qt,exports.updateCameraAspectRatio=function(e,t){const s=e.getEntitiesWithComponents([re]);for(const n of s){const s=e.get(n,re);s&&(s.aspectRatio=t,e.insert(n,re,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){Jr.warn(e,t,s)},exports.wrapSceneSystem=Cs,exports.wxFileExists=M,exports.wxFileExistsSync=function(e){const t=v();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=E,exports.wxLoadImage=T,exports.wxLoadImagePixels=async function(e){return E(await T(e))},exports.wxReadFile=S,exports.wxReadTextFile=P,exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{v().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};+"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function s(){return"wechat"===e?.name}async function n(e,s){return t().fetch(e,s)}async function r(e){return t().readFile(e)}async function o(e){return t().readTextFile(e)}async function i(e){return t().fileExists(e)}function a(e,s){return t().createCanvas(e,s)}function l(){return t().now()}function c(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}function u(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 d(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 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}],p={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"},f=new Map,g=new Set;for(const e of h)for(const t of e.extensions)f.set(t,e),g.add(t);function y(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function m(e){return f.get(y(e))}function _(e){return g.has(e.toLowerCase())}function x(){const e=[];for(const t of h)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function w(e){const t=m(e);return t?.wechatPackInclude??!1}let v=null;function b(){return v||(v=wx.getFileSystemManager()),v}function S(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(w(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return 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 P(e){return new Promise((t,s)=>{b().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(S(e,t.errMsg)))}})})}function M(e,t="utf-8"){return new Promise((s,n)=>{b().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(S(e,t.errMsg)))}})})}function T(e){return new Promise(t=>{b().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function E(e){return new Promise((t,s)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function C(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}let A=!1;const R=new class{constructor(){this.name="wechat"}async fetch(e,t){return u(e,t)}async readFile(e){return P(e)}async readTextFile(e){return M(e)}async fileExists(e){return T(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return d(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)})}},I=1920,F=1080,D=1/60,k={x:0,y:-9.81},B=1/60,L={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};const U=4294967295,W=4294967295;function z(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(z);const t={};for(const s in e)t[s]=z(e[s]);return t}let $=0;function O(e,t){const s=++$;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...z(t),...e}:z(t)}}const H=new Map;function j(){return"undefined"==typeof window?H:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function X(e,t){const s=q.get(e)??j().get(e);if(s)return s;const n=O(e,t);return j().set(e,n),q.set(e,n),Y(e,t,!1),n}function N(e){const t=q.get(e)??j().get(e);if(t)return t;const s=O(e,{});return j().set(e,s),q.set(e,s),Y(e,{},!0),s}function V(e){return j().get(e)}function Y(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function G(e){return!0===e._builtin}const q=new Map;function J(e,t){q.set(e,t)}function K(e){return q.get(e)??V(e)}function Q(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return q.set(e,s),s}const Z={Perspective:0,Orthographic:1},ee={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},te={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},se=Q("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),ne=Q("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),re=Q("Sprite",{texture:U,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}),oe=Q("Camera",{projectionType:Z.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:ee.ColorAndDepth}),ie=Q("Canvas",{designResolution:{x:I,y:F},pixelsPerUnit:100,scaleMode:te.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),ae=Q("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),le=Q("Parent",{entity:0}),ce=Q("Children",{entities:[]}),ue=Q("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:W,enabled:!0}),de=Q("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}),he={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},pe=X("SceneOwner",{scene:"",persistent:!1});J("Name",he);const fe=Q("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ge=Q("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ye=Q("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),me=Q("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),_e={Static:0,Kinematic:1,Dynamic:2};let xe=0;function we(e,t){const s=++xe;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function ve(e){return{_type:"res",_resource:e}}function be(e){return{_type:"res_mut",_resource:e}}class Se{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class Pe{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new Se(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Me=we({delta:0,elapsed:0,frameCount:0},"Time");function Te(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}class Ee{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>Te(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=s.length,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let u=null;this.world_.beginIteration();try{for(const d of n){if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}if(i){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(d,t[s])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,s[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=d}yield a}}finally{if(this.world_.endIteration(),null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class Ce{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=G(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 Ae{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Ce(this,null);return this.spawned_.push(e),e}entity(e){return new Ce(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 Re;exports.Schedule=void 0,(Re=exports.Schedule||(exports.Schedule={}))[Re.Startup=0]="Startup",Re[Re.First=1]="First",Re[Re.PreUpdate=2]="PreUpdate",Re[Re.Update=3]="Update",Re[Re.PostUpdate=4]="PostUpdate",Re[Re.Last=5]="Last",Re[Re.FixedPreUpdate=10]="FixedPreUpdate",Re[Re.FixedUpdate=11]="FixedUpdate",Re[Re.FixedPostUpdate=12]="FixedPostUpdate";let Ie=0;function Fe(e,t,s){const n=++Ie;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function De(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class ke{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 Ae&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new Ee(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Ae(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Be{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 Le=we(new Be,"Input");class Ue{constructor(e){this.target_=e??null}build(e){const s=new Be;e.insertResource(Le,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,Fe([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const We=new Ue;function ze(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=$e(t[e]),o=$e(r);"null"!==s&&"undefined"!==s&&(s!==o&&null!=r&&n.push({field:e,expected:s,actual:o,value:r}))}return n}function $e(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Oe(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 He=null;function je(e){He=e}function Xe(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),He&&He(e,t)}function Ne(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}:Ne(e)}}return t}class Ve{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,this.nextEntityId_=0}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw Xe(e,"spawn"),e}else e=++this.nextEntityId_;return this.entities_.add(e),this.worldVersion_++,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){Xe(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){Xe(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Xe(t,`removeParent(entity=${e})`)}}insert(e,t,s){return G(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return G(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return G(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(G(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return Xe(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.");G(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const s=this.cppRegistry_,n=s[`add${e}`],r=s[`get${e}`],o=s[`has${e}`],i=s[`remove${e}`];if("function"!=typeof n||"function"!=typeof r||"function"!=typeof o||"function"!=typeof i)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:n.bind(s),get:r.bind(s),has:o.bind(s),remove:i.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=ze(t._name,t._default,n);if(e.length>0)throw new Error(Oe(t._name,e))}const r={...t._default,...n};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,Ne(r))}catch(s){Xe(s,`insertBuiltin(${t._name}, entity=${e})`)}return this.worldVersion_++,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 Xe(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 Xe(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Xe(s,`removeBuiltin(${t._name}, entity=${e})`)}this.worldVersion_++}}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const r=ze(t._name,t._default,e);if(r.length>0)throw new Error(Oe(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}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 q)if(G(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=j();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(!G(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.slice()}),a}}const Ye=we({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var Ge;function qe(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(Ge=exports.BlendMode||(exports.BlendMode={}))[Ge.Normal=0]="Normal",Ge[Ge.Additive=1]="Additive",Ge[Ge.Multiply=2]="Multiply",Ge[Ge.Screen=3]="Screen",Ge[Ge.PremultipliedAlpha=4]="PremultipliedAlpha";let Je=null,Ke=null,Qe=1;const Ze=new Map;function et(e){Je=e,Ke=e.getResourceManager(),ut()}function tt(){0!==ot&&Je&&(Je._free(ot),ot=0),Ze.clear(),Qe=1,rt=!1,at.clear(),lt=null,Ke=null,Je=null}function st(){if(!Ke)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ke}const nt={createShader:(e,t)=>st().createShader(e,t),releaseShader(e){e>0&&st().releaseShader(e)},create(e){const t=Qe++,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 Ze.set(t,s),t},get:e=>Ze.get(e),setUniform(e,t,s){const n=Ze.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ze.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ze.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ze.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=Ze.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ze.get(e);return t?.shader??0},release(e){Ze.delete(e)},isValid:e=>Ze.has(e),releaseAll(){Ze.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=Ze.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Qe++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ze.set(s,n),s},toAssetData(e,t){const s=Ze.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=Ze.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let rt=!1,ot=0;const it=4096,at=new Map;let lt=null;function ct(e){const t=(0===ot&&Je&&(ot=Je._malloc(it)),ot);if(0===t||!Je)return{ptr:0,count:0};let s=0,n=0;const r=Je.HEAPU8,o=Je.HEAPU32,i=Je.HEAPF32;for(const[a,l]of e){if(s+128>it)break;let e=at.get(a);e||(lt||(lt=new TextEncoder),e=lt.encode(a),at.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+s>>2]=c,s+=4,r.set(e,t+s),s+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+s>>2]=d,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function ut(){if(!Je||rt)return;Je.materialDataProvider=(e,t,s,n,r)=>{const o=Ze.get(e);if(!o)return Je.HEAPU32[t>>2]=0,Je.HEAPU32[s>>2]=0,Je.HEAPU32[n>>2]=0,void(Je.HEAPU32[r>>2]=0);Je.HEAPU32[t>>2]=o.shader,Je.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=ct(o.uniforms);Je.HEAPU32[n>>2]=i,Je.HEAPU32[r>>2]=a},rt=!0}const dt={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class ht{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 pt{constructor(e,t=""){this.cache_=new ht,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&&(nt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())nt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await i(t))throw new Error(`Material file not found: ${t}`);const s=await o(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const r=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(r);return{handle:nt.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 ft=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 gt(e){return ft.get(e)?.fields??[]}function yt(e){return ft.get(e)?.spine??null}const mt=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function _t(e,t){const s=mt.get(e.type);if(!s)return;const n=e.data;for(const e of s){const s=n[e];if("number"==typeof s&&0!==s){const r=t.get(s);n[e]=void 0!==r?r:0}}}function xt(e,t){const s=new Map;for(const n of t.entities){const t=e.spawn();s.set(n.id,t),e.insert(t,he,{value:n.name})}for(const n of t.entities){if(!1===n.visible)continue;const t=s.get(n.id);for(const r of n.components)_t(r,s),St(e,t,r,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}function wt(e,t){return xt(e,t)}async function vt(e,t,s){const n=s?.assetServer,r=s?.assetBaseUrl,o=new Map;n&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Map;for(const e of bt.keys())r.set(e,new Set);const o=[],i=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ft.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}`;i.has(t)||(i.add(t),o.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];"string"==typeof t&&t&&r.get(e.type)?.add(t)}}const a=new Map,l=[...bt.entries()].map(async([e,o])=>{const i=await o.load(r.get(e),t,s,n);a.set(e,i)}),c=o.map(async e=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)});await Promise.all([...l,...c]);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ft.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];"string"==typeof t&&t&&(s[e.field]=a.get(e.type)?.get(t)??0)}}}(t,n,r,o);const i=xt(e,t);if(n&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&n.setTextureMetadataByPath(t,s.sliceBorder)}return i}const bt=new Map([["texture",{async load(e,t,s,n){const r=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,i=await t.loadTexture(o);r.set(e,i.handle),n.set(e,o)}catch(t){console.warn(`Failed to load texture: ${e}`,t),r.set(e,0)}});return await Promise.all(o),r}}],["material",{async load(e,t,s){const n=new Map,r=[...e].map(async e=>{try{const r=await t.loadMaterial(e,s);n.set(e,r.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),n.set(e,0)}});return await Promise.all(r),n}}],["font",{async load(e,t,s){const n=new Map,r=[...e].map(async e=>{try{const r=await t.loadBitmapFont(e,s);n.set(e,r)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),n.set(e,0)}});return await Promise.all(r),n}}]]);function St(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=K(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 ht,this.shaderCache_=new ht,this.jsonCache_=new ht,this.textCache_=new ht,this.binaryCache_=new ht,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new ht,this.prefabCache_=new ht,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_=a(L.textCanvasSize,L.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 pt(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(),nt.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),u="binary"===m(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=l.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=m(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 vt(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 nt.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await i(t))throw new Error(`Shader file not found: ${e}`);const n=await o(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:a}=this.parseEsShader(n);if(!r||!a)throw new Error(`Invalid shader format: ${e}`);return nt.createShader(r,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 o(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return o(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(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 s=await n(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let 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 Mt=we(null,"Assets");class Tt{build(e){const t=e.wasmModule;t?e.insertResource(Mt,new Pt(t)):console.warn("AssetPlugin: No WASM module available")}}const Et=new Tt;async function Ct(e,t,s){const{entities:n,rootId:r}=await Rt(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 vt(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 At=10;async function Rt(e,t,s,n,r,o=0){if(o>At)throw new Error(`Prefab nesting depth exceeded ${At}. 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 Rt(e,n.nestedPrefab.overrides,s,a,r,o+1);i.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?i.get(n.parent)??null:null),l.push(...t.entities);continue}const c=i.get(n.prefabEntityId),u=n.prefabEntityId===e.rootEntityId,d={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?null:null!==n.parent?i.get(n.parent)??null:null,children:n.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};It(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 It(e,t){for(const s of t)if(s.prefabEntityId===e.prefabEntityId)switch(s.type){case"property":if(s.componentType&&void 0!==s.propertyName){const t=e.components.find(e=>e.type===s.componentType);t&&(t.data[s.propertyName]=s.value)}break;case"name":"string"==typeof s.value&&(e.name=s.value);break;case"visibility":"boolean"==typeof s.value&&(e.visible=s.value);break;case"component_added":if(s.componentData){e.components.some(e=>e.type===s.componentData.type)||e.components.push({type:s.componentData.type,data:JSON.parse(JSON.stringify(s.componentData.data))})}break;case"component_removed":s.componentType&&(e.components=e.components.filter(e=>e.type!==s.componentType))}}class Ft{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return Ct(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Dt=we(null,"Prefabs");class kt{constructor(){this.name="PrefabsPlugin",this.dependencies=[Mt]}build(e){const t=e.getResource(Mt);e.insertResource(Dt,new Ft(e.world,t))}}const Bt=new kt;let Lt=null,Ut=0,Wt=0,zt=0;const $t=new Float32Array(256);function Ot(e){Lt=e,Ut=Lt._malloc(64),Wt=Lt._malloc(64),zt=Lt._malloc(1024)}function Ht(){Lt&&(Ut&&(Lt._free(Ut),Ut=0),Wt&&(Lt._free(Wt),Wt=0),zt&&(Lt._free(zt),zt=0)),Lt=null}function jt(){if(!Lt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Lt}const Xt={r:1,g:1,b:1,a:1},Nt={begin(e){const t=jt();try{t.HEAPF32.set(e,Ut/4),t.draw_begin(Ut)}catch(e){Xe(e,"Draw.begin")}},end(){try{jt().draw_end()}catch(e){Xe(e,"Draw.end")}},line(e,t,s,n=1){try{jt().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Xe(e,"Draw.line")}},rect(e,t,s,n=!0){try{jt().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Xe(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{jt().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Xe(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,r=32){try{jt().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Xe(e,"Draw.circle")}},circleOutline(e,t,s,n=1,r=32){try{jt().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Xe(e,"Draw.circleOutline")}},texture(e,t,s,n=Xt){try{jt().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Xe(e,"Draw.texture")}},textureRotated(e,t,s,n,r=Xt){try{jt().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)}catch(e){Xe(e,"Draw.textureRotated")}},setLayer(e){jt().draw_setLayer(e)},setDepth(e){jt().draw_setDepth(e)},getDrawCallCount:()=>Lt?Lt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Lt?Lt.draw_getPrimitiveCount():0,setBlendMode(e){jt().draw_setBlendMode(e)},setDepthTest(e){jt().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=jt();n.HEAPF32.set(s,Wt/4),n.draw_mesh(e,t,Wt)}catch(s){Xe(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=jt(),r=nt.get(t);if(!r)return;if(Nt.setBlendMode(r.blendMode),Nt.setDepthTest(r.depthTest),0===r.uniforms.size)return void Nt.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,Wt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=Gt(t);if(!(n<0)){if(qe(s))$t[o++]=10,$t[o++]=n,$t[o++]=s.slot??e++,$t[o++]=s.textureId;else if("number"==typeof s)$t[o++]=1,$t[o++]=n,$t[o++]=s;else if(Array.isArray(s)){$t[o++]=s.length,$t[o++]=n;for(let e=0;e<s.length;e++)$t[o++]=s[e]}else"w"in s?($t[o++]=4,$t[o++]=n,$t[o++]=s.x,$t[o++]=s.y,$t[o++]=s.z,$t[o++]=s.w):"z"in s?($t[o++]=3,$t[o++]=n,$t[o++]=s.x,$t[o++]=s.y,$t[o++]=s.z):($t[o++]=2,$t[o++]=n,$t[o++]=s.x,$t[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($t.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void n.draw_mesh(e,r.shader,Wt);n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),zt/4),n.draw_meshWithUniforms(e,r.shader,Wt,zt,o)}catch(s){Xe(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Vt={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},Yt=new Set;function Gt(e){const t=Vt[e];return void 0!==t?t:(Yt.has(e)||(Yt.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Vt).join(", ")}`)),-1)}const qt=new Map;function Jt(e,t,s){qt.set(e,{fn:t,scene:s??""})}function Kt(e){qt.delete(e)}function Qt(){qt.clear()}var Zt;exports.DataType=void 0,(Zt=exports.DataType||(exports.DataType={}))[Zt.Float=1]="Float",Zt[Zt.Float2=2]="Float2",Zt[Zt.Float3=3]="Float3",Zt[Zt.Float4=4]="Float4",Zt[Zt.Int=5]="Int",Zt[Zt.Int2=6]="Int2",Zt[Zt.Int3=7]="Int3",Zt[Zt.Int4=8]="Int4";let es=null,ts=0,ss=0,ns=0;function rs(e){es=e,ts=es._malloc(262144),ss=es._malloc(65536),ns=es._malloc(256)}function os(){es&&(ts&&es._free(ts),ss&&es._free(ss),ns&&es._free(ns),ts=0,ss=0,ns=0),es=null}function is(){if(!es)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return es}const as={create(e){const t=is(),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,ts/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,ns,r).set(o),t.geometry_init(s,ts,n,ns,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,ss,n).set(e.indices),t.geometry_setIndices16(s,ss,n)}else{new Uint32Array(t.HEAPU8.buffer,ss,n).set(e.indices),t.geometry_setIndices32(s,ss,n)}}return s},updateVertices(e,t,s=0){const n=is(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,ts/4),n.geometry_updateVertices(e,ts,r,s)},release(e){e>0&&is().geometry_release(e)},isValid:e=>!(!es||e<=0)&&es.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return as.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 as.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 as.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 ls=null;function cs(e){ls=e}function us(){ls&&hs.isInitialized()&&hs.shutdown(),ls=null}function ds(){if(!ls)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return ls}const hs={init(e,t){try{return ds().postprocess_init(e,t)}catch(s){return Xe(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{ds().postprocess_shutdown()}catch(e){Xe(e,"PostProcess.shutdown")}},resize(e,t){try{ds().postprocess_resize(e,t)}catch(s){Xe(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return ds().postprocess_addPass(e,t)}catch(t){return Xe(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{ds().postprocess_removePass(e)}catch(t){Xe(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{ds().postprocess_setPassEnabled(e,t)}catch(t){Xe(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return ds().postprocess_isPassEnabled(e)}catch(t){return Xe(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{ds().postprocess_setUniformFloat(e,t,s)}catch(s){Xe(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{ds().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){Xe(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{ds().postprocess_begin()}catch(e){Xe(e,"PostProcess.begin")}},end(){try{ds().postprocess_end()}catch(e){Xe(e,"PostProcess.end")}},getPassCount(){try{return ds().postprocess_getPassCount()}catch(e){return Xe(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!ls)return!1;try{return ls.postprocess_isInitialized()}catch(e){return Xe(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{ds().postprocess_setBypass(e)}catch(e){Xe(e,"PostProcess.setBypass")}},isBypassed(){if(!ls)return!0;try{return ls.postprocess_isBypassed()}catch(e){return Xe(e,"PostProcess.isBypassed"),!0}},createBlur:()=>nt.createShader(ps,"#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:()=>nt.createShader(ps,"#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:()=>nt.createShader(ps,"#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:()=>nt.createShader(ps,"#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")},ps="#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 fs;exports.RenderStage=void 0,(fs=exports.RenderStage||(exports.RenderStage={}))[fs.Background=0]="Background",fs[fs.Opaque=1]="Opaque",fs[fs.Transparent=2]="Transparent",fs[fs.Overlay=3]="Overlay";let gs=null,ys=0;function ms(e){gs=e,ys=gs._malloc(64)}function _s(){gs&&ys&&(gs._free(ys),ys=0),gs=null}const xs={init(e,t){gs?.renderer_init(e,t)},resize(e,t){gs?.renderer_resize(e,t)},begin(e,t){if(gs&&ys)try{gs.HEAPF32.set(e,ys/4),gs.renderer_begin(ys,t??0)}catch(e){Xe(e,"Renderer.begin")}},flush(){try{gs?.renderer_flush()}catch(e){Xe(e,"Renderer.flush")}},end(){try{gs?.renderer_end()}catch(e){Xe(e,"Renderer.end")}},submitSprites(e){if(gs)try{gs.renderer_submitSprites(e._cpp)}catch(e){Xe(e,"Renderer.submitSprites")}},submitBitmapText(e){if(gs)try{gs.renderer_submitBitmapText(e._cpp)}catch(e){Xe(e,"Renderer.submitBitmapText")}},submitSpine(e){if(gs)try{gs.renderer_submitSpine?.(e._cpp)}catch(e){Xe(e,"Renderer.submitSpine")}},setStage(e){gs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>gs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){gs?.renderer_releaseTarget(e)},getTargetTexture:e=>gs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>gs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){gs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){gs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){gs?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){gs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>gs?gs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>gs?{drawCalls:gs.renderer_getDrawCalls(),triangles:gs.renderer_getTriangles(),sprites:gs.renderer_getSprites(),text:gs.renderer_getText(),spine:gs.renderer_getSpine?.()??0,meshes:gs.renderer_getMeshes(),culled:gs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let ws=null;function vs(e){ws=e}function bs(){ws=null}const Ss={enable(){ws?.gl_enableErrorCheck(!0)},disable(){ws?.gl_enableErrorCheck(!1)},check:e=>ws?.gl_checkErrors(e)??0,diagnose(){ws?.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_||(xs.resize(n,r),hs.isInitialized()&&hs.getPassCount()>0&&hs.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),xs.setViewport(0,0,n,r),xs.clearBuffers(3),xs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),xs.submitSprites(t),xs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):xs.submitSpine(t),xs.flush(),this.executeDrawCallbacks(s,o),xs.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;xs.setViewport(n.x,n.y,n.w,n.h),xs.setScissor(n.x,n.y,n.w,n.h,!0),xs.clearBuffers(r),xs.setScissor(0,0,0,0,!1),xs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),xs.submitSprites(t),xs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):xs.submitSpine(t),xs.flush(),this.executeDrawCallbacks(s,o),xs.end()}executeDrawCallbacks(e,t){const s=qt;if(s.size>0){Nt.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)}Nt.end();for(const e of n)Kt(e)}}}const Ms="__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 Es{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,pe,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),Jt(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=hs.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){hs.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,pe)){const s=this.app_.world.get(e,pe);s.persistent=t,this.app_.world.insert(e,pe,s)}}}class Cs{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??L.sceneTransitionDuration,r=t.color??{...L.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},Jt(Ms,()=>{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;Nt.setLayer(9999),Nt.setDepth(9999),Nt.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()=>{try{s&&s!==e&&await this.unload(s,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,Kt(Ms),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Kt(Ms),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 Ts(t);this.scenes_.set(e,s);const n=new Es(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Mt)?this.app_.getResource(Mt):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(Mt)&&(t.assetServer=this.app_.getResource(Mt));const n=await vt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,pe,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=Rs(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 Ts(t);this.scenes_.set(e,s);const n=new Es(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Mt)?this.app_.getResource(Mt):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(Mt)&&(t.assetServer=this.app_.getResource(Mt));const n=await vt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,pe,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=Rs(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,pe)){if(this.app_.world.get(e,pe).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())Kt(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{hs.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)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n={};let r=!1;if(s.has(e,re)){const t=s.get(e,re);n.sprite=t.color.a,t.color={...t.color,a:0},s.insert(e,re,t),r=!0}if(s.has(e,de)){const t=s.get(e,de);n.spine=t.color.a,t.color={...t.color,a:0},s.insert(e,de,t),r=!0}if(s.has(e,ue)){const t=s.get(e,ue);n.bitmapText=t.color.a,t.color={...t.color,a:0},s.insert(e,ue,t),r=!0}r&&t.savedAlphas.set(e,n)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n=t.savedAlphas.get(e);if(n){if(void 0!==n.sprite&&s.has(e,re)){const t=s.get(e,re);t.color={...t.color,a:n.sprite},s.insert(e,re,t)}if(void 0!==n.spine&&s.has(e,de)){const t=s.get(e,de);t.color={...t.color,a:n.spine},s.insert(e,de,t)}if(void 0!==n.bitmapText&&s.has(e,ue)){const t=s.get(e,ue);t.color={...t.color,a:n.bitmapText},s.insert(e,ue,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{hs.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 As=we(null,"SceneManager");function Rs(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(As).getSceneStatus(t)&&s._fn(...n)}}}const Is=Fe([be(As),ve(Me)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Fs={name:"SceneManager",build(e){const t=new Cs(e);e.insertResource(As,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(As),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,Is)}};class Ds{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=l(),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 Ve,this.resources_=new Pe;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Ds}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 je(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}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(As).register(e),this}setInitialScene(e){return this.getResource(As).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new ke(this.world_,this.resources_),this.resources_.insert(Me,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=l(),this.mainLoop())}quit(){this.running_=!1,Qt();for(const e of this.installed_plugins_)try{e.cleanup?.()}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.clear();const e=[bs,_s,us,os,tt,Ht];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(Me);t.delta=e,t.elapsed+=e,t.frameCount++}}const ks=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Bs(e,t,s,n,r){const o=e*t/s,i=e;switch(n){case te.FixedWidth:return o;case te.FixedHeight:return i;case te.Expand:return Math.max(o,i);case te.Shrink:return Math.min(o,i);case te.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function Ls(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,pe);return!t||""===t.scene||o.has(t.scene)}):i;if(0===a.length)return[];const l=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),c=[];for(const e of a){const r=t.getCamera(e),o=t.getLocalTransform(e),i={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=i.w*s/(i.h*n);let u,d=0,h=0;if(r.projectionType===Z.Orthographic){if(h=r.orthoSize,l){h=Bs(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}d=h*a,u=Ws(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=$s(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const p=Hs(o.position.x,o.position.y,o.position.z);c.push({entity:e,viewProjection:new Float32Array(Xs(u,p)),viewportRect:i,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:o.position.x,cameraY:o.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const Us=new Float32Array(16);function Ws(e,t,s,n,r,o){const i=Us;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 zs=new Float32Array(16);function $s(e,t,s,n){const r=zs;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 Os=new Float32Array(16);function Hs(e,t,s){const n=Os;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 js=new Float32Array(16);function Xs(e,t){const s=js;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}const Ns={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function Vs(e,t,s,n,r,o,i={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,u=o.left+t.x*a,d=o.bottom+e.y*l,h=o.bottom+t.y*l;let p,f,g,y;e.x===t.x?(p=c+s.x-r.x*i.x,g=p+r.x):(p=c+s.x,g=u+n.x),e.y===t.y?(f=d+s.y-r.y*i.y,y=f+r.y):(f=d+s.y,y=h+n.y);const m=Math.max(0,g-p),_=Math.max(0,y-f);return{originX:p+i.x*m,originY:f+i.y*_,width:m,height:_,rect:{left:p,bottom:f,right:g,top:y}}}const Ys=X("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},_dirty:!0,_computedWidth:void 0,_computedHeight:void 0,_layoutManaged:void 0});function Gs(e,t){e.has(t,re)||e.insert(t,re,{texture:U,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0})}function qs(e,t){switch(e){case Ns.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Ns.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Ns.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function Js(e,t,s,n){if(!e.has(t,Ys))return;const r=e.get(t,Ys),o=qs(s,n);r.anchorMin=o.anchorMin,r.anchorMax=o.anchorMax,r.offsetMin=o.offsetMin,r.offsetMax=o.offsetMax,o.anchorMin.x===o.anchorMax.x&&(r.size={...r.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(r.size={...r.size,y:0}),e.insert(t,Ys,r)}function Ks(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Qs(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Zs(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(let o=0;o<t.length;o++){const i=t[o],a=n+i;if(e.measureText(a).width>s&&n){if(Qs(i.charCodeAt(0))&&n.length>0&&Qs(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!Qs(n.charCodeAt(t))){e=t;break}e>=0?(r.push(n.substring(0,e+1)),n=n.substring(e+1)+i):(r.push(n),n=i)}else r.push(n),n=i}else n=a}n&&r.push(n)}return r.length>0?r:[""]}function en(e){let t=1;for(;t<e;)t*=2;return t}function tn(e,t){let s=0,n=t;for(;e.has(n,le);){const t=e.get(n,le).entity;if(!e.valid(t))break;s++,n=t}return s}function sn(e){return e._computedWidth??e.size.x}function nn(e){return e._computedHeight??e.size.y}function rn(e,t,s){let n=t;for(;e.has(n,le);){const t=e.get(n,le).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function on(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function an(e,t,s,n,r){if(!e.has(t,Ys))return;const o=e.get(t,Ys),i=Vs(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s,o.pivot),a=i.rect.right-i.rect.left,l=i.rect.top-i.rect.bottom;if(o._computedWidth=a,o._computedHeight=l,e.has(t,re)){const s=e.get(t,re);s.size.x===a&&s.size.y===l||(s.size.x=a,s.size.y=l,e.insert(t,re,s))}if(!o._layoutManaged&&e.has(t,se)){const s=e.get(t,se);s.position.x=i.originX-n,s.position.y=i.originY-r,e.insert(t,se,s)}}function ln(e){const t=Object.keys(e),s=t.map(t=>e[t]);return{take(e){const n={};for(let r=0;r<t.length;r++)n[t[r]]=s[r](e);return n},changed(e,n){for(let r=0;r<t.length;r++)if(e[t[r]]!==s[r](n))return!0;return!1},update(e,n){for(let r=0;r<t.length;r++)e[t[r]]=s[r](n)}}}const cn={r:.3,g:.5,b:.8,a:1},un={Left:0,Center:1,Right:2},dn={Top:0,Middle:1,Bottom:2},hn={Visible:0,Clip:1,Ellipsis:2},pn=X("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:un.Left,verticalAlign:dn.Top,wordWrap:!0,overflow:hn.Visible,lineHeight:1.2});class fn{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=a(L.textCanvasSize,L.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,en(this.frameMaxW_)),e.height=Math.max(e.height,en(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=en(this.frameMaxW_),e.height=en(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const 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=Zs(s,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=r?Math.ceil(o):d+2*u,f=r?Math.ceil(i):h+2*u;if(r&&e.overflow===hn.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)}}this.frameMaxW_=Math.max(this.frameMaxW_,p),this.frameMaxH_=Math.max(this.frameMaxH_,f),(n.width<p||n.height<f)&&(n.width=Math.max(n.width,en(p)),n.height=Math.max(n.height,en(f)));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;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}, ${y}, ${m}, ${_})`,r&&e.overflow===hn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const x=l.length*c;let w;if(r)switch(e.verticalAlign){case dn.Top:w=u;break;case dn.Middle:w=u+(f-2*u-x)/2;break;case dn.Bottom:w=f-x-u;break;default:w=u}else w=u;let v=w;for(const t of l){let n;switch(e.align){case un.Left:n=u;break;case un.Center:n=p/2;break;case un.Right:n=p-u;break;default:n=u}s.fillText(t,n,v),v+=c}r&&e.overflow===hn.Clip&&s.restore();const b=s.getImageData(0,0,p,f),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(p,f,M,S.length,1,!0);return this.module._free(M),{textureHandle:T,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const 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()}measureWidth(e){let t=0;for(const s of e)t=Math.max(t,this.ctx.measureText(s).width);return t}mapAlign(e){switch(e){case un.Left:return"left";case un.Center:return"center";case un.Right:return"right"}}}const gn=ln({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?sn(e.uiRect):0,containerHeight:e=>e.uiRect?nn(e.uiRect):0});class yn{build(e){J("Text",pn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new fn(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,Fe([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,pn));for(const e of r.keys())if(!n.valid(e)||!n.has(e,pn)){if(n.valid(e)&&n.has(e,re)){const t=n.get(e,re);t.texture=U,n.insert(e,re,t)}r.delete(e)}const e=n.getEntitiesWithComponents([pn]);for(const t of e){const e=n.get(t,pn),o=n.has(t,Ys)?n.get(t,Ys):null,i={text:e,uiRect:o},a=r.get(t);if(a&&!gn.changed(a,i))continue;Gs(n,t);const l=s.renderForEntity(t,e,o),c=n.get(t,re);c.texture=l.textureHandle,c.size.x=l.width,c.size.y=l.height,c.uvOffset.x=0,c.uvOffset.y=0,c.uvScale.x=1,c.uvScale.y=1,n.insert(t,re,c),r.set(t,gn.take(i))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const mn=new yn,_n=X("UIMask",{enabled:!0,mode:"scissor"});function xn(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 wn(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],p=e[10],f=e[11],g=e[12],y=e[13],m=e[14],_=e[15],x=n*l-r*a,w=n*c-o*a,v=n*u-i*a,b=r*c-o*l,S=r*u-i*l,P=o*u-i*c,M=d*y-h*g,T=d*m-p*g,E=d*_-f*g,C=h*m-p*y,A=h*_-f*y,R=p*_-f*m;let I=x*R-w*A+v*C+b*E-S*T+P*M;return 0===I||(I=1/I,s[0]=(l*R-c*A+u*C)*I,s[1]=(o*A-r*R-i*C)*I,s[2]=(y*P-m*S+_*b)*I,s[3]=(p*S-h*P-f*b)*I,s[4]=(c*E-a*R-u*T)*I,s[5]=(n*R-o*E+i*T)*I,s[6]=(m*v-g*P-_*w)*I,s[7]=(d*P-p*v+f*w)*I,s[8]=(a*A-l*E+u*M)*I,s[9]=(r*E-n*A-i*M)*I,s[10]=(g*S-y*v+_*x)*I,s[11]=(h*v-d*S-f*x)*I,s[12]=(l*T-a*C-c*M)*I,s[13]=(n*C-r*T+o*M)*I,s[14]=(y*w-g*b-m*x)*I,s[15]=(d*b-h*w+p*x)*I),s}function vn(e,t,s,n,r,o,i){const a=(e-n)/o*2-1,l=(t-r)/i*2-1,c=s[0]*a+s[4]*l+s[12],u=s[1]*a+s[5]*l+s[13],d=s[3]*a+s[7]*l+s[15];return{x:c/d,y:u/d}}function bn(e,t){return 2*Math.atan2(e,t)}function Sn(e,t,s,n,r,o,i){const a=s[0]*e+s[4]*t+s[12],l=s[1]*e+s[5]*t+s[13],c=s[3]*e+s[7]*t+s[15];return[n+(.5*(a/c)+.5)*o,r+(.5*(l/c)+.5)*i]}function Pn(e,t,s,n,r,o,i,a,l,c){const u=bn(l,c),d=Math.sin(-u),h=Math.cos(-u),p=e-s,f=t-n,g=p*h-f*d+s,y=p*d+f*h+n;return g>=s-r*i&&g<=s+r*(1-i)&&y>=n-o*a&&y<=n+o*(1-a)}function Mn(e,t,s,n,r,o,i){if(!e.has(t,Ys)||!e.has(t,ne))return null;const a=e.get(t,Ys),l=e.get(t,ne),c=sn(a)*l.scale.x,u=nn(a)*l.scale.y,d=l.position.x,h=l.position.y,p=a.pivot.x,f=a.pivot.y,g=-c*p,y=c*(1-p),m=-u*f,_=u*(1-f),x=bn(l.rotation.z,l.rotation.w),w=Math.cos(x),v=Math.sin(x),b=[[d+g*w-m*v,h+g*v+m*w],[d+y*w-m*v,h+y*v+m*w],[d+y*w-_*v,h+y*v+_*w],[d+g*w-_*v,h+g*v+_*w]];let S=1/0,P=1/0,M=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=Sn(e,t,s,n,r,o,i);S=Math.min(S,a),P=Math.min(P,l),M=Math.max(M,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(P),w:Math.round(M-S),h:Math.round(T-P)}}function Tn(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([_n]);if(0===l.length)return;const c=[],u=[],d=new Set,h=new Set;for(const e of l){const s=t.get(e,_n);s.enabled&&(d.add(e),"stencil"===s.mode?(u.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,r,o,i,a,l,c){const u=[];for(const e of n){let s=!0;rn(t,e,e=>{if(r.has(e)){if("scissor"===t.get(e,_n).mode)return s=!1,!0}return!1}),s&&u.push(e)}function d(n,u){const h=e.getChildEntities(s,n);for(const s of h){let n=u;if(r.has(s)){if("scissor"===t.get(s,_n).mode){const e=Mn(t,s,o,i,a,l,c);e&&(n=xn(u,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=Mn(t,e,o,i,a,l,c);s&&d(e,s)}}(e,t,s,c,d,n,r,o,i,a),u.length>0&&function(e,t,s,n,r){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0;rn(t,e,e=>!!r.has(e)&&(s=!1,!0)),s&&o.push(e)}let i=1,a=!1;function l(){return i>255?(a||console.warn("Stencil mask overflow"),a=!0,null):i++}function c(t,n){if(a)return;e.renderer_setEntityStencilMask(t,n);const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),u(t,n)}function u(t,n){if(a)return;const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),u(t,n)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,s,u,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class En{build(e){if(J("UIMask",_n),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Tn(e.wasmModule,e.world))}}const Cn=new En,An=X("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),Rn=X("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),In={Normal:0,Hovered:1,Pressed:2,Disabled:3},Fn=X("Button",{state:In.Normal,transition:null});class Dn{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 kn=we(new Dn,"UIEvents"),Bn=N("ScreenSpace"),Ln=ln({anchorMinX:e=>e.anchorMin.x,anchorMinY:e=>e.anchorMin.y,anchorMaxX:e=>e.anchorMax.x,anchorMaxY:e=>e.anchorMax.y,offsetMinX:e=>e.offsetMin.x,offsetMinY:e=>e.offsetMin.y,offsetMaxX:e=>e.offsetMax.x,offsetMaxY:e=>e.offsetMax.y,sizeX:e=>e.size.x,sizeY:e=>e.size.y});function Un(e,t,s,n,r,o){if(!e.has(t,Ys))return;const i=e.get(t,Ys),a=Vs(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,s,i.pivot),l=a.rect.right-a.rect.left,c=a.rect.top-a.rect.bottom;if(i._computedWidth=l,i._computedHeight=c,e.has(t,re)){const s=e.get(t,re);s.size.x===l&&s.size.y===c||(s.size.x=l,s.size.y=c,e.insert(t,re,s))}if(!i._layoutManaged){const s=e.get(t,se);o?(s.position.x=a.originX,s.position.y=a.originY):(s.position.x=a.originX-n,s.position.y=a.originY-r),e.insert(t,se,s)}if(!e.has(t,ce))return;const u=e.get(t,ce);if(u&&u.entities)for(const t of u.entities)e.valid(t)&&Un(e,t,a.rect,a.originX,a.originY,!1)}class Wn{build(e){J("UIRect",Ys);const t=e.world,s=new Map,n=new Map;let r=NaN,o=NaN,i=NaN,a=NaN;function l(e){let s=n.get(e);return void 0!==s||(s=function(e,t){let s=t;for(;;){if(e.has(s,Bn))return s;if(!e.has(s,le))return null;const t=e.get(s,le);if(!e.valid(t.entity))return null;s=t.entity}}(t,e),n.set(e,s)),s}function c(e){if(n.delete(e),!t.has(e,ce))return;const s=t.get(e,ce);if(s&&s.entities)for(const e of s.entities)t.valid(e)&&c(e)}e.addSystemToSchedule(exports.Schedule.PreUpdate,Fe([ve(Ye)],e=>{if(!e.valid)return;const u={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},d=.5*(u.left+u.right),h=.5*(u.bottom+u.top),p=r!==e.worldLeft||o!==e.worldBottom||i!==e.worldRight||a!==e.worldTop;r=e.worldLeft,o=e.worldBottom,i=e.worldRight,a=e.worldTop;const f=new Set;if(p){n.clear();const e=t.getEntitiesWithComponents([Bn,Ys,se]);for(const t of e)f.add(t)}for(const e of s.keys())t.valid(e)&&t.has(e,Ys)||(s.delete(e),n.delete(e));const g=t.getEntitiesWithComponents([Ys]);for(const e of g){const n=t.get(e,Ys),r=s.get(e);if(n._dirty||!r||Ln.changed(r,n)){n._dirty=!1,c(e);const t=l(e);null!==t&&f.add(t)}}for(const e of f)Un(t,e,u,d,h,!0);for(const e of g){const n=t.get(e,Ys),r=s.get(e);r?Ln.update(r,n):s.set(e,Ln.take(n))}},{name:"UILayoutSystem"}))}}const zn=new Wn,$n=function(){const e=new Float32Array(16),t=new Float32Array(16);let s=!0;return{update(e){for(let n=0;n<16;n++)if(t[n]!==e[n]){t.set(e),s=!0;break}},getInverse:t=>(s&&(wn(t,e),s=!1),e)}}();function On(e,t,s,n){let r=!1;return rn(e,t,t=>{if(!e.has(t,_n))return!1;if(!e.get(t,_n).enabled||!e.has(t,Ys)||!e.has(t,ne))return!1;const o=e.get(t,ne),i=e.get(t,Ys),a=sn(i)*o.scale.x,l=nn(i)*o.scale.y;return!Pn(s,n,o.position.x,o.position.y,a,l,i.pivot.x,i.pivot.y,o.rotation.z,o.rotation.w)&&(r=!0,!0)}),r}function Hn(e,t,s,n){t.emit(s,n,s),rn(e,s,r=>{if(!e.has(r,An))return!1;const o=e.get(r,An);return o.enabled&&t.emit(r,n,s),o.blockRaycast})}class jn{build(e){J("Interactable",An),J("Button",Fn);const t=e.world,s=new Dn;e.insertResource(kn,s);let n=null,r=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,Fe([ve(Le),ve(Ye)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([Rn]);for(const e of i){const s=t.get(e,Rn);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a=c(),l=e.mouseX*a,u=o.screenH-e.mouseY*a;$n.update(o.viewProjection);const d=vn(l,u,$n.getInverse(o.viewProjection),o.vpX,o.vpY,o.vpW,o.vpH);o.worldMouseX=d.x,o.worldMouseY=d.y;const h=t.getEntitiesWithComponents([An,Ys,ne]);let p=null,f=-1/0;for(const e of h){on(t,e,Rn);const s=t.get(e,An);if(!s.enabled)continue;if(!s.raycastTarget)continue;const n=t.get(e,ne),r=t.get(e,Ys),o=sn(r)*n.scale.x,i=nn(r)*n.scale.y;if(Pn(d.x,d.y,n.position.x,n.position.y,o,i,r.pivot.x,r.pivot.y,n.rotation.z,n.rotation.w)){if(On(t,e,d.x,d.y))continue;let s=0;t.has(e,re)&&(s=t.get(e,re).layer),s>f&&(f=s,p=e)}}if(null===n||t.valid(n)||(n=null),n!==p){if(null!==n&&t.valid(n)&&t.has(n,Rn)){t.get(n,Rn).hovered=!1,s.emit(n,"hover_exit")}if(null!==p){t.get(p,Rn).hovered=!0,s.emit(p,"hover_enter")}n=p}if(e.isMouseButtonPressed(0)&&null!==p){const e=t.get(p,Rn);e.pressed=!0,e.justPressed=!0,r=p,Hn(t,s,p,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Rn)){const e=t.get(r,Rn);e.pressed=!1,e.justReleased=!0,Hn(t,s,r,"release"),r===n&&Hn(t,s,r,"click")}r=null}},{name:"UIInteractionSystem"}));const o=new Set;e.addSystemToSchedule(exports.Schedule.Update,Fe([],()=>{const e=t.getEntitiesWithComponents([Fn]);for(const s of e){if(on(t,s,An,{enabled:!0}),!t.has(s,Rn))continue;const e=t.get(s,Rn),n=t.get(s,Fn),r=t.get(s,An),i=!o.has(s),a=n.state;if(r.enabled?e.pressed?n.state=In.Pressed:e.hovered?n.state=In.Hovered:n.state=In.Normal:n.state=In.Disabled,i&&o.add(s),(i||a!==n.state)&&n.transition&&t.has(s,re)){const o=t.get(s,re);o.color=Ks(n.transition,r.enabled,e.pressed,e.hovered),t.insert(s,re,o)}}},{name:"ButtonSystem"}))}}const Xn=new jn,Nn=X("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}),Vn=X("Focusable",{tabIndex:0,isFocused:!1});class Yn{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 Gn=we(new Yn,"FocusManager");class qn{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){J("TextInput",Nn);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=a(L.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let i=!1,l=!0,c=0,u=0;const d=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!d)return;const h=d;function p(){const t=e.getResource(Gn);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,Nn)?n:null}const f=()=>{i||null===p()||x()},g=()=>{i=!0},y=()=>{i=!1,x()},m=t=>{const n=p();if(null===n)return;if("Escape"===t.key)return void w();const r=s.get(n,Nn);if("Enter"===t.key&&!r.multiline){t.preventDefault();return e.getResource(kn).emit(n,"submit"),void w()}let o=r.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,r.cursorPos-1):"ArrowRight"===t.key?o=Math.min(r.value.length,r.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=r.value.length),o!==r.cursorPos&&(r.cursorPos=o,h.selectionStart=o,h.selectionEnd=o,r.dirty=!0,v())},_=()=>{const t=p();if(null!==t){const n=s.get(t,Nn);n.focused=!1,n.dirty=!0;e.getResource(Gn).blur()}};function x(){const t=p();if(null===t)return;const n=s.get(t,Nn);if(n.readOnly)return;let r=h.value;if(n.maxLength>0&&r.length>n.maxLength&&(r=r.substring(0,n.maxLength),h.value=r),r!==n.value){n.value=r;e.getResource(kn).emit(t,"change")}n.cursorPos=h.selectionStart??r.length,n.dirty=!0,v()}function w(){const t=p();if(null!==t){const e=s.get(t,Nn);e.focused=!1,e.dirty=!0}e.getResource(Gn).blur(),h.blur()}function v(){l=!0,c=0}h.addEventListener("input",f),h.addEventListener("compositionstart",g),h.addEventListener("compositionend",y),h.addEventListener("keydown",m),h.addEventListener("blur",_),this.cleanupListeners_=()=>{h.removeEventListener("input",f),h.removeEventListener("compositionstart",g),h.removeEventListener("compositionend",y),h.removeEventListener("keydown",m),h.removeEventListener("blur",_),h.remove();const e=t.getResourceManager();for(const t of n.values())e.releaseTexture(t);n.clear()};let b=null;function S(e,i,a,c){(r.width<a||r.height<c)&&(r.width=en(Math.max(r.width,a)),r.height=en(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,p=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*p.r)}, ${Math.round(255*p.g)}, ${Math.round(255*p.b)}, ${p.a})`;const f=Math.ceil(1.2*i.fontSize),g=i.padding;if(i.multiline){const e=Zs(o,h,a-2*g);let t=g;for(const s of e)o.fillText(s,g,t),t+=f}else{const e=(c-i.fontSize)/2;o.fillText(h,g,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,s,n;if(i.multiline){const e=Zs(o,i.value,a-2*g);let r=0,l=0,c=0;for(let t=0;t<e.length;t++){const s=e[t].length;if(r+s>=i.cursorPos){l=t,c=i.cursorPos-r;break}r+=s,t<e.length-1&&r<i.value.length&&"\n"===i.value[r]&&r++,l=t+1,c=0}const u=l<e.length?e[l].substring(0,c):"";t=g+o.measureText(u).width,s=g+l*f,n=f}else t=g+o.measureText(e).width,s=(c-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 y=o.getImageData(0,0,a,c),m=new Uint8Array(y.data.buffer),_=t.getResourceManager(),x=t._malloc(m.length);t.HEAPU8.set(m,x);const w=n.get(e);void 0!==w&&_.releaseTexture(w);const v=_.createTexture(a,c,x,m.length,1,!0);n.set(e,v),t._free(x);const b=s.get(e,re);b.texture=v,b.size.x=a,b.size.y=c,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},s.insert(e,re,b)}e.addSystemToSchedule(exports.Schedule.Update,Fe([ve(Gn)],e=>{const t=s.getEntitiesWithComponents([Nn]);for(const e of t)on(s,e,Vn,{tabIndex:0,isFocused:!1}),on(s,e,An,{enabled:!0,blockRaycast:!0});const n=p();if(n!==b){if(null!==b&&s.valid(b)&&s.has(b,Nn)){const e=s.get(b,Nn);e.focused=!1,e.dirty=!0,h.blur()}null!==n&&function(e){const t=s.get(e,Nn);t.readOnly||(t.focused=!0,t.dirty=!0,h.value=t.value,h.selectionStart=t.cursorPos,h.selectionEnd=t.cursorPos,h.focus(),v())}(n),b=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(exports.Schedule.PreUpdate,Fe([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let r=0===u?0:(e-u)/1e3;u=e,r=Math.min(r,.1);const o=p();if(null!==o&&(c+=r,c>=.5)){c-=.5,l=!l;s.get(o,Nn).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Nn)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Nn,Ys]);for(const e of a){const t=s.get(e,Nn);if(!t.dirty)continue;const n=s.get(e,Ys),r=Math.ceil(n.size.x),o=Math.ceil(n.size.y);r<=0||o<=0||(Gs(s,e),S(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Jn=new qn,Kn={Simple:0,Sliced:1,Tiled:2,Filled:3},Qn={Horizontal:0,Vertical:1},Zn={Left:0,Right:1,Bottom:2,Top:3},er=X("Image",{texture:U,color:{r:1,g:1,b:1,a:1},imageType:Kn.Simple,fillMethod:Qn.Horizontal,fillOrigin:Zn.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),tr=ln({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,layer:e=>e.image.layer,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?sn(e.uiRect):0,rectHeight:e=>e.uiRect?nn(e.uiRect):0,enabled:e=>e.image.enabled});const sr=new class{build(e){J("Image",er);const t=e.world,s=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,Fe([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,er)||s.delete(e);const e=t.getEntitiesWithComponents([er]);for(const n of e){const e=t.get(n,er),r=t.has(n,Ys)?t.get(n,Ys):null,o={image:e,uiRect:r},i=s.get(n);if(i&&!tr.changed(i,o))continue;Gs(t,n);const a=t.get(n,re);if(e.enabled){if(a.texture=e.texture,a.color.r=e.color.r,a.color.g=e.color.g,a.color.b=e.color.b,a.color.a=e.color.a,a.layer=e.layer,a.material=e.material,r&&(a.size.x=sn(r),a.size.y=nn(r)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Kn.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===Qn.Horizontal?e.fillOrigin===Zn.Left?(a.uvScale.x=t,a.size.x=s*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=s*t):e.fillOrigin===Zn.Bottom?(a.uvScale.y=t,a.size.y=n*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=n*t)}else e.imageType===Kn.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale.x=a.size.x/e.tileSize.x,a.uvScale.y=a.size.y/e.tileSize.y);t.insert(n,re,a),s.set(n,tr.take(o))}else a.color.a=0,t.insert(n,re,a),s.set(n,tr.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},nr=X("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),rr=X("ToggleGroup",{allowSwitchOff:!1});const or=new class{build(e){J("Toggle",nr),J("ToggleGroup",rr);const t=e.world,s=new Set;e.addSystemToSchedule(exports.Schedule.Update,Fe([ve(kn)],e=>{const n=t.getEntitiesWithComponents([nr]),r=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,nr);n.isOn&&0!==n.group&&t.valid(n.group)&&(r.has(n.group)?n.isOn=!1:r.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,nr);if(0!==s.group&&t.valid(s.group)){let t=o.get(s.group);t||(t=[],o.set(s.group,t)),t.push(e)}}for(const s of n){if(on(t,s,An,{enabled:!0}),!t.has(s,Rn))continue;const n=t.get(s,Rn),r=t.get(s,nr),i=t.get(s,An);if(n.justPressed&&i.enabled){const n=r.group,i=0!==n&&t.valid(n)&&t.has(n,rr);if(r.isOn&&i){if(!t.get(n,rr).allowSwitchOff)continue}if(r.isOn=!r.isOn,r.isOn&&i){const r=o.get(n);if(r)for(const n of r){if(n===s)continue;const r=t.get(n,nr);r.isOn&&(r.isOn=!1,e.emit(n,"change"))}}e.emit(s,"change")}if(r.graphicEntity&&t.valid(r.graphicEntity)&&t.has(r.graphicEntity,re)){const e=t.get(r.graphicEntity,re);e.enabled=r.isOn,t.insert(r.graphicEntity,re,e)}if(r.transition&&t.has(s,re)){const e=t.get(s,re);e.color=Ks(r.transition,i.enabled,n.pressed,n.hovered),t.insert(s,re,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},ir=Ns,ar=X("ProgressBar",{value:0,fillEntity:0,direction:Ns.LeftToRight});const lr=new class{build(e){J("ProgressBar",ar);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Fe([],()=>{const e=t.getEntitiesWithComponents([ar,Ys]);for(const s of e){const e=t.get(s,ar);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=Math.max(0,Math.min(1,e.value));Js(t,e.fillEntity,e.direction,n)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}},cr=X("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),ur=X("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}});const dr=new class{build(e){J("Draggable",cr),J("DragState",ur);const t=e.world,s=e.getResource(kn);let n=null,r={x:0,y:0},o=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,Fe([ve(Le),ve(Ye)],(e,i)=>{if(!i.valid)return;const a={x:i.worldMouseX,y:i.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([cr,Rn]);let s=null,o=-1/0,i=-1;for(const n of e){if(!t.get(n,cr).enabled)continue;if(t.get(n,Rn).hovered){let e=0;t.has(n,re)&&(e=t.get(n,re).layer);const r=tn(t,n);(e>o||e===o&&r>=i)&&(o=e,i=r,s=n)}}if(null!==s){n=s,r={x:a.x,y:a.y},t.has(s,ur)||t.insert(s,ur);const e=t.get(s,ur),o=t.get(s,ne);e.startWorldPos={x:o.position.x,y:o.position.y},e.currentWorldPos={x:o.position.x,y:o.position.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==n&&!e.isMouseButtonDown(0)){if(t.valid(n)&&t.has(n,ur)){t.get(n,ur).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=a.x-r.x,l=a.y-r.y,c=Math.sqrt(e*e+l*l),u=t.get(n,cr);if(c*(i.vpW/(i.worldRight-i.worldLeft))>=u.dragThreshold){o=n,n=null;t.get(o,ur).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,ur))return void(o=null);const n=t.get(o,ur),r=t.get(o,cr),i=a.x-n.pointerStartWorld.x,l=a.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+i,u=n.startWorldPos.y+l;const d=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,u);c=d.x,u=d.y;const h=n.currentWorldPos.x,p=n.currentWorldPos.y;if(n.deltaWorld={x:c-h,y:u-p},n.currentWorldPos={x:c,y:u},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:u-n.startWorldPos.y},t.has(o,se)){const e=function(e,t,s,n){if(!e.has(t,le))return{x:s,y:n};const r=e.get(t,le).entity;if(!e.valid(r)||!e.has(r,ne))return{x:s,y:n};const o=e.get(r,ne),i=0!==o.scale.x?o.scale.x:1,a=0!==o.scale.y?o.scale.y:1,l=bn(o.rotation.z,o.rotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(s*u-n*c)/i,y:(s*c+n*u)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,se);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,se,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},hr=X("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135});const pr=new class{build(e){J("ScrollView",hr);const t=e.world,s=new Map;let n=0;e.addSystemToSchedule(exports.Schedule.PreUpdate,Fe([ve(Le),ve(Ye)],(e,r)=>{const o=performance.now()/1e3,i=n>0?Math.min(o-n,.05):0;if(n=o,!r.valid)return;for(const[e]of s)t.valid(e)||s.delete(e);const a={x:r.worldMouseX,y:r.worldMouseY},l=t.getEntitiesWithComponents([hr,Ys]);for(const n of l){on(t,n,An,{enabled:!0,blockRaycast:!0}),on(t,n,_n,{enabled:!0,mode:"scissor"});const r=t.get(n,hr),o=t.get(n,Ys);let l=s.get(n);l||(l={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0},s.set(n,l));const c=t.has(n,Rn)?t.get(n,Rn):null;if(c?.justPressed&&(l.isDragging=!0,l.lastWorldX=a.x,l.lastWorldY=a.y,l.velocityX=0,l.velocityY=0),l.isDragging&&e.isMouseButtonDown(0)){const e=a.x-l.lastWorldX,t=a.y-l.lastWorldY;if(r.horizontalEnabled){r.scrollX-=e;const t=i>0?-e/i:0;l.velocityX=.8*l.velocityX+.2*t}if(r.verticalEnabled){r.scrollY-=t;const e=i>0?-t/i:0;l.velocityY=.8*l.velocityY+.2*e}l.lastWorldX=a.x,l.lastWorldY=a.y}if(l.isDragging&&e.isMouseButtonReleased(0)&&(l.isDragging=!1),c?.hovered){const t=e.getScrollDelta();r.verticalEnabled&&0!==t.y&&(r.scrollY+=.1*t.y,l.velocityY=0),r.horizontalEnabled&&0!==t.x&&(r.scrollX+=.1*t.x,l.velocityX=0)}if(!l.isDragging&&r.inertia&&i>0){const e=Math.pow(r.decelerationRate,60*i);r.horizontalEnabled&&Math.abs(l.velocityX)>.1?(r.scrollX+=l.velocityX*i,l.velocityX*=e):l.velocityX=0,r.verticalEnabled&&Math.abs(l.velocityY)>.1?(r.scrollY+=l.velocityY*i,l.velocityY*=e):l.velocityY=0}const u=sn(o),d=nn(o),h=Math.max(0,r.contentWidth-u),p=Math.max(0,r.contentHeight-d),f=r.scrollX,g=r.scrollY;if(r.scrollX=Math.max(0,Math.min(r.scrollX,h)),r.scrollY=Math.max(0,Math.min(r.scrollY,p)),r.scrollX!==f&&(l.velocityX=0),r.scrollY!==g&&(l.velocityY=0),0!==r.contentEntity&&t.valid(r.contentEntity)&&t.has(r.contentEntity,se)){const e=t.get(r.contentEntity,se);e.position.x=-r.scrollX,e.position.y=r.scrollY,t.insert(r.contentEntity,se,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UIInteractionSystem"]})}},fr=Ns,gr=X("Slider",{value:0,minValue:0,maxValue:1,direction:Ns.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});const yr=new class{build(e){J("Slider",gr);const t=e.world;let s=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,Fe([ve(Le),ve(Ye),ve(kn)],(e,n,r)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=n.worldMouseX,i=n.worldMouseY,a=t.getEntitiesWithComponents([gr,Ys,ne]);for(const n of a){on(t,n,An,{enabled:!0,blockRaycast:!0});const a=t.get(n,gr),l=t.get(n,Ys),c=t.get(n,ne),u=t.has(n,Rn)?t.get(n,Rn):null,d=a.handleEntity;if(0!==d&&t.valid(d)&&(on(t,d,An,{enabled:!0,blockRaycast:!1}),t.has(d,An))){const e=t.get(d,An);e.blockRaycast&&(e.blockRaycast=!1,t.insert(d,An,e))}let h=u?.justPressed??!1;if(!h&&0!==d&&t.valid(d)&&t.has(d,Rn)){h=t.get(d,Rn).justPressed}if(h&&(s=n),s===n&&e.isMouseButtonDown(0)){const e=sn(l),s=nn(l),u=e*c.scale.x,d=s*c.scale.y,h=bn(c.rotation.z,c.rotation.w),p=Math.sin(-h),f=Math.cos(-h),g=o-c.position.x,y=i-c.position.y,m=g*f-y*p,_=g*p+y*f,x=-l.pivot.x*u,w=-l.pivot.y*d;let v;switch(a.direction){case Ns.LeftToRight:v=u>0?(m-x)/u:0;break;case Ns.RightToLeft:v=u>0?1-(m-x)/u:0;break;case Ns.BottomToTop:v=d>0?(_-w)/d:0;break;case Ns.TopToBottom:v=d>0?1-(_-w)/d:0}v=Math.max(0,Math.min(1,v));let b=a.minValue+v*(a.maxValue-a.minValue);a.wholeNumbers&&(b=Math.round(b));const S=a.value;a.value=Math.max(a.minValue,Math.min(a.maxValue,b)),t.insert(n,gr,a),a.value!==S&&r.emit(n,"change")}s===n&&e.isMouseButtonReleased(0)&&(s=null);const p=a.maxValue-a.minValue,f=p>0?(a.value-a.minValue)/p:0,g=sn(l),y=nn(l),m=l.pivot,_={left:-m.x*g,bottom:-m.y*y,right:(1-m.x)*g,top:(1-m.y)*y};if(0!==a.fillEntity&&t.valid(a.fillEntity)&&(Js(t,a.fillEntity,a.direction,f),an(t,a.fillEntity,_,0,0)),0!==a.handleEntity&&t.valid(a.handleEntity)){if(t.has(a.handleEntity,Ys)){const e=t.get(a.handleEntity,Ys);switch(e.offsetMin={x:0,y:0},e.offsetMax={x:0,y:0},a.direction){case Ns.LeftToRight:e.anchorMin={x:f,y:0},e.anchorMax={x:f,y:1};break;case Ns.RightToLeft:e.anchorMin={x:1-f,y:0},e.anchorMax={x:1-f,y:1};break;case Ns.BottomToTop:e.anchorMin={x:0,y:f},e.anchorMax={x:1,y:f};break;case Ns.TopToBottom:e.anchorMin={x:0,y:1-f},e.anchorMax={x:1,y:1-f}}t.insert(a.handleEntity,Ys,e)}an(t,a.handleEntity,_,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}};const mr=new class{build(e){J("Focusable",Vn);const t=e.world,s=new Yn;e.insertResource(Gn,s),e.addSystemToSchedule(exports.Schedule.Update,Fe([ve(Le),ve(kn)],(e,n)=>{null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const r=t.getEntitiesWithComponents([Vn]);for(const e of r){if(!t.has(e,Rn))continue;t.get(e,Rn).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const n=function(){const e=[];for(const s of r){if(!t.valid(s))continue;if(t.has(s,An)){if(!t.get(s,An).enabled)continue}const n=t.get(s,Vn);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,Vn)){t.get(r,Vn).isFocused=!1,n.emit(r,"blur",r)}s.focus(e);t.get(e,Vn).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}},_r=X("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function xr(){return s()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:s,screenWidth:n,screenHeight:r}=t;return{top:s.top,bottom:r-s.bottom,left:s.left,right:n-s.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}const wr=new class{build(e){J("SafeArea",_r);const t=e.world;let n=xr(),r=!0,o=0,i=0;if(s()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=xr(),r=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=xr(),r=!0});e.addSystemToSchedule(exports.Schedule.PreUpdate,Fe([ve(Ye)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===i||(o=e.screenH,i=a,r=!0),!r)return;r=!1;const l=c(),u=s()?a/e.screenH:l*a/e.screenH,d=t.getEntitiesWithComponents([_r,Ys]);for(const e of d){const s=t.get(e,_r),r=t.get(e,Ys),o=s.applyTop?n.top*u:0,i=s.applyBottom?n.bottom*u:0,a=s.applyLeft?n.left*u:0,l=s.applyRight?n.right*u:0;let c=!1;r.offsetMin.x===a&&r.offsetMin.y===i||(r.offsetMin={x:a,y:i},c=!0),r.offsetMax.x===-l&&r.offsetMax.y===-o||(r.offsetMax={x:-l,y:-o},c=!0),c&&t.insert(e,Ys,r)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},vr=X("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let br=null;const Sr=new class{build(e){J("ListView",vr);const t=e.world,s=new Map;br=s,e.addSystemToSchedule(exports.Schedule.PreUpdate,Fe([ve(Le)],e=>{for(const[e,n]of s)if(!t.valid(e)){for(const e of n.itemEntities.values())t.valid(e)&&t.despawn(e);s.delete(e)}const n=t.getEntitiesWithComponents([vr,Ys]);for(const r of n){on(t,r,An,{enabled:!0,blockRaycast:!0}),on(t,r,_n,{enabled:!0,mode:"scissor"});let n=s.get(r);n||(n={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},s.set(r,n));const o=t.get(r,vr),i=t.get(r,Ys),a=i._computedHeight??i.size.y,l=i._computedWidth??i.size.x,c=t.has(r,Rn)?t.get(r,Rn):null;if(c?.hovered){const t=e.getScrollDelta();0!==t.y&&(o.scrollY+=.1*t.y)}const u=Math.max(0,o.itemCount*o.itemHeight-a);o.scrollY=Math.max(0,Math.min(o.scrollY,u));const d=Math.max(0,Math.floor(o.scrollY/o.itemHeight)-o.overscan),h=Math.min(o.itemCount,Math.ceil((o.scrollY+a)/o.itemHeight)+o.overscan);for(const[e,s]of n.itemEntities)(e<d||e>=h)&&(t.valid(s)&&t.despawn(s),n.itemEntities.delete(e));for(let e=d;e<h;e++){let s=n.itemEntities.get(e);if(s&&t.valid(s)||(s=t.spawn(),t.insert(s,he,{value:`ListItem_${e}`}),t.insert(s,Ys,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:l,y:o.itemHeight},pivot:{x:.5,y:1}}),t.setParent(s,r),n.itemEntities.set(e,s),n.renderer&&n.renderer(e,s)),t.has(s,se)){const n=t.get(s,se);n.position.y=-(e*o.itemHeight-o.scrollY),t.insert(s,se,n)}}n.visibleStart=d,n.visibleEnd=h}},{name:"ListViewSystem"}))}},Pr=X("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const Mr=new class{build(e){J("Dropdown",Pr);const t=e.world,s=new Map;function n(e,s,n){s.isOpen=!0,n.highlightIndex=s.selectedIndex;const r=s.listEntity;if(0===r||!t.valid(r))return;l(r,!0),t.has(r,_n)||t.insert(r,_n,{enabled:!0,mode:"scissor"}),a(n);const o=t.has(r,Ys)?t.get(r,Ys):null,i=o?o.size.x:160;for(let e=0;e<s.options.length;e++){const o=t.spawn();t.insert(o,he,{value:`Option_${e}`}),t.insert(o,Ys,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:i,y:30},pivot:{x:.5,y:1}}),t.insert(o,se,{position:{x:0,y:-30*e,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(o,pn,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:1,g:1,b:1,a:1},align:un.Left,verticalAlign:dn.Middle,wordWrap:!1,overflow:hn.Clip,lineHeight:1.2}),t.insert(o,re,{texture:0,color:{r:1,g:1,b:1,a:0},size:{x:i,y:30},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,An,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,r),n.optionEntities.push(o)}o&&(o.size.y=30*s.options.length,t.insert(r,Ys,o)),c(n)}function r(e,t,s){t.isOpen=!1,a(s),l(t.listEntity,!1)}function o(e,t,s,n,o){t.selectedIndex=n,r(0,t,s),o.emit(e,"change")}function i(e){const s=e.labelEntity;if(0===s||!t.valid(s))return;if(!t.has(s,pn))return;const n=t.get(s,pn),r=e.selectedIndex>=0&&e.selectedIndex<e.options.length?e.options[e.selectedIndex]:"";n.content!==r&&(n.content=r,t.insert(s,pn,n))}function a(e){for(const s of e.optionEntities)t.valid(s)&&t.despawn(s);e.optionEntities=[]}function l(e,s){if(0!==e&&t.valid(e)){if(t.has(e,An)){const n=t.get(e,An);n.enabled=s,t.insert(e,An,n)}if(t.has(e,re)){const n=t.get(e,re);n.enabled=s,t.insert(e,re,n)}}}function c(e){for(let s=0;s<e.optionEntities.length;s++){const n=e.optionEntities[s];if(!t.valid(n)||!t.has(n,re))continue;const r=t.get(n,re);s===e.highlightIndex?r.color={...cn}:r.color={r:1,g:1,b:1,a:0},t.insert(n,re,r)}}function u(e){for(const s of e.optionEntities){if(!t.valid(s)||!t.has(s,Rn))continue;if(t.get(s,Rn).hovered)return!0}return!1}e.addSystemToSchedule(exports.Schedule.Update,Fe([ve(Le),ve(kn)],(e,a)=>{for(const[e]of s)t.valid(e)||s.delete(e);const l=t.getEntitiesWithComponents([Pr]);for(const d of l){on(t,d,An,{enabled:!0,blockRaycast:!0});const l=t.get(d,Pr),h=t.has(d,Rn)?t.get(d,Rn):null;let p=s.get(d);if(p||(p={optionEntities:[],highlightIndex:-1},s.set(d,p)),h?.justPressed&&(l.isOpen?r(d,l,p):n(d,l,p)),l.isOpen){for(let e=0;e<p.optionEntities.length;e++){const s=p.optionEntities[e];if(!t.valid(s)||!t.has(s,Rn))continue;if(t.get(s,Rn).justPressed){o(d,l,p,e,a);break}}e.isKeyPressed("ArrowDown")?(p.highlightIndex>=l.options.length-1?p.highlightIndex=0:p.highlightIndex++,c(p)):e.isKeyPressed("ArrowUp")?(p.highlightIndex<=0?p.highlightIndex=l.options.length-1:p.highlightIndex--,c(p)):e.isKeyPressed("Enter")&&p.highlightIndex>=0?o(d,l,p,p.highlightIndex,a):e.isKeyPressed("Escape")&&r(d,l,p),e.isMouseButtonPressed(0)&&(h?.hovered||u(p)||r(d,l,p))}i(l)}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},Tr=0,Er=0,Cr=2,Ar=X("LayoutGroup",{direction:Tr,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Er,reverseOrder:!1});const Rr=new class{build(e){J("LayoutGroup",Ar);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Fe([],()=>{const e=t.getEntitiesWithComponents([Ar,Ys,ce]);for(const s of e){const e=t.get(s,Ar),n=t.get(s,Ys),r=t.get(s,ce);if(!r.entities||0===r.entities.length)continue;const o=[];for(const e of r.entities)t.valid(e)&&t.has(e,Ys)&&t.has(e,se)&&o.push({entity:e,rect:t.get(e,Ys)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const i=n._computedWidth??n.size.x,a=n._computedHeight??n.size.y,l=n.pivot.x,c=n.pivot.y,u=e.padding,d=e.direction===Tr;let h=0;for(let s=0;s<o.length;s++){const n=o[s],r=n.rect._computedWidth??n.rect.size.x,p=n.rect._computedHeight??n.rect.size.y,f=n.rect.pivot.x,g=n.rect.pivot.y;let y,m;d?(y=-l*i+u.left+h+f*r,m=e.childAlignment===Er?(1-c)*a-u.top-(1-g)*p:e.childAlignment===Cr?-c*a+u.bottom+g*p:(.5-c)*a+.5*(u.bottom-u.top)+(g-.5)*p,h+=r,s<o.length-1&&(h+=e.spacing)):(y=e.childAlignment===Er?-l*i+u.left+f*r:e.childAlignment===Cr?(1-l)*i-u.right-(1-f)*r:(.5-l)*i+.5*(u.left-u.right)+(f-.5)*r,m=(1-c)*a-u.top-h-(1-g)*p,h+=p,s<o.length-1&&(h+=e.spacing)),n.rect._layoutManaged=!0;const _=t.get(n.entity,se);_.position.x=y,_.position.y=m,t.insert(n.entity,se,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};function Ir(e,t,s){if(e.has(t,re)&&e.has(t,Ys)){const n=e.get(t,re);n.layer!==s&&(n.layer=s,e.insert(t,re,n)),s++}if(!e.has(t,ce))return s;const n=e.get(t,ce);if(!n||!n.entities)return s;for(const t of n.entities)e.valid(t)&&(s=Ir(e,t,s));return s}const Fr=new class{build(e){const t=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,Fe([],()=>{let e=0;const s=t.getEntitiesWithComponents([Bn,Ys]);for(const n of s)e=Ir(t,n,e)},{name:"UIRenderOrderSystem"}))}};async function Dr(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const kr=we({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Br=we(null,"PhysicsAPI");function Lr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Ur(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Wr{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(kr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Dr(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([ie]);for(const s of t){const t=e.world.get(s,ie);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,Fe([ve(Me)],a=>{const l=i.getEntitiesWithComponents([fe,se,ne]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,fe),l=i.get(r,ne);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=Lr(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),zr(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===_e.Kinematic){const e=Lr(l.rotation);n._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<n;r++){const n=o+4*r,i=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const u=e.world.get(i,se);if(!u)continue;let d=a,h=l,p=c;if(e.world.has(i,le)){const t=e.world.get(i,le);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ne)){const s=e.world.get(t.entity,ne),n=Lr(s.rotation),r=a-s.position.x,o=l-s.position.y,i=Math.cos(-n),u=Math.sin(-n);d=(r*i-o*u)/(0!==s.scale.x?s.scale.x:1),h=(r*u+o*i)/(0!==s.scale.y?s.scale.y:1),p=c-n}}u.position.x=d,u.position.y=h;const f=Ur(p);u.rotation.w=f.w,u.rotation.x=f.x,u.rotation.y=f.y,u.rotation.z=f.z,e.world.insert(i,se,u)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<i;s++){const n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(kr,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Br,$r._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function zr(e,t,s){const n=e.world;if(n.has(s,ge)){const e=n.get(s,ge);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,ye)){const e=n.get(s,ye);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,me)){const e=n.get(s,me);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 $r{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($r.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 Or(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 Hr(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 jr(e,t,s,n){const r=e.scale.x*t*(s?-1:1),o=e.scale.y*t*(n?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,p=c+c,f=a*d,g=a*h,y=a*p,m=l*h,_=l*p,x=c*p,w=u*d,v=u*h,b=u*p;return new Float32Array([(1-(m+x))*r,(g+b)*r,(y-v)*r,0,(g-b)*o,(1-(f+x))*o,(_+w)*o,0,(y+v)*i,(_-w)*i,(1-(f+m))*i,0,e.position.x,e.position.y,e.position.z,1])}async function Xr(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){const r=gt(t.type);for(const o of r){if("texture"!==o.type)continue;const r=t.data[o.field];if("string"==typeof r&&r&&void 0===n[r])try{n[r]=Or(e,await s.loadPixels(r))}catch{n[r]=0}}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,c);let u={},d=null;if(r&&(d=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),u=await async function(e,t,s,n,r){const o={};for(const i of n.entities)for(const n of i.components){const i=yt(n.type);if(!i||!n.data)continue;const a=n.data[i.skeletonField],l=n.data[i.atlasField];if(!a||!l)continue;const c=r.resolvePath(a),u=r.resolvePath(l);try{const n=await r.readText(l),i="binary"===m(c)?.contentType;let d,h;if(i){const e=await r.readBinary(a);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await r.readText(a),s=(new TextEncoder).encode(e);h=s.length,d=t._malloc(h+1),t.HEAPU8.set(s,d),t.HEAPU8[d+h]=0}const p=s.loadSkeleton(d,h,n,n.length,i);if(t._free(d),p<0)continue;o[a]=p;const f=Hr(n),g=u.substring(0,u.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=g+"/"+f[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),i=Or(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,d,s,n)),o){const t={gravity:i?.gravity??{...k},fixedTimestep:i?.fixedTimestep??B,subStepCount:i?.subStepCount??4};new Wr("",t,()=>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){const r=gt(t.type).find(e=>"font"===e.type);if(!r)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===n[o])try{let t,r;const i=m(o);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await s.readText(o)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){n[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await s.readText(l),r=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(o),r=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[o]=0;continue}const l=r?`${r}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),u=Or(e,c,!1),d=e.getResourceManager();n[o]=d.loadBitmapFont(t,u,c.width,c.height)}catch{n[o]=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)continue;const r=gt(e.type).find(e=>"material"===e.type);if(!r)continue;const o=e.data[r.field];if("string"==typeof o&&o&&void 0===s[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){s[o]=0;continue}const r=e.vertexSource+e.fragmentSource;let i=n[r];i||(i=nt.createShader(e.vertexSource,e.fragmentSource),n[r]=i),s[o]=nt.createFromAsset(e,i)}catch{s[o]=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=gt(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=wt(e.world,s);if(l&&e.hasResource(As))for(const t of f.values())e.world.insert(t,pe,{scene:l,persistent:!1});if(r&&d){const n=function(e,t,s,n){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const i=yt(t.type);if(!i||!t.data)continue;const a=s[t.data[i.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=n.get(o.id);void 0!==c&&(r[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return r}(d,s,u,f);!function(e,t,s,n,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=D);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,de)?c.get(o,de):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(i,l*d);let h=0;if(c.has(o,ne)){const e=jr(c.get(o,ne),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=n.getMeshBatchCount(i);for(let e=0;e<p;e++){const r=n.getMeshBatchVertexCount(i,e),o=n.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=s._malloc(a),u=s._malloc(l),d=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(i,e,c,u,d,p);const f=s.HEAPU32[d>>2],g=s.HEAPU32[p>>2],y=new Float32Array(s.HEAPF32.buffer,c,8*r),m=new Uint16Array(s.HEAPU8.buffer,u,o),_=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(y,_>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(m),t.renderer_submitTriangles(_,r,x,o,f,g,h),t._free(_),t._free(x),s._free(c),s._free(u),s._free(d),s._free(p)}h&&t._free(h)}})}(e,t,r,d,n)}if(a){const t=e.getResource(Mt);t&&t.setAddressableManifest(a)}}class Nr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components){if(!e.data)continue;const r=yt(e.type);if(r){const n=e.data[r.skeletonField],o=e.data[r.atlasField];n&&("binary"===m(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=gt(e.type);for(const s of o){const r=e.data[s.field];"string"==typeof r&&r&&("font"===s.type?(n.add(r),t.add(r)):"material"===s.type&&t.add(r))}}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=m(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 Vr="__preview__";const Yr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=xs.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:xs.getTargetTexture(s),width:e.width,height:e.height}},release(e){xs.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(xs.releaseRenderTarget(e._handle),Yr.create({width:t,height:s,depth:!0})),begin(e,t){xs.begin(t,e._handle)},end(){xs.end()},getDepthTexture:e=>xs.getTargetDepthTexture(e._handle)};let Gr=!1;var qr;exports.LogLevel=void 0,(qr=exports.LogLevel||(exports.LogLevel={}))[qr.Debug=0]="Debug",qr[qr.Info=1]="Info",qr[qr.Warn=2]="Warn",qr[qr.Error=3]="Error";class Jr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${exports.LogLevel[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case exports.LogLevel.Debug:console.debug(t,s);break;case exports.LogLevel.Info:console.log(t,s);break;case exports.LogLevel.Warn:console.warn(t,s);break;case exports.LogLevel.Error:console.error(t,s)}}}class Kr{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new Jr)}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 Qr=new Kr;const Zr=[mn,Cn,zn,sr,lr,Xn,dr,pr,yr,or,Jn,mr,wr,Sr,Mr,Rr,Fr];A||(A=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await u(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 d(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=R,exports.App=Ds,exports.AssetPlugin=Tt,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=Mt,exports.AsyncCache=ht,exports.BitmapText=ue,exports.BodyType=_e,exports.BoxCollider=ge,exports.Button=Fn,exports.ButtonState=In,exports.Camera=oe,exports.Canvas=ie,exports.CapsuleCollider=me,exports.Children=ce,exports.CircleCollider=ye,exports.ClearFlags=ee,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=Ae,exports.DEFAULT_DESIGN_HEIGHT=F,exports.DEFAULT_DESIGN_WIDTH=I,exports.DEFAULT_FALLBACK_DT=D,exports.DEFAULT_FIXED_TIMESTEP=B,exports.DEFAULT_FONT_FAMILY="Arial",exports.DEFAULT_FONT_SIZE=24,exports.DEFAULT_GRAVITY=k,exports.DEFAULT_LINE_HEIGHT=1.2,exports.DEFAULT_MAX_DELTA_TIME=.5,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_SPINE_SKIN="default",exports.DEFAULT_SPRITE_SIZE={x:100,y:100},exports.DEFAULT_TEXT_CANVAS_SIZE=512,exports.DragState=ur,exports.Draggable=cr,exports.Draw=Nt,exports.Dropdown=Pr,exports.EntityCommands=Ce,exports.FillDirection=Ns,exports.FillMethod=Qn,exports.FillOrigin=Zn,exports.FocusManager=Gn,exports.FocusManagerState=Yn,exports.Focusable=Vn,exports.GLDebug=Ss,exports.Geometry=as,exports.INVALID_ENTITY=0,exports.INVALID_FONT=W,exports.INVALID_MATERIAL=0,exports.INVALID_TEXTURE=U,exports.Image=er,exports.ImageType=Kn,exports.Input=Le,exports.InputPlugin=Ue,exports.InputState=Be,exports.Interactable=An,exports.ListView=vr,exports.LocalTransform=se,exports.Logger=Kr,exports.Material=nt,exports.MaterialLoader=pt,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=he,exports.Parent=le,exports.Physics=$r,exports.PhysicsEvents=kr,exports.PhysicsPlugin=Wr,exports.PostProcess=hs,exports.PrefabServer=Ft,exports.Prefabs=Dt,exports.PrefabsPlugin=kt,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(As);t.register({name:Vr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Vr),this.loadPromise_=t.load(Vr).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await n(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new Nr(this.baseUrl_);await s.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await Xr(this.app_,this.app_.wasmModule,t,s,r,null,void 0,null,Vr)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([oe]);for(const n of s){if(e.get(n,oe).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([ie]);for(const r of n){const n=e.get(r,ie);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(As).getScene(Vr),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,se,i);const a={isActive:!0,projectionType:Z.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:ee.ColorAndDepth};e.insert(o,oe,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(As);await e.switchTo(Vr),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=ar,exports.ProgressBarDirection=ir,exports.ProjectionType=Z,exports.Query=function(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{Te(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)},exports.QueryInstance=Ee,exports.RenderPipeline=Ps,exports.RenderTexture=Yr,exports.Renderer=xs,exports.Res=ve,exports.ResMut=be,exports.RigidBody=fe,exports.RuntimeConfig=L,exports.SafeArea=_r,exports.ScaleMode=te,exports.SceneManager=As,exports.SceneManagerState=Cs,exports.SceneOwner=pe,exports.ScreenSpace=Bn,exports.ScrollView=hr,exports.ShaderSources=dt,exports.Slider=gr,exports.SliderDirection=fr,exports.SpineAnimation=de,exports.Sprite=re,exports.SystemRunner=ke,exports.Text=pn,exports.TextAlign=un,exports.TextInput=Nn,exports.TextInputPlugin=qn,exports.TextOverflow=hn,exports.TextPlugin=yn,exports.TextRenderer=fn,exports.TextVerticalAlign=dn,exports.Time=Me,exports.Toggle=nr,exports.UICameraInfo=Ye,exports.UIEventQueue=Dn,exports.UIEvents=kn,exports.UIInteraction=Rn,exports.UIInteractionPlugin=jn,exports.UILayoutPlugin=Wn,exports.UIMask=_n,exports.UIMaskPlugin=En,exports.UIRect=Ys,exports.Velocity=ae,exports.WebAssetProvider=Nr,exports.World=Ve,exports.WorldTransform=ne,exports.addStartupSystem=function(e){De().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){De().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){De().push({schedule:e,system:t})},exports.applyDirectionalFill=Js,exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=L.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=L.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=L.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=L.canvasMatchWidthOrHeight)},exports.assetPlugin=Et,exports.clearDrawCallbacks=Qt,exports.clearUserComponents=function(){const e=j();for(const t of e.keys())q.delete(t);e.clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeFillAnchors=qs,exports.computeFillSize=function(e,t,s,n){switch(e){case Ns.BottomToTop:case Ns.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}},exports.computeHandleAnchors=function(e,t){switch(e){case Ns.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case Ns.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case Ns.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1-t}};default:return{anchorMin:{x:t,y:0},anchorMax:{x:t,y:1}}}},exports.computeUIRectLayout=Vs,exports.createMaskProcessor=Tn,exports.createRuntimeSceneConfig=function(e,t,s){return{name:e,data:t,async setup(){await Xr(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=Ds.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ot(e),et(e),rs(e),cs(e),ms(e),vs(e);const r=new Ps;s.setPipeline(r);let o=l();const i=t?.getViewportSize??(()=>{const e=c();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,r,o){o||(o=Ls(e,n,t,r));const i=s.getResource(Ye);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(Ye,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const u={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},d={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=i();if(0===t||0===c)return;const u=e.registry_getCanvasEntity(n);if(u>=0){const e=n.getCanvas(u).backgroundColor;xs.setClearColor(e.x,e.y,e.z,e.w)}const d=(l()-o)/1e3;let h;if(xs.resize(t,c),hs.isInitialized()&&hs.getPassCount()>0&&!hs.isBypassed()&&hs.resize(t,c),s.hasResource(As)){const e=s.getResource(As).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const p=Ls(e,n,t,c,s.world,h);if(a(t,c,p),0===p.length)r.render({registry:{_cpp:n},viewProjection:ks,width:t,height:c,elapsed:d});else{for(const e of p){const s=e.viewportRect,o=Math.round(s.x*t),i=Math.round((1-s.y-s.h)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:l},clearFlags:e.clearFlags,elapsed:d})}xs.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(exports.Schedule.First,u),s.addSystemToSchedule(exports.Schedule.Last,d),s.addPlugin(Et),s.addPlugin(Bt),s.addPlugin(We),s.addPlugin(Fs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Zr,...t})},exports.debug=function(e,t,s){Qr.debug(e,t,s)},exports.defineComponent=X,exports.defineResource=we,exports.defineSystem=Fe,exports.defineTag=N,exports.error=function(e,t,s){Qr.error(e,t,s)},exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([he]);for(const n of s){const s=e.get(n,he);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 m(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of h)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return g},exports.getAssetMimeType=function(e){return p[e.toLowerCase()]},exports.getAssetTypeEntry=m,exports.getComponent=K,exports.getComponentAssetFields=function(e){const t=ft.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=K(e);return t?z(t._default):null},exports.getCustomExtensions=x,exports.getEditorType=function(e){return m(e)?.editorType??"unknown"},exports.getLogger=function(){return Qr},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=V,exports.getWeChatPackOptions=function(){return x().map(e=>({type:"suffix",value:e}))},exports.info=function(e,t,s){Qr.info(e,t,s)},exports.initDrawAPI=Ot,exports.initGLDebugAPI=vs,exports.initGeometryAPI=rs,exports.initMaterialAPI=et,exports.initPostProcessAPI=cs,exports.initRendererAPI=ms,exports.inputPlugin=We,exports.instantiatePrefab=Ct,exports.intersectRects=xn,exports.invertMatrix4=wn,exports.isBuiltinComponent=G,exports.isCustomExtension=w,exports.isEditor=function(){return Gr},exports.isKnownAssetExtension=_,exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!Gr},exports.isTextureRef=qe,exports.isWeChat=s,exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=St,exports.loadPhysicsModule=Dr,exports.loadRuntimeScene=Xr,exports.loadSceneData=wt,exports.loadSceneWithAssets=vt,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&_(y(e)))},exports.platformFetch=n,exports.platformFileExists=i,exports.platformInstantiateWasm=async function(e,s){return t().instantiateWasm(e,s)},exports.platformReadFile=r,exports.platformReadTextFile=o,exports.pointInOBB=Pn,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=Bt,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerComponent=J,exports.registerComponentAssetFields=function(e,t){ft.set(e,t)},exports.registerComponentEntityFields=function(e,t){mt.set(e,t)},exports.registerDrawCallback=Jt,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(Mt);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=ut,exports.sceneManagerPlugin=Fs,exports.screenToWorld=vn,exports.setEditorMode=function(e){Gr=e},exports.setListViewRenderer=function(e,t){if(!br)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=br.get(e);s?s.renderer=t:br.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})},exports.setLogLevel=function(e){Qr.setMinLevel(e)},exports.setWasmErrorHandler=je,exports.shutdownDrawAPI=Ht,exports.shutdownGLDebugAPI=bs,exports.shutdownGeometryAPI=os,exports.shutdownMaterialAPI=tt,exports.shutdownPostProcessAPI=us,exports.shutdownRendererAPI=_s,exports.syncFillSpriteSize=function(e,t,s,n,r,o){if(!e.has(t,re))return;const i=e.get(t,re);let a,l;switch(s){case Ns.BottomToTop:case Ns.TopToBottom:a=r,l=o*n;break;default:a=r*n,l=o}i.size.x===a&&i.size.y===l||(i.size.x=a,i.size.y=l,e.insert(t,re,i))},exports.textInputPlugin=Jn,exports.textPlugin=mn,exports.transitionTo=async function(e,t,s){const n=e.getResource(As);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=Xn,exports.uiLayoutPlugin=zn,exports.uiMaskPlugin=Cn,exports.uiPlugins=Zr,exports.unregisterComponent=function(e){j().delete(e),q.delete(e)},exports.unregisterDrawCallback=Kt,exports.updateCameraAspectRatio=function(e,t){const s=e.getEntitiesWithComponents([oe]);for(const n of s){const s=e.get(n,oe);s&&(s.aspectRatio=t,e.insert(n,oe,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){Qr.warn(e,t,s)},exports.wrapSceneSystem=Rs,exports.wxFileExists=T,exports.wxFileExistsSync=function(e){const t=b();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=C,exports.wxLoadImage=E,exports.wxLoadImagePixels=async function(e){return C(await E(e))},exports.wxReadFile=P,exports.wxReadTextFile=M,exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{b().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};//# sourceMappingURL=index.wechat.cjs.js.mapdiff --git a/desktop/public/sdk/cjs/index.wechat.js b/desktop/public/sdk/cjs/index.wechat.jsindex cc113d097..b456dbcbb 100644--- a/desktop/public/sdk/cjs/index.wechat.js+++ b/desktop/public/sdk/cjs/index.wechat.js@@ -1,2 +1,2 @@-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function d(e,n){return t().createCanvas(e,n)}function h(){return t().now()}function f(e,t){return new Promise((n,s)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];n({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,n="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(n).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function p(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const n=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(n,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${n}": ${t}`)}}const 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 M(e){return _.has(e.toLowerCase())}function P(){return _}function E(e){return"string"==typeof e&&(!!e.includes("/")&&M(w(e)))}function T(){const e=[];for(const t of g)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function C(){return T().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 I=null;function F(){return I||(I=wx.getFileSystemManager()),I}function k(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 B(e){return new Promise((t,n)=>{F().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(k(e,t.errMsg)))}})})}function W(e,t="utf-8"){return new Promise((n,s)=>{F().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(k(e,t.errMsg)))}})})}function $(e){return new Promise(t=>{F().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function z(e){const t=F();try{return t.accessSync(e),!0}catch{return!1}}function U(e,t){return new Promise((n,s)=>{F().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function D(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 D(e))}let H=!1;const j=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return B(e)}async readTextFile(e){return W(e)}async fileExists(e){return $(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return p(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const n=wx.createCanvas();return n.width=e,n.height=t,n}now(){return Date.now()}bindInputEvents(e,t){const{pixelRatio:n}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX*n,s.clientY*n)}),wx.onTouchMove(t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX*n,s.clientY*n)}),wx.onTouchEnd(t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)})}},X=1920,Y=1080,N=100,V=512,G={x:100,y:100},q="Arial",J=24,K=1.2,Q=.5,Z=1/60,ee={x:0,y:-9.81},te=1/60,ne="default",se={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function re(e){e.Text&&(e.Text._default.fontFamily=se.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=se.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=se.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=se.canvasMatchWidthOrHeight)}const oe=0,ie=4294967295,ae=4294967295,le=0,ce=(e=0,t=0)=>({x:e,y:t}),ue=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),de=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),he=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),fe=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function pe(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(pe);const t={};for(const n in e)t[n]=pe(e[n]);return t}let ge=0;function ye(e,t){const n=++ge;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...pe(t),...e}:pe(t)}}const me=new Map;function _e(){return"undefined"==typeof window?me:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function we(e,t){const n=Ee.get(e)??_e().get(e);if(n)return n;const s=ye(e,t);return _e().set(e,s),Ee.set(e,s),Me(e,t,!1),s}function xe(e){const t=Ee.get(e)??_e().get(e);if(t)return t;const n=ye(e,{});return _e().set(e,n),Ee.set(e,n),Me(e,{},!0),n}function ve(e){return _e().get(e)}function be(){const e=_e();for(const t of e.keys())Ee.delete(t);e.clear()}function Se(e){_e().delete(e),Ee.delete(e)}function Me(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function Pe(e){return!0===e._builtin}const Ee=new Map;function Te(e,t){Ee.set(e,t)}function Ce(e){return Ee.get(e)??ve(e)}function Re(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return Ee.set(e,n),n}const Ae={Perspective:0,Orthographic:1},Ie={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},Fe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},ke=Re("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Be=Re("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),We=Re("Sprite",{texture:ie,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}),$e=Re("Camera",{projectionType:Ae.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Ie.ColorAndDepth}),ze=Re("Canvas",{designResolution:{x:X,y:Y},pixelsPerUnit:100,scaleMode:Fe.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Ue=Re("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),De=Re("Parent",{entity:0}),Le=Re("Children",{entities:[]}),Oe=Re("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:ae,enabled:!0}),He=Re("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),je={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},Xe=we("SceneOwner",{scene:"",persistent:!1});function Ye(e){const t=Ce(e);return t?pe(t._default):null}Te("Name",je);const Ne=Re("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Ve=Re("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ge=Re("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),qe=Re("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Je={Static:0,Kinematic:1,Dynamic:2};let Ke=0;function Qe(e,t){const n=++Ke;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function Ze(e){return{_type:"res",_resource:e}}function et(e){return{_type:"res_mut",_resource:e}}class tt{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 nt{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 tt(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const st=Qe({delta:0,elapsed:0,frameCount:0},"Time");function rt(e){return{_type:"mut",_component:e}}function ot(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function it(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{ot(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class at{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>ot(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 u=null;this.world_.beginIteration();try{for(const d of s){if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(d,t[n])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,n[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=d}yield a}}finally{if(this.world_.endIteration(),null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function lt(){return{_type:"commands"}}class ct{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 ut{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ct(this,null);return this.spawned_.push(e),e}entity(e){return new ct(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 dt;!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"}(dt||(dt={}));let ht=0;function ft(e,t,n){const s=++ht;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function pt(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function gt(e){pt().push({schedule:dt.Update,system:e})}function yt(e){pt().push({schedule:dt.Startup,system:e})}function mt(e,t){pt().push({schedule:e,system:t})}class _t{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 ut&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new at(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new ut(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class wt{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 xt=Qe(new wt,"Input");class vt{constructor(e){this.target_=e??null}build(e){const n=new wt;e.insertResource(xt,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(dt.Last,ft([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const bt=new vt;function St(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=Mt(t[e]),o=Mt(r);"null"!==n&&"undefined"!==n&&(n!==o&&null!=r&&s.push({field:e,expected:n,actual:o,value:r}))}return s}function Mt(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 Et=null;function Tt(e){Et=e}function Ct(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Et&&Et(e,t)}function Rt(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}:Rt(e)}}return t}class At{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,this.nextEntityId_=0}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw Ct(e,"spawn"),e}else e=++this.nextEntityId_;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){Ct(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){Ct(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Ct(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 Ct(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_,s=n[`add${e}`],r=n[`get${e}`],o=n[`has${e}`],i=n[`remove${e}`];if("function"!=typeof s||"function"!=typeof r||"function"!=typeof o||"function"!=typeof i)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:s.bind(n),get:r.bind(n),has:o.bind(n),remove:i.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=St(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,Rt(r))}catch(n){Ct(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 Ct(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 Ct(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){Ct(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=St(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 Ee)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=_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 It=Qe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var Ft;function kt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}!function(e){e[e.Normal=0]="Normal",e[e.Additive=1]="Additive",e[e.Multiply=2]="Multiply",e[e.Screen=3]="Screen",e[e.PremultipliedAlpha=4]="PremultipliedAlpha"}(Ft||(Ft={}));let Bt=null,Wt=null,$t=1;const zt=new Map;function Ut(e){Bt=e,Wt=e.getResourceManager(),Gt()}function Dt(){0!==jt&&Bt&&(Bt._free(jt),jt=0),zt.clear(),$t=1,Ht=!1,Yt.clear(),Nt=null,Wt=null,Bt=null}function Lt(){if(!Wt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Wt}const Ot={createShader:(e,t)=>Lt().createShader(e,t),releaseShader(e){e>0&&Lt().releaseShader(e)},create(e){const t=$t++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Ft.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 zt.set(t,n),t},get:e=>zt.get(e),setUniform(e,t,n){const s=zt.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=zt.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=zt.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=zt.get(e);return t?.blendMode??Ft.Normal},setDepthTest(e,t){const n=zt.get(e);n&&(n.depthTest=t)},getShader(e){const t=zt.get(e);return t?.shader??0},release(e){zt.delete(e)},isValid:e=>zt.has(e),releaseAll(){zt.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??Ft.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=zt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=$t++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return zt.set(n,s),n},toAssetData(e,t){const n=zt.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=zt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ht=!1,jt=0;const Xt=4096,Yt=new Map;let Nt=null;function Vt(e){const t=(0===jt&&Bt&&(jt=Bt._malloc(Xt)),jt);if(0===t||!Bt)return{ptr:0,count:0};let n=0,s=0;const r=Bt.HEAPU8,o=Bt.HEAPU32,i=Bt.HEAPF32;for(const[a,l]of e){if(n+128>Xt)break;let e=Yt.get(a);e||(Nt||(Nt=new TextEncoder),e=Nt.encode(a),Yt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=h[e],n+=4;s++}return{ptr:t,count:s}}function Gt(){if(!Bt||Ht)return;Bt.materialDataProvider=(e,t,n,s,r)=>{const o=zt.get(e);if(!o)return Bt.HEAPU32[t>>2]=0,Bt.HEAPU32[n>>2]=0,Bt.HEAPU32[s>>2]=0,void(Bt.HEAPU32[r>>2]=0);Bt.HEAPU32[t>>2]=o.shader,Bt.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Vt(o.uniforms);Bt.HEAPU32[s>>2]=i,Bt.HEAPU32[r>>2]=a},Ht=!0}const qt={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class Jt{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 Kt{constructor(e,t=""){this.cache_=new Jt,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ot.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ot.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const 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:Ot.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 Qt=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 Zt(e,t){Qt.set(e,t)}function en(e){const t=Qt.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 tn(e){return Qt.get(e)?.fields??[]}function nn(e){return Qt.get(e)?.spine??null}const sn=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function rn(e,t){sn.set(e,t)}function on(e,t){const n=sn.get(e.type);if(!n)return;const s=e.data;for(const e of n){const n=s[e];if("number"==typeof n&&0!==n){const r=t.get(n);s[e]=void 0!==r?r:0}}}function an(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();n.set(s.id,t),e.insert(t,je,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;const t=n.get(s.id);for(const r of s.components)on(r,n),un(e,t,r,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}function ln(e,t){return an(e,t)}async function cn(e,t,n){const s=n?.assetServer,r=n?.assetBaseUrl,o=new Map;s&&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=Qt.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,u=new Map,d=new Map,h=[];for(const e of r)h.push((async()=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)h.push((async()=>{try{const s=await t.loadMaterial(e,n);u.set(e,s.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of i)h.push((async()=>{try{const s=await t.loadBitmapFont(e,n);d.set(e,s)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.set(e,0)}})());for(const e of a)h.push((async()=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)})());await Promise.all(h);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Qt.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":n[e.field]=c.get(t)??0;break;case"material":n[e.field]=u.get(t)??0;break;case"font":n[e.field]=d.get(t)??0}}}}(t,s,r,o);const i=an(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return i}function un(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=Ce(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 dn(e,t){const n=e.getEntitiesWithComponents([$e]);for(const s of n){const n=e.get(s,$e);n&&(n.aspectRatio=t,e.insert(s,$e,n))}}function hn(e,t){const n=e.getEntitiesWithComponents([je]);for(const s of n){const n=e.get(s,je);if(n&&n.value===t)return s}return null}class fn{constructor(e){this.textureCache_=new Jt,this.shaderCache_=new Jt,this.jsonCache_=new Jt,this.textCache_=new Jt,this.binaryCache_=new Jt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Jt,this.prefabCache_=new Jt,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(se.textCanvasSize,se.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Kt(t)}registerEmbeddedAssets(e){for(const[t,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(),Ot.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u="binary"===x(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),r=l.find(e=>e.name===n);if(r){const n=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,r.info.width,r.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=x(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return cn(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 Ot.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 Ot.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 pn=Qe(null,"Assets");class gn{build(e){const t=e.wasmModule;t?e.insertResource(pn,new fn(t)):console.warn("AssetPlugin: No WASM module available")}}const yn=new gn;class mn{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 _n(e,t){const n=e.getResource(pn);n&&n.registerEmbeddedAssets(t)}async function wn(e,t,n){const{entities:s,rootId:r}=await vn(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 cn(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 xn=10;async function vn(e,t,n,s,r,o=0){if(o>xn)throw new Error(`Prefab nesting depth exceeded ${xn}. 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 vn(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),u=s.prefabEntityId===e.rootEntityId,d={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:u?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};bn(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 bn(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 Sn{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 wn(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Mn=Qe(null,"Prefabs");class Pn{constructor(){this.name="PrefabsPlugin",this.dependencies=[pn]}build(e){const t=e.getResource(pn);e.insertResource(Mn,new Sn(e.world,t))}}const En=new Pn;let Tn=null,Cn=0,Rn=0,An=0;const In=new Float32Array(256);function Fn(e){Tn=e,Cn=Tn._malloc(64),Rn=Tn._malloc(64),An=Tn._malloc(1024)}function kn(){Tn&&(Cn&&(Tn._free(Cn),Cn=0),Rn&&(Tn._free(Rn),Rn=0),An&&(Tn._free(An),An=0)),Tn=null}function Bn(){if(!Tn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Tn}const Wn={r:1,g:1,b:1,a:1},$n={begin(e){const t=Bn();try{t.HEAPF32.set(e,Cn/4),t.draw_begin(Cn)}catch(e){Ct(e,"Draw.begin")}},end(){try{Bn().draw_end()}catch(e){Ct(e,"Draw.end")}},line(e,t,n,s=1){try{Bn().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Ct(e,"Draw.line")}},rect(e,t,n,s=!0){try{Bn().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Ct(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{Bn().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Ct(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,r=32){try{Bn().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)}catch(e){Ct(e,"Draw.circle")}},circleOutline(e,t,n,s=1,r=32){try{Bn().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)}catch(e){Ct(e,"Draw.circleOutline")}},texture(e,t,n,s=Wn){try{Bn().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){Ct(e,"Draw.texture")}},textureRotated(e,t,n,s,r=Wn){try{Bn().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)}catch(e){Ct(e,"Draw.textureRotated")}},setLayer(e){Bn().draw_setLayer(e)},setDepth(e){Bn().draw_setDepth(e)},getDrawCallCount:()=>Tn?Tn.draw_getDrawCallCount():0,getPrimitiveCount:()=>Tn?Tn.draw_getPrimitiveCount():0,setBlendMode(e){Bn().draw_setBlendMode(e)},setDepthTest(e){Bn().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=Bn();s.HEAPF32.set(n,Rn/4),s.draw_mesh(e,t,Rn)}catch(n){Ct(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=Bn(),r=Ot.get(t);if(!r)return;if($n.setBlendMode(r.blendMode),$n.setDepthTest(r.depthTest),0===r.uniforms.size)return void $n.drawMesh(e,r.shader,n);let o;if(s.HEAPF32.set(n,Rn/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,n]of r.uniforms){const s=Dn(t);if(!(s<0)){if(kt(n))In[o++]=10,In[o++]=s,In[o++]=n.slot??e++,In[o++]=n.textureId;else if("number"==typeof n)In[o++]=1,In[o++]=s,In[o++]=n;else if(Array.isArray(n)){In[o++]=n.length,In[o++]=s;for(let e=0;e<n.length;e++)In[o++]=n[e]}else"w"in n?(In[o++]=4,In[o++]=s,In[o++]=n.x,In[o++]=n.y,In[o++]=n.z,In[o++]=n.w):"z"in n?(In[o++]=3,In[o++]=s,In[o++]=n.x,In[o++]=n.y,In[o++]=n.z):(In[o++]=2,In[o++]=s,In[o++]=n.x,In[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(In.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void s.draw_mesh(e,r.shader,Rn);s.HEAPF32.set(r.cachedBuffer_.subarray(0,o),An/4),s.draw_meshWithUniforms(e,r.shader,Rn,An,o)}catch(n){Ct(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},zn={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},Un=new Set;function Dn(e){const t=zn[e];return void 0!==t?t:(Un.has(e)||(Un.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(zn).join(", ")}`)),-1)}const Ln=new Map;function On(e,t,n){Ln.set(e,{fn:t,scene:n??""})}function Hn(e){Ln.delete(e)}function jn(){Ln.clear()}var Xn;!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"}(Xn||(Xn={}));let Yn=null,Nn=0,Vn=0,Gn=0;function qn(e){Yn=e,Nn=Yn._malloc(262144),Vn=Yn._malloc(65536),Gn=Yn._malloc(256)}function Jn(){Yn&&(Nn&&Yn._free(Nn),Vn&&Yn._free(Vn),Gn&&Yn._free(Gn),Nn=0,Vn=0,Gn=0),Yn=null}function Kn(){if(!Yn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Yn}const Qn={create(e){const t=Kn(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,Nn/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Gn,r).set(o),t.geometry_init(n,Nn,s,Gn,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,Vn,s).set(e.indices),t.geometry_setIndices16(n,Vn,s)}else{new Uint32Array(t.HEAPU8.buffer,Vn,s).set(e.indices),t.geometry_setIndices32(n,Vn,s)}}return n},updateVertices(e,t,n=0){const s=Kn(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,Nn/4),s.geometry_updateVertices(e,Nn,r,n)},release(e){e>0&&Kn().geometry_release(e)},isValid:e=>!(!Yn||e<=0)&&Yn.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Qn.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:Xn.Float2},{name:"a_texCoord",type:Xn.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 Qn.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Xn.Float2},{name:"a_texCoord",type:Xn.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 Qn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Xn.Float2},{name:"a_texCoord",type:Xn.Float2}],indices:new Uint16Array(i)})}};let Zn=null;function es(e){Zn=e}function ts(){Zn&&ss.isInitialized()&&ss.shutdown(),Zn=null}function ns(){if(!Zn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Zn}const ss={init(e,t){try{return ns().postprocess_init(e,t)}catch(n){return Ct(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{ns().postprocess_shutdown()}catch(e){Ct(e,"PostProcess.shutdown")}},resize(e,t){try{ns().postprocess_resize(e,t)}catch(n){Ct(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return ns().postprocess_addPass(e,t)}catch(t){return Ct(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{ns().postprocess_removePass(e)}catch(t){Ct(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{ns().postprocess_setPassEnabled(e,t)}catch(t){Ct(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return ns().postprocess_isPassEnabled(e)}catch(t){return Ct(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{ns().postprocess_setUniformFloat(e,t,n)}catch(n){Ct(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{ns().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){Ct(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{ns().postprocess_begin()}catch(e){Ct(e,"PostProcess.begin")}},end(){try{ns().postprocess_end()}catch(e){Ct(e,"PostProcess.end")}},getPassCount(){try{return ns().postprocess_getPassCount()}catch(e){return Ct(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Zn)return!1;try{return Zn.postprocess_isInitialized()}catch(e){return Ct(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{ns().postprocess_setBypass(e)}catch(e){Ct(e,"PostProcess.setBypass")}},isBypassed(){if(!Zn)return!0;try{return Zn.postprocess_isBypassed()}catch(e){return Ct(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Ot.createShader(rs,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>Ot.createShader(rs,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Ot.createShader(rs,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Ot.createShader(rs,"#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")},rs="#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 os;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(os||(os={}));let is=null,as=0;function ls(e){is=e,as=is._malloc(64)}function cs(){is&&as&&(is._free(as),as=0),is=null}const us={init(e,t){is?.renderer_init(e,t)},resize(e,t){is?.renderer_resize(e,t)},begin(e,t){if(is&&as)try{is.HEAPF32.set(e,as/4),is.renderer_begin(as,t??0)}catch(e){Ct(e,"Renderer.begin")}},flush(){try{is?.renderer_flush()}catch(e){Ct(e,"Renderer.flush")}},end(){try{is?.renderer_end()}catch(e){Ct(e,"Renderer.end")}},submitSprites(e){if(is)try{is.renderer_submitSprites(e._cpp)}catch(e){Ct(e,"Renderer.submitSprites")}},submitBitmapText(e){if(is)try{is.renderer_submitBitmapText(e._cpp)}catch(e){Ct(e,"Renderer.submitBitmapText")}},submitSpine(e){if(is)try{is.renderer_submitSpine?.(e._cpp)}catch(e){Ct(e,"Renderer.submitSpine")}},setStage(e){is?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>is?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){is?.renderer_releaseTarget(e)},getTargetTexture:e=>is?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>is?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){is?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){is?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){is?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){is?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>is?is.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>is?{drawCalls:is.renderer_getDrawCalls(),triangles:is.renderer_getTriangles(),sprites:is.renderer_getSprites(),text:is.renderer_getText(),spine:is.renderer_getSpine?.()??0,meshes:is.renderer_getMeshes(),culled:is.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let ds=null;function hs(e){ds=e}function fs(){ds=null}const ps={enable(){ds?.gl_enableErrorCheck(!0)},disable(){ds?.gl_enableErrorCheck(!1)},check:e=>ds?.gl_checkErrors(e)??0,diagnose(){ds?.renderer_diagnose()}};class gs{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_||(us.resize(s,r),ss.isInitialized()&&ss.getPassCount()>0&&ss.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),us.setViewport(0,0,s,r),us.clearBuffers(3),us.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),us.submitSprites(t),us.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):us.submitSpine(t),us.flush(),this.executeDrawCallbacks(n,o),us.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;us.setViewport(s.x,s.y,s.w,s.h),us.setScissor(s.x,s.y,s.w,s.h,!0),us.clearBuffers(r),us.setScissor(0,0,0,0,!1),us.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),us.submitSprites(t),us.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):us.submitSpine(t),us.flush(),this.executeDrawCallbacks(n,o),us.end()}executeDrawCallbacks(e,t){const n=Ln;if(n.size>0){$n.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)}$n.end();for(const e of s)Hn(e)}}}const ys="__scene_transition_overlay__";class ms{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class _s{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,Xe,{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),On(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=ss.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){ss.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,Xe)){const n=this.app_.world.get(e,Xe);n.persistent=t,this.app_.world.insert(e,Xe,n)}}}class ws{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??se.sceneTransitionDuration,r=t.color??{...se.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:r,targetScene:e,options:t,resolve:n},On(ys,()=>{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;$n.setLayer(9999),$n.setDepth(9999),$n.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()=>{try{n&&n!==e&&await this.unload(n,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,Hn(ys),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Hn(ys),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 ms(t);this.scenes_.set(e,n);const s=new _s(n,this.app_);this.contexts_.set(e,s);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(pn)?this.app_.getResource(pn):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(pn)&&(t.assetServer=this.app_.getResource(pn));const s=await cn(this.app_.world,r,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,Xe,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=vs(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 ms(t);this.scenes_.set(e,n);const s=new _s(n,this.app_);this.contexts_.set(e,s);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(pn)?this.app_.getResource(pn):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(pn)&&(t.assetServer=this.app_.getResource(pn));const s=await cn(this.app_.world,r,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,Xe,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=vs(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,Xe)){if(this.app_.world.get(e,Xe).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())Hn(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{ss.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)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s={};let r=!1;if(n.has(e,We)){const t=n.get(e,We);s.sprite=t.color.a,t.color={...t.color,a:0},n.insert(e,We,t),r=!0}if(n.has(e,He)){const t=n.get(e,He);s.spine=t.color.a,t.color={...t.color,a:0},n.insert(e,He,t),r=!0}if(n.has(e,Oe)){const t=n.get(e,Oe);s.bitmapText=t.color.a,t.color={...t.color,a:0},n.insert(e,Oe,t),r=!0}r&&t.savedAlphas.set(e,s)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s=t.savedAlphas.get(e);if(s){if(void 0!==s.sprite&&n.has(e,We)){const t=n.get(e,We);t.color={...t.color,a:s.sprite},n.insert(e,We,t)}if(void 0!==s.spine&&n.has(e,He)){const t=n.get(e,He);t.color={...t.color,a:s.spine},n.insert(e,He,t)}if(void 0!==s.bitmapText&&n.has(e,Oe)){const t=n.get(e,Oe);t.color={...t.color,a:s.bitmapText},n.insert(e,Oe,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{ss.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 xs=Qe(null,"SceneManager");function vs(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(xs).getSceneStatus(t)&&n._fn(...s)}}}const bs=ft([et(xs),Ze(st)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Ss={name:"SceneManager",build(e){const t=new ws(e);e.insertResource(xs,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(xs),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(dt.Startup,n),e.addSystemToSchedule(dt.Last,bs)}};class Ms{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=h(),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(dt.Last);else{this.runSchedule(dt.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(dt.FixedPreUpdate),this.runSchedule(dt.FixedUpdate),this.runSchedule(dt.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(dt.PreUpdate),this.runSchedule(dt.Update),this.runSchedule(dt.PostUpdate),this.runSchedule(dt.Last),this.step_pending_&&(this.step_pending_=!1)}requestAnimationFrame(this.mainLoop)},this.world_=new At,this.resources_=new nt;for(const e of Object.values(dt))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Ms}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(dt.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(dt.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 Tt(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 _t(this.world_,this.resources_),this.resources_.insert(st,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(dt.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1,jn();const e=[fs,cs,ts,Jn,Dt,kn];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(st);t.delta=e,t.elapsed+=e,t.frameCount++}}function Ps(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 Es=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ts(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case Fe.FixedWidth:return o;case Fe.FixedHeight:return i;case Fe.Expand:return Math.max(o,i);case Fe.Shrink:return Math.min(o,i);case Fe.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function Cs(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,Xe);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 u,d=0,h=0;if(r.projectionType===Ae.Orthographic){if(h=r.orthoSize,l){h=Ts(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}d=h*a,u=As(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=Fs(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=Bs(o.position.x,o.position.y,o.position.z);c.push({entity:e,viewProjection:new Float32Array($s(u,f)),viewportRect:i,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:o.position.x,cameraY:o.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const Rs=new Float32Array(16);function As(e,t,n,s,r,o){const i=Rs;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 Is=new Float32Array(16);function Fs(e,t,n,s){const r=Is;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 ks=new Float32Array(16);function Bs(e,t,n){const s=ks;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 $s(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}const zs={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function Us(e,t,n,s,r,o,i={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,u=o.left+t.x*a,d=o.bottom+e.y*l,h=o.bottom+t.y*l;let f,p,g,y;e.x===t.x?(f=c+n.x-r.x*i.x,g=f+r.x):(f=c+n.x,g=u+s.x),e.y===t.y?(p=d+n.y-r.y*i.y,y=p+r.y):(p=d+n.y,y=h+s.y);const m=Math.max(0,g-f),_=Math.max(0,y-p);return{originX:f+i.x*m,originY:p+i.y*_,width:m,height:_,rect:{left:f,bottom:p,right:g,top:y}}}const Ds=we("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},_dirty:!0,_computedWidth:void 0,_computedHeight:void 0,_layoutManaged:void 0});function Ls(e,t){e.has(t,We)||e.insert(t,We,{texture:ie,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0})}function Os(e,t){switch(e){case zs.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case zs.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case zs.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function Hs(e,t){switch(e){case zs.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case zs.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case zs.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1-t}};default:return{anchorMin:{x:t,y:0},anchorMax:{x:t,y:1}}}}function js(e,t,n,s){switch(e){case zs.BottomToTop:case zs.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function Xs(e,t,n,s){if(!e.has(t,Ds))return;const r=e.get(t,Ds),o=Os(n,s);r.anchorMin=o.anchorMin,r.anchorMax=o.anchorMax,r.offsetMin=o.offsetMin,r.offsetMax=o.offsetMax,e.insert(t,Ds,r)}function Ys(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Ns(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Vs(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(let o=0;o<t.length;o++){const i=t[o],a=s+i;if(e.measureText(a).width>n&&s){if(Ns(i.charCodeAt(0))&&s.length>0&&Ns(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!Ns(s.charCodeAt(t))){e=t;break}e>=0?(r.push(s.substring(0,e+1)),s=s.substring(e+1)+i):(r.push(s),s=i)}else r.push(s),s=i}else s=a}s&&r.push(s)}return r.length>0?r:[""]}function Gs(e){let t=1;for(;t<e;)t*=2;return t}function qs(e,t){let n=0,s=t;for(;e.has(s,De);){const t=e.get(s,De).entity;if(!e.valid(t))break;n++,s=t}return n}function Js(e){return e._computedWidth??e.size.x}function Ks(e){return e._computedHeight??e.size.y}function Qs(e,t,n,s,r,o){if(!e.has(t,We))return;const i=e.get(t,We);let a,l;switch(n){case zs.BottomToTop:case zs.TopToBottom:a=r,l=o*s;break;default:a=r*s,l=o}i.size.x===a&&i.size.y===l||(i.size.x=a,i.size.y=l,e.insert(t,We,i))}function Zs(e,t,n){let s=t;for(;e.has(s,De);){const t=e.get(s,De).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function er(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function tr(e,t,n,s,r){if(!e.has(t,Ds))return;const o=e.get(t,Ds),i=Us(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,n,o.pivot),a=i.rect.right-i.rect.left,l=i.rect.top-i.rect.bottom;if(o._computedWidth=a,o._computedHeight=l,e.has(t,We)){const n=e.get(t,We);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,We,n))}if(!o._layoutManaged&&e.has(t,ke)){const n=e.get(t,ke);n.position.x=i.originX-s,n.position.y=i.originY-r,e.insert(t,ke,n)}}function nr(e){const t=Object.keys(e),n=t.map(t=>e[t]);return{take(e){const s={};for(let r=0;r<t.length;r++)s[t[r]]=n[r](e);return s},changed(e,s){for(let r=0;r<t.length;r++)if(e[t[r]]!==n[r](s))return!0;return!1},update(e,s){for(let r=0;r<t.length;r++)e[t[r]]=n[r](s)}}}const sr={r:.3,g:.5,b:.8,a:1},rr={Left:0,Center:1,Right:2},or={Top:0,Middle:1,Bottom:2},ir={Visible:0,Clip:1,Ellipsis:2},ar=we("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:rr.Left,verticalAlign:or.Top,wordWrap:!0,overflow:ir.Visible,lineHeight:1.2});class lr{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=d(se.textCanvasSize,se.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,Gs(this.frameMaxW_)),e.height=Math.max(e.height,Gs(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Gs(this.frameMaxW_),e.height=Gs(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const 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=Vs(n,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=r?Math.ceil(o):d+2*u,p=r?Math.ceil(i):h+2*u;if(r&&e.overflow===ir.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)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,Gs(f)),s.height=Math.max(s.height,Gs(p)));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===ir.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 or.Top:x=u;break;case or.Middle:x=u+(p-2*u-w)/2;break;case or.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of l){let s;switch(e.align){case rr.Left:s=u;break;case rr.Center:s=f/2;break;case rr.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=c}r&&e.overflow===ir.Clip&&n.restore();const b=n.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),M=this.module.getResourceManager(),P=this.module._malloc(S.length);this.module.HEAPU8.set(S,P);const E=M.createTexture(f,p,P,S.length,1,!0);return this.module._free(P),{textureHandle:E,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()}measureWidth(e){let t=0;for(const n of e)t=Math.max(t,this.ctx.measureText(n).width);return t}mapAlign(e){switch(e){case rr.Left:return"left";case rr.Center:return"center";case rr.Right:return"right"}}}const cr=nr({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?Js(e.uiRect):0,containerHeight:e=>e.uiRect?Ks(e.uiRect):0});class ur{build(e){Te("Text",ar);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new lr(t),s=e.world,r=new Map;e.addSystemToSchedule(dt.PreUpdate,ft([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,ar));for(const e of r.keys())if(!s.valid(e)||!s.has(e,ar)){if(s.valid(e)&&s.has(e,We)){const t=s.get(e,We);t.texture=ie,s.insert(e,We,t)}r.delete(e)}const e=s.getEntitiesWithComponents([ar]);for(const t of e){const e=s.get(t,ar),o=s.has(t,Ds)?s.get(t,Ds):null,i={text:e,uiRect:o},a=r.get(t);if(a&&!cr.changed(a,i))continue;Ls(s,t);const l=n.renderForEntity(t,e,o),c=s.get(t,We);c.texture=l.textureHandle,c.size.x=l.width,c.size.y=l.height,c.uvOffset.x=0,c.uvOffset.y=0,c.uvScale.x=1,c.uvScale.y=1,s.insert(t,We,c),r.set(t,cr.take(i))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const dr=new ur,hr=we("UIMask",{enabled:!0,mode:"scissor"});function fr(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 pr(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],f=e[10],p=e[11],g=e[12],y=e[13],m=e[14],_=e[15],w=s*l-r*a,x=s*c-o*a,v=s*u-i*a,b=r*c-o*l,S=r*u-i*l,M=o*u-i*c,P=d*y-h*g,E=d*m-f*g,T=d*_-p*g,C=h*m-f*y,R=h*_-p*y,A=f*_-p*m;let I=w*A-x*R+v*C+b*T-S*E+M*P;return 0===I||(I=1/I,n[0]=(l*A-c*R+u*C)*I,n[1]=(o*R-r*A-i*C)*I,n[2]=(y*M-m*S+_*b)*I,n[3]=(f*S-h*M-p*b)*I,n[4]=(c*T-a*A-u*E)*I,n[5]=(s*A-o*T+i*E)*I,n[6]=(m*v-g*M-_*x)*I,n[7]=(d*M-f*v+p*x)*I,n[8]=(a*R-l*T+u*P)*I,n[9]=(r*T-s*R-i*P)*I,n[10]=(g*S-y*v+_*w)*I,n[11]=(h*v-d*S-p*w)*I,n[12]=(l*E-a*C-c*P)*I,n[13]=(s*C-r*E+o*P)*I,n[14]=(y*x-g*b-m*w)*I,n[15]=(d*b-h*x+f*w)*I),n}function gr(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:u/d}}function yr(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 mr(e,t){return 2*Math.atan2(e,t)}function _r(e,t,n,s,r,o,i){const a=n[0]*e+n[4]*t+n[12],l=n[1]*e+n[5]*t+n[13],c=n[3]*e+n[7]*t+n[15];return[s+(.5*(a/c)+.5)*o,r+(.5*(l/c)+.5)*i]}function wr(e,t,n,s,r,o,i,a,l,c){const u=mr(l,c),d=Math.sin(-u),h=Math.cos(-u),f=e-n,p=t-s,g=f*h-p*d+n,y=f*d+p*h+s;return g>=n-r*i&&g<=n+r*(1-i)&&y>=s-o*a&&y<=s+o*(1-a)}function xr(e,t,n,s,r,o,i){if(!e.has(t,Ds)||!e.has(t,Be))return null;const a=e.get(t,Ds),l=e.get(t,Be),c=Js(a)*l.scale.x,u=Ks(a)*l.scale.y,d=l.position.x,h=l.position.y,f=a.pivot.x,p=a.pivot.y,g=-c*f,y=c*(1-f),m=-u*p,_=u*(1-p),w=mr(l.rotation.z,l.rotation.w),x=Math.cos(w),v=Math.sin(w),b=[[d+g*x-m*v,h+g*v+m*x],[d+y*x-m*v,h+y*v+m*x],[d+y*x-_*v,h+y*v+_*x],[d+g*x-_*v,h+g*v+_*x]];let S=1/0,M=1/0,P=-1/0,E=-1/0;for(const[e,t]of b){const[a,l]=_r(e,t,n,s,r,o,i);S=Math.min(S,a),M=Math.min(M,l),P=Math.max(P,a),E=Math.max(E,l)}return{x:Math.round(S),y:Math.round(M),w:Math.round(P-S),h:Math.round(E-M)}}function vr(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([hr]);if(0===l.length)return;const c=[],u=[],d=new Set,h=new Set;for(const e of l){const n=t.get(e,hr);n.enabled&&(d.add(e),"stencil"===n.mode?(u.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,r,o,i,a,l,c){const u=[];for(const e of s){let n=!0;Zs(t,e,e=>{if(r.has(e)){if("scissor"===t.get(e,hr).mode)return n=!1,!0}return!1}),n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(r.has(n)){if("scissor"===t.get(n,hr).mode){const e=xr(t,n,o,i,a,l,c);e&&(s=fr(u,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=xr(t,e,o,i,a,l,c);n&&d(e,n)}}(e,t,n,c,d,s,r,o,i,a),u.length>0&&function(e,t,n,s,r){e.renderer_clearStencil();const o=[];for(const e of s){let n=!0;Zs(t,e,e=>!!r.has(e)&&(n=!1,!0)),n&&o.push(e)}let i=1,a=!1;function l(){return i>255?(a||console.warn("Stencil mask overflow"),a=!0,null):i++}function c(t,s){if(a)return;e.renderer_setEntityStencilMask(t,s);const o=e.getChildEntities(n,t);for(const t of o)if(r.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),u(t,s)}function u(t,s){if(a)return;const o=e.getChildEntities(n,t);for(const t of o)if(r.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),u(t,s)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,n,u,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class br{build(e){if(Te("UIMask",hr),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(vr(e.wasmModule,e.world))}}const Sr=new br,Mr=we("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),Pr=we("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Er={Normal:0,Hovered:1,Pressed:2,Disabled:3},Tr=we("Button",{state:Er.Normal,transition:null});class Cr{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 Rr=Qe(new Cr,"UIEvents"),Ar=xe("ScreenSpace"),Ir=nr({anchorMinX:e=>e.anchorMin.x,anchorMinY:e=>e.anchorMin.y,anchorMaxX:e=>e.anchorMax.x,anchorMaxY:e=>e.anchorMax.y,offsetMinX:e=>e.offsetMin.x,offsetMinY:e=>e.offsetMin.y,offsetMaxX:e=>e.offsetMax.x,offsetMaxY:e=>e.offsetMax.y,sizeX:e=>e.size.x,sizeY:e=>e.size.y});function Fr(e,t,n,s,r,o){if(!e.has(t,Ds))return;const i=e.get(t,Ds),a=Us(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n,i.pivot),l=a.rect.right-a.rect.left,c=a.rect.top-a.rect.bottom;if(i._computedWidth=l,i._computedHeight=c,e.has(t,We)){const n=e.get(t,We);n.size.x===l&&n.size.y===c||(n.size.x=l,n.size.y=c,e.insert(t,We,n))}if(!i._layoutManaged){const n=e.get(t,ke);o?(n.position.x=a.originX,n.position.y=a.originY):(n.position.x=a.originX-s,n.position.y=a.originY-r),e.insert(t,ke,n)}if(!e.has(t,Le))return;const u=e.get(t,Le);if(u&&u.entities)for(const t of u.entities)e.valid(t)&&Fr(e,t,a.rect,a.originX,a.originY,!1)}class kr{build(e){Te("UIRect",Ds);const t=e.world,n=new Map,s=new Map;let r=NaN,o=NaN,i=NaN,a=NaN;function l(e){let n=s.get(e);return void 0!==n||(n=function(e,t){let n=t;for(;;){if(e.has(n,Ar))return n;if(!e.has(n,De))return null;const t=e.get(n,De);if(!e.valid(t.entity))return null;n=t.entity}}(t,e),s.set(e,n)),n}function c(e){if(s.delete(e),!t.has(e,Le))return;const n=t.get(e,Le);if(n&&n.entities)for(const e of n.entities)t.valid(e)&&c(e)}e.addSystemToSchedule(dt.PreUpdate,ft([Ze(It)],e=>{if(!e.valid)return;const u={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},d=.5*(u.left+u.right),h=.5*(u.bottom+u.top),f=r!==e.worldLeft||o!==e.worldBottom||i!==e.worldRight||a!==e.worldTop;r=e.worldLeft,o=e.worldBottom,i=e.worldRight,a=e.worldTop;const p=new Set;if(f){s.clear();const e=t.getEntitiesWithComponents([Ar,Ds,ke]);for(const t of e)p.add(t)}for(const e of n.keys())t.valid(e)&&t.has(e,Ds)||(n.delete(e),s.delete(e));const g=t.getEntitiesWithComponents([Ds]);for(const e of g){const s=t.get(e,Ds),r=n.get(e);if(s._dirty||!r||Ir.changed(r,s)){s._dirty=!1,c(e);const t=l(e);null!==t&&p.add(t)}}for(const e of p)Fr(t,e,u,d,h,!0);for(const e of g){const s=t.get(e,Ds),r=n.get(e);r?Ir.update(r,s):n.set(e,Ir.take(s))}},{name:"UILayoutSystem"}))}}const Br=new kr,Wr=function(){const e=new Float32Array(16),t=new Float32Array(16);let n=!0;return{update(e){for(let s=0;s<16;s++)if(t[s]!==e[s]){t.set(e),n=!0;break}},getInverse:t=>(n&&(pr(t,e),n=!1),e)}}();function $r(e,t,n,s){let r=!1;return Zs(e,t,t=>{if(!e.has(t,hr))return!1;if(!e.get(t,hr).enabled||!e.has(t,Ds)||!e.has(t,Be))return!1;const o=e.get(t,Be),i=e.get(t,Ds),a=Js(i)*o.scale.x,l=Ks(i)*o.scale.y;return!wr(n,s,o.position.x,o.position.y,a,l,i.pivot.x,i.pivot.y,o.rotation.z,o.rotation.w)&&(r=!0,!0)}),r}function zr(e,t,n,s){t.emit(n,s,n),Zs(e,n,r=>{if(!e.has(r,Mr))return!1;const o=e.get(r,Mr);return o.enabled&&t.emit(r,s,n),o.blockRaycast})}class Ur{build(e){Te("Interactable",Mr),Te("Button",Tr);const t=e.world,n=new Cr;e.insertResource(Rr,n);let s=null,r=null;e.addSystemToSchedule(dt.PreUpdate,ft([Ze(xt),Ze(It)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([Pr]);for(const e of i){const n=t.get(e,Pr);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a="undefined"!=typeof window&&window.devicePixelRatio||1,l=e.mouseX*a,c=o.screenH-e.mouseY*a;Wr.update(o.viewProjection);const u=gr(l,c,Wr.getInverse(o.viewProjection),o.vpX,o.vpY,o.vpW,o.vpH);o.worldMouseX=u.x,o.worldMouseY=u.y;const d=t.getEntitiesWithComponents([Mr,Ds,Be]);let h=null,f=-1/0;for(const e of d){er(t,e,Pr);const n=t.get(e,Mr);if(!n.enabled)continue;if(!n.raycastTarget)continue;const s=t.get(e,Be),r=t.get(e,Ds),o=Js(r)*s.scale.x,i=Ks(r)*s.scale.y;if(wr(u.x,u.y,s.position.x,s.position.y,o,i,r.pivot.x,r.pivot.y,s.rotation.z,s.rotation.w)){if($r(t,e,u.x,u.y))continue;let n=0;t.has(e,We)&&(n=t.get(e,We).layer),n>f&&(f=n,h=e)}}if(null===s||t.valid(s)||(s=null),s!==h){if(null!==s&&t.valid(s)&&t.has(s,Pr)){t.get(s,Pr).hovered=!1,n.emit(s,"hover_exit")}if(null!==h){t.get(h,Pr).hovered=!0,n.emit(h,"hover_enter")}s=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,Pr);e.pressed=!0,e.justPressed=!0,r=h,zr(t,n,h,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Pr)){const e=t.get(r,Pr);e.pressed=!1,e.justReleased=!0,zr(t,n,r,"release"),r===s&&zr(t,n,r,"click")}r=null}},{name:"UIInteractionSystem"}));const o=new Set;e.addSystemToSchedule(dt.Update,ft([],()=>{const e=t.getEntitiesWithComponents([Tr]);for(const n of e){if(er(t,n,Mr,{enabled:!0}),!t.has(n,Pr))continue;const e=t.get(n,Pr),s=t.get(n,Tr),r=t.get(n,Mr),i=!o.has(n),a=s.state;if(r.enabled?e.pressed?s.state=Er.Pressed:e.hovered?s.state=Er.Hovered:s.state=Er.Normal:s.state=Er.Disabled,i&&o.add(n),(i||a!==s.state)&&s.transition&&t.has(n,We)){const o=t.get(n,We);o.color=Ys(s.transition,r.enabled,e.pressed,e.hovered),t.insert(n,We,o)}}},{name:"ButtonSystem"}))}}const Dr=new Ur,Lr=we("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}),Or=we("Focusable",{tabIndex:0,isFocused:!1});class Hr{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 jr=Qe(new Hr,"FocusManager");class Xr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){Te("TextInput",Lr);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=d(se.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let i=!1,a=!0,l=0,c=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 h=u;function f(){const t=e.getResource(jr);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,Lr)?s:null}const p=()=>{i||null===f()||w()},g=()=>{i=!0},y=()=>{i=!1,w()},m=t=>{const s=f();if(null===s)return;if("Escape"===t.key)return void x();const r=n.get(s,Lr);if("Enter"===t.key&&!r.multiline){t.preventDefault();return e.getResource(Rr).emit(s,"submit"),void x()}let o=r.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,r.cursorPos-1):"ArrowRight"===t.key?o=Math.min(r.value.length,r.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=r.value.length),o!==r.cursorPos&&(r.cursorPos=o,h.selectionStart=o,h.selectionEnd=o,r.dirty=!0,v())},_=()=>{const t=f();if(null!==t){const s=n.get(t,Lr);s.focused=!1,s.dirty=!0;e.getResource(jr).blur()}};function w(){const t=f();if(null===t)return;const s=n.get(t,Lr);if(s.readOnly)return;let r=h.value;if(s.maxLength>0&&r.length>s.maxLength&&(r=r.substring(0,s.maxLength),h.value=r),r!==s.value){s.value=r;e.getResource(Rr).emit(t,"change")}s.cursorPos=h.selectionStart??r.length,s.dirty=!0,v()}function x(){const t=f();if(null!==t){const e=n.get(t,Lr);e.focused=!1,e.dirty=!0}e.getResource(jr).blur(),h.blur()}function v(){a=!0,l=0}h.addEventListener("input",p),h.addEventListener("compositionstart",g),h.addEventListener("compositionend",y),h.addEventListener("keydown",m),h.addEventListener("blur",_),this.cleanupListeners_=()=>{h.removeEventListener("input",p),h.removeEventListener("compositionstart",g),h.removeEventListener("compositionend",y),h.removeEventListener("keydown",m),h.removeEventListener("blur",_),h.remove();const e=t.getResourceManager();for(const t of s.values())e.releaseTexture(t);s.clear()};let b=null;function S(e,i,l,c){(r.width<l||r.height<c)&&(r.width=Gs(Math.max(r.width,l)),r.height=Gs(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,l,c),o.save(),o.beginPath(),o.rect(i.padding,0,l-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),g=i.padding;if(i.multiline){const e=Vs(o,h,l-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(h,g,e)}if(i.focused&&a){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=Vs(o,i.value,l-2*g);let r=0,a=0,c=0;for(let t=0;t<e.length;t++){const n=e[t].length;if(r+n>=i.cursorPos){a=t,c=i.cursorPos-r;break}r+=n,t<e.length-1&&r<i.value.length&&"\n"===i.value[r]&&r++,a=t+1,c=0}const u=a<e.length?e[a].substring(0,c):"";t=g+o.measureText(u).width,n=g+a*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,l,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(l,c,w,m.length,1,!0);s.set(e,v),t._free(w);const b=n.get(e,We);b.texture=v,b.size.x=l,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,We,b)}e.addSystemToSchedule(dt.Update,ft([Ze(jr)],e=>{const t=n.getEntitiesWithComponents([Lr]);for(const e of t)er(n,e,Or,{tabIndex:0,isFocused:!1}),er(n,e,Mr,{enabled:!0,blockRaycast:!0});const s=f();if(s!==b){if(null!==b&&n.valid(b)&&n.has(b,Lr)){const e=n.get(b,Lr);e.focused=!1,e.dirty=!0,h.blur()}null!==s&&function(e){const t=n.get(e,Lr);t.readOnly||(t.focused=!0,t.dirty=!0,h.value=t.value,h.selectionStart=t.cursorPos,h.selectionEnd=t.cursorPos,h.focus(),v())}(s),b=s}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(dt.PreUpdate,ft([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let r=0===c?0:(e-c)/1e3;c=e,r=Math.min(r,.1);const o=f();if(null!==o&&(l+=r,l>=.5)){l-=.5,a=!a;n.get(o,Lr).dirty=!0}const i=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Lr)||(i.releaseTexture(t),s.delete(e));const u=n.getEntitiesWithComponents([Lr,Ds]);for(const e of u){const t=n.get(e,Lr);if(!t.dirty)continue;const s=n.get(e,Ds),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(Ls(n,e),S(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Yr=new Xr,Nr={Simple:0,Sliced:1,Tiled:2,Filled:3},Vr={Horizontal:0,Vertical:1},Gr={Left:0,Right:1,Bottom:2,Top:3},qr=we("Image",{texture:ie,color:{r:1,g:1,b:1,a:1},imageType:Nr.Simple,fillMethod:Vr.Horizontal,fillOrigin:Gr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Jr=nr({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,layer:e=>e.image.layer,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?Js(e.uiRect):0,rectHeight:e=>e.uiRect?Ks(e.uiRect):0,enabled:e=>e.image.enabled});const Kr=new class{build(e){Te("Image",qr);const t=e.world,n=new Map;e.addSystemToSchedule(dt.PreUpdate,ft([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,qr)||n.delete(e);const e=t.getEntitiesWithComponents([qr]);for(const s of e){const e=t.get(s,qr),r=t.has(s,Ds)?t.get(s,Ds):null,o={image:e,uiRect:r},i=n.get(s);if(i&&!Jr.changed(i,o))continue;Ls(t,s);const a=t.get(s,We);if(e.enabled){if(a.texture=e.texture,a.color.r=e.color.r,a.color.g=e.color.g,a.color.b=e.color.b,a.color.a=e.color.a,a.layer=e.layer,a.material=e.material,r&&(a.size.x=Js(r),a.size.y=Ks(r)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Nr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===Vr.Horizontal?e.fillOrigin===Gr.Left?(a.uvScale.x=t,a.size.x=n*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=n*t):e.fillOrigin===Gr.Bottom?(a.uvScale.y=t,a.size.y=s*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=s*t)}else e.imageType===Nr.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale.x=a.size.x/e.tileSize.x,a.uvScale.y=a.size.y/e.tileSize.y);t.insert(s,We,a),n.set(s,Jr.take(o))}else a.color.a=0,t.insert(s,We,a),n.set(s,Jr.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},Qr=we("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Zr=we("ToggleGroup",{allowSwitchOff:!1});const eo=new class{build(e){Te("Toggle",Qr),Te("ToggleGroup",Zr);const t=e.world,n=new Set;e.addSystemToSchedule(dt.Update,ft([Ze(Rr)],e=>{const s=t.getEntitiesWithComponents([Qr]),r=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,Qr);s.isOn&&0!==s.group&&t.valid(s.group)&&(r.has(s.group)?s.isOn=!1:r.set(s.group,e))}const o=new Map;for(const e of s){const n=t.get(e,Qr);if(0!==n.group&&t.valid(n.group)){let t=o.get(n.group);t||(t=[],o.set(n.group,t)),t.push(e)}}for(const n of s){if(er(t,n,Mr,{enabled:!0}),!t.has(n,Pr))continue;const s=t.get(n,Pr),r=t.get(n,Qr),i=t.get(n,Mr);if(s.justPressed&&i.enabled){const s=r.group,i=0!==s&&t.valid(s)&&t.has(s,Zr);if(r.isOn&&i){if(!t.get(s,Zr).allowSwitchOff)continue}if(r.isOn=!r.isOn,r.isOn&&i){const r=o.get(s);if(r)for(const s of r){if(s===n)continue;const r=t.get(s,Qr);r.isOn&&(r.isOn=!1,e.emit(s,"change"))}}e.emit(n,"change")}if(r.graphicEntity&&t.valid(r.graphicEntity)&&t.has(r.graphicEntity,We)){const e=t.get(r.graphicEntity,We);e.enabled=r.isOn,t.insert(r.graphicEntity,We,e)}if(r.transition&&t.has(n,We)){const e=t.get(n,We);e.color=Ys(r.transition,i.enabled,s.pressed,s.hovered),t.insert(n,We,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},to=zs,no=we("ProgressBar",{value:0,fillEntity:0,direction:zs.LeftToRight});const so=new class{build(e){Te("ProgressBar",no);const t=e.world;e.addSystemToSchedule(dt.PreUpdate,ft([],()=>{const e=t.getEntitiesWithComponents([no,Ds]);for(const n of e){const e=t.get(n,no);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=Math.max(0,Math.min(1,e.value));Xs(t,e.fillEntity,e.direction,s)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}},ro=we("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),oo=we("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}});const io=new class{build(e){Te("Draggable",ro),Te("DragState",oo);const t=e.world,n=e.getResource(Rr);let s=null,r={x:0,y:0},o=null;e.addSystemToSchedule(dt.PreUpdate,ft([Ze(xt),Ze(It)],(e,i)=>{if(!i.valid)return;const a={x:i.worldMouseX,y:i.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([ro,Pr]);let n=null,o=-1/0,i=-1;for(const s of e){if(!t.get(s,ro).enabled)continue;if(t.get(s,Pr).hovered){let e=0;t.has(s,We)&&(e=t.get(s,We).layer);const r=qs(t,s);(e>o||e===o&&r>=i)&&(o=e,i=r,n=s)}}if(null!==n){s=n,r={x:a.x,y:a.y},t.has(n,oo)||t.insert(n,oo);const e=t.get(n,oo),o=t.get(n,Be);e.startWorldPos={x:o.position.x,y:o.position.y},e.currentWorldPos={x:o.position.x,y:o.position.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,oo)){t.get(s,oo).isDragging=!1}s=null}if(null!==s&&null===o){if(!t.valid(s))return void(s=null);const e=a.x-r.x,l=a.y-r.y,c=Math.sqrt(e*e+l*l),u=t.get(s,ro);if(c*(i.vpW/(i.worldRight-i.worldLeft))>=u.dragThreshold){o=s,s=null;t.get(o,oo).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,oo))return void(o=null);const s=t.get(o,oo),r=t.get(o,ro),i=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+i,u=s.startWorldPos.y+l;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,u);c=d.x,u=d.y;const h=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-h,y:u-f},s.currentWorldPos={x:c,y:u},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:u-s.startWorldPos.y},t.has(o,ke)){const e=function(e,t,n,s){if(!e.has(t,De))return{x:n,y:s};const r=e.get(t,De).entity;if(!e.valid(r)||!e.has(r,Be))return{x:n,y:s};const o=e.get(r,Be),i=0!==o.scale.x?o.scale.x:1,a=0!==o.scale.y?o.scale.y:1,l=mr(o.rotation.z,o.rotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(n*u-s*c)/i,y:(n*c+s*u)/a}}(t,o,s.deltaWorld.x,s.deltaWorld.y),n=t.get(o,ke);n.position.x+=e.x,n.position.y+=e.y,t.insert(o,ke,n)}n.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},ao=we("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135});const lo=new class{build(e){Te("ScrollView",ao);const t=e.world,n=new Map;let s=0;e.addSystemToSchedule(dt.PreUpdate,ft([Ze(xt),Ze(It)],(e,r)=>{const o=performance.now()/1e3,i=s>0?Math.min(o-s,.05):0;if(s=o,!r.valid)return;for(const[e]of n)t.valid(e)||n.delete(e);const a={x:r.worldMouseX,y:r.worldMouseY},l=t.getEntitiesWithComponents([ao,Ds]);for(const s of l){er(t,s,Mr,{enabled:!0,blockRaycast:!0}),er(t,s,hr,{enabled:!0,mode:"scissor"});const r=t.get(s,ao),o=t.get(s,Ds);let l=n.get(s);l||(l={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0},n.set(s,l));const c=t.has(s,Pr)?t.get(s,Pr):null;if(c?.justPressed&&(l.isDragging=!0,l.lastWorldX=a.x,l.lastWorldY=a.y,l.velocityX=0,l.velocityY=0),l.isDragging&&e.isMouseButtonDown(0)){const e=a.x-l.lastWorldX,t=a.y-l.lastWorldY;if(r.horizontalEnabled){r.scrollX-=e;const t=i>0?-e/i:0;l.velocityX=.8*l.velocityX+.2*t}if(r.verticalEnabled){r.scrollY-=t;const e=i>0?-t/i:0;l.velocityY=.8*l.velocityY+.2*e}l.lastWorldX=a.x,l.lastWorldY=a.y}if(l.isDragging&&e.isMouseButtonReleased(0)&&(l.isDragging=!1),c?.hovered){const t=e.getScrollDelta();r.verticalEnabled&&0!==t.y&&(r.scrollY+=.1*t.y,l.velocityY=0),r.horizontalEnabled&&0!==t.x&&(r.scrollX+=.1*t.x,l.velocityX=0)}if(!l.isDragging&&r.inertia&&i>0){const e=Math.pow(r.decelerationRate,60*i);r.horizontalEnabled&&Math.abs(l.velocityX)>.1?(r.scrollX+=l.velocityX*i,l.velocityX*=e):l.velocityX=0,r.verticalEnabled&&Math.abs(l.velocityY)>.1?(r.scrollY+=l.velocityY*i,l.velocityY*=e):l.velocityY=0}const u=Js(o),d=Ks(o),h=Math.max(0,r.contentWidth-u),f=Math.max(0,r.contentHeight-d),p=r.scrollX,g=r.scrollY;if(r.scrollX=Math.max(0,Math.min(r.scrollX,h)),r.scrollY=Math.max(0,Math.min(r.scrollY,f)),r.scrollX!==p&&(l.velocityX=0),r.scrollY!==g&&(l.velocityY=0),0!==r.contentEntity&&t.valid(r.contentEntity)&&t.has(r.contentEntity,ke)){const e=t.get(r.contentEntity,ke);e.position.x=-r.scrollX,e.position.y=r.scrollY,t.insert(r.contentEntity,ke,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UIInteractionSystem"]})}},co=zs,uo=we("Slider",{value:0,minValue:0,maxValue:1,direction:zs.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});const ho=new class{build(e){Te("Slider",uo);const t=e.world;let n=null;e.addSystemToSchedule(dt.PreUpdate,ft([Ze(xt),Ze(It),Ze(Rr)],(e,s,r)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const o=s.worldMouseX,i=s.worldMouseY,a=t.getEntitiesWithComponents([uo,Ds,Be]);for(const s of a){er(t,s,Mr,{enabled:!0,blockRaycast:!0});const a=t.get(s,uo),l=t.get(s,Ds),c=t.get(s,Be),u=t.has(s,Pr)?t.get(s,Pr):null,d=a.handleEntity;if(0!==d&&t.valid(d)&&(er(t,d,Mr,{enabled:!0,blockRaycast:!1}),t.has(d,Mr))){const e=t.get(d,Mr);e.blockRaycast&&(e.blockRaycast=!1,t.insert(d,Mr,e))}let h=u?.justPressed??!1;if(!h&&0!==d&&t.valid(d)&&t.has(d,Pr)){h=t.get(d,Pr).justPressed}if(h&&(n=s),n===s&&e.isMouseButtonDown(0)){const e=Js(l),n=Ks(l),u=e*c.scale.x,d=n*c.scale.y,h=mr(c.rotation.z,c.rotation.w),f=Math.sin(-h),p=Math.cos(-h),g=o-c.position.x,y=i-c.position.y,m=g*p-y*f,_=g*f+y*p,w=-l.pivot.x*u,x=-l.pivot.y*d;let v;switch(a.direction){case zs.LeftToRight:v=u>0?(m-w)/u:0;break;case zs.RightToLeft:v=u>0?1-(m-w)/u:0;break;case zs.BottomToTop:v=d>0?(_-x)/d:0;break;case zs.TopToBottom:v=d>0?1-(_-x)/d:0}v=Math.max(0,Math.min(1,v));let b=a.minValue+v*(a.maxValue-a.minValue);a.wholeNumbers&&(b=Math.round(b));const S=a.value;a.value=Math.max(a.minValue,Math.min(a.maxValue,b)),t.insert(s,uo,a),a.value!==S&&r.emit(s,"change")}n===s&&e.isMouseButtonReleased(0)&&(n=null);const f=a.maxValue-a.minValue,p=f>0?(a.value-a.minValue)/f:0,g=Js(l),y=Ks(l),m=l.pivot,_={left:-m.x*g,bottom:-m.y*y,right:(1-m.x)*g,top:(1-m.y)*y};if(0!==a.fillEntity&&t.valid(a.fillEntity)&&(Xs(t,a.fillEntity,a.direction,p),tr(t,a.fillEntity,_,0,0)),0!==a.handleEntity&&t.valid(a.handleEntity)){if(t.has(a.handleEntity,Ds)){const e=t.get(a.handleEntity,Ds);switch(e.offsetMin={x:0,y:0},e.offsetMax={x:0,y:0},a.direction){case zs.LeftToRight:e.anchorMin={x:p,y:0},e.anchorMax={x:p,y:1};break;case zs.RightToLeft:e.anchorMin={x:1-p,y:0},e.anchorMax={x:1-p,y:1};break;case zs.BottomToTop:e.anchorMin={x:0,y:p},e.anchorMax={x:1,y:p};break;case zs.TopToBottom:e.anchorMin={x:0,y:1-p},e.anchorMax={x:1,y:1-p}}t.insert(a.handleEntity,Ds,e)}tr(t,a.handleEntity,_,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}};const fo=new class{build(e){Te("Focusable",Or);const t=e.world,n=new Hr;e.insertResource(jr,n),e.addSystemToSchedule(dt.Update,ft([Ze(xt),Ze(Rr)],(e,s)=>{null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const r=t.getEntitiesWithComponents([Or]);for(const e of r){if(!t.has(e,Pr))continue;t.get(e,Pr).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of r){if(!t.valid(n))continue;if(t.has(n,Mr)){if(!t.get(n,Mr).enabled)continue}const s=t.get(n,Or);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,Or)){t.get(r,Or).isFocused=!1,s.emit(r,"blur",r)}n.focus(e);t.get(e,Or).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},po=we("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function go(){return r()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:n,screenWidth:s,screenHeight:r}=t;return{top:n.top,bottom:r-n.bottom,left:n.left,right:s-n.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}const yo=new class{build(e){Te("SafeArea",po);const t=e.world;let n=go(),s=!0,o=0,i=0;if(r()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=go(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=go(),s=!0});e.addSystemToSchedule(dt.PreUpdate,ft([Ze(It)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===i||(o=e.screenH,i=a,s=!0),!s)return;s=!1;const l="undefined"!=typeof window&&window.devicePixelRatio||1,c=r()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([po,Ds]);for(const e of u){const s=t.get(e,po),r=t.get(e,Ds),o=s.applyTop?n.top*c:0,i=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let u=!1;r.offsetMin.x===a&&r.offsetMin.y===i||(r.offsetMin={x:a,y:i},u=!0),r.offsetMax.x===-l&&r.offsetMax.y===-o||(r.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,Ds,r)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},mo=we("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let _o=null;function wo(e,t){if(!_o)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=_o.get(e);n?n.renderer=t:_o.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const xo=new class{build(e){Te("ListView",mo);const t=e.world,n=new Map;_o=n,e.addSystemToSchedule(dt.PreUpdate,ft([Ze(xt)],e=>{for(const[e,s]of n)if(!t.valid(e)){for(const e of s.itemEntities.values())t.valid(e)&&t.despawn(e);n.delete(e)}const s=t.getEntitiesWithComponents([mo,Ds]);for(const r of s){er(t,r,Mr,{enabled:!0,blockRaycast:!0}),er(t,r,hr,{enabled:!0,mode:"scissor"});let s=n.get(r);s||(s={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(r,s));const o=t.get(r,mo),i=t.get(r,Ds),a=i._computedHeight??i.size.y,l=i._computedWidth??i.size.x,c=t.has(r,Pr)?t.get(r,Pr):null;if(c?.hovered){const t=e.getScrollDelta();0!==t.y&&(o.scrollY+=.1*t.y)}const u=Math.max(0,o.itemCount*o.itemHeight-a);o.scrollY=Math.max(0,Math.min(o.scrollY,u));const d=Math.max(0,Math.floor(o.scrollY/o.itemHeight)-o.overscan),h=Math.min(o.itemCount,Math.ceil((o.scrollY+a)/o.itemHeight)+o.overscan);for(const[e,n]of s.itemEntities)(e<d||e>=h)&&(t.valid(n)&&t.despawn(n),s.itemEntities.delete(e));for(let e=d;e<h;e++){let n=s.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,je,{value:`ListItem_${e}`}),t.insert(n,Ds,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:l,y:o.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,r),s.itemEntities.set(e,n),s.renderer&&s.renderer(e,n)),t.has(n,ke)){const s=t.get(n,ke);s.position.y=-(e*o.itemHeight-o.scrollY),t.insert(n,ke,s)}}s.visibleStart=d,s.visibleEnd=h}},{name:"ListViewSystem"}))}},vo=we("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const bo=new class{build(e){Te("Dropdown",vo);const t=e.world,n=new Map;function s(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const r=n.listEntity;if(0===r||!t.valid(r))return;l(r,!0),t.has(r,hr)||t.insert(r,hr,{enabled:!0,mode:"scissor"}),a(s);const o=t.has(r,Ds)?t.get(r,Ds):null,i=o?o.size.x:160;for(let e=0;e<n.options.length;e++){const o=t.spawn();t.insert(o,je,{value:`Option_${e}`}),t.insert(o,Ds,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:i,y:30},pivot:{x:.5,y:1}}),t.insert(o,ke,{position:{x:0,y:-30*e,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(o,ar,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:1,g:1,b:1,a:1},align:rr.Left,verticalAlign:or.Middle,wordWrap:!1,overflow:ir.Clip,lineHeight:1.2}),t.insert(o,We,{texture:0,color:{r:1,g:1,b:1,a:0},size:{x:i,y:30},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,Mr,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,r),s.optionEntities.push(o)}o&&(o.size.y=30*n.options.length,t.insert(r,Ds,o)),c(s)}function r(e,t,n){t.isOpen=!1,a(n),l(t.listEntity,!1)}function o(e,t,n,s,o){t.selectedIndex=s,r(0,t,n),o.emit(e,"change")}function i(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,ar))return;const s=t.get(n,ar),r=e.selectedIndex>=0&&e.selectedIndex<e.options.length?e.options[e.selectedIndex]:"";s.content!==r&&(s.content=r,t.insert(n,ar,s))}function a(e){for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[]}function l(e,n){if(0!==e&&t.valid(e)){if(t.has(e,Mr)){const s=t.get(e,Mr);s.enabled=n,t.insert(e,Mr,s)}if(t.has(e,We)){const s=t.get(e,We);s.enabled=n,t.insert(e,We,s)}}}function c(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s)||!t.has(s,We))continue;const r=t.get(s,We);n===e.highlightIndex?r.color={...sr}:r.color={r:1,g:1,b:1,a:0},t.insert(s,We,r)}}function u(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,Pr))continue;if(t.get(n,Pr).hovered)return!0}return!1}e.addSystemToSchedule(dt.Update,ft([Ze(xt),Ze(Rr)],(e,a)=>{for(const[e]of n)t.valid(e)||n.delete(e);const l=t.getEntitiesWithComponents([vo]);for(const d of l){er(t,d,Mr,{enabled:!0,blockRaycast:!0});const l=t.get(d,vo),h=t.has(d,Pr)?t.get(d,Pr):null;let f=n.get(d);if(f||(f={optionEntities:[],highlightIndex:-1},n.set(d,f)),h?.justPressed&&(l.isOpen?r(d,l,f):s(d,l,f)),l.isOpen){for(let e=0;e<f.optionEntities.length;e++){const n=f.optionEntities[e];if(!t.valid(n)||!t.has(n,Pr))continue;if(t.get(n,Pr).justPressed){o(d,l,f,e,a);break}}e.isKeyPressed("ArrowDown")?(f.highlightIndex>=l.options.length-1?f.highlightIndex=0:f.highlightIndex++,c(f)):e.isKeyPressed("ArrowUp")?(f.highlightIndex<=0?f.highlightIndex=l.options.length-1:f.highlightIndex--,c(f)):e.isKeyPressed("Enter")&&f.highlightIndex>=0?o(d,l,f,f.highlightIndex,a):e.isKeyPressed("Escape")&&r(d,l,f),e.isMouseButtonPressed(0)&&(h?.hovered||u(f)||r(d,l,f))}i(l)}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},So=0,Mo=0,Po=2,Eo=we("LayoutGroup",{direction:So,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Mo,reverseOrder:!1});const To=new class{build(e){Te("LayoutGroup",Eo);const t=e.world;e.addSystemToSchedule(dt.PreUpdate,ft([],()=>{const e=t.getEntitiesWithComponents([Eo,Ds,Le]);for(const n of e){const e=t.get(n,Eo),s=t.get(n,Ds),r=t.get(n,Le);if(!r.entities||0===r.entities.length)continue;const o=[];for(const e of r.entities)t.valid(e)&&t.has(e,Ds)&&t.has(e,ke)&&o.push({entity:e,rect:t.get(e,Ds)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const i=s._computedWidth??s.size.x,a=s._computedHeight??s.size.y,l=s.pivot.x,c=s.pivot.y,u=e.padding,d=e.direction===So;let h=0;for(let n=0;n<o.length;n++){const s=o[n],r=s.rect._computedWidth??s.rect.size.x,f=s.rect._computedHeight??s.rect.size.y,p=s.rect.pivot.x,g=s.rect.pivot.y;let y,m;d?(y=-l*i+u.left+h+p*r,m=e.childAlignment===Mo?(1-c)*a-u.top-(1-g)*f:e.childAlignment===Po?-c*a+u.bottom+g*f:(.5-c)*a+.5*(u.bottom-u.top)+(g-.5)*f,h+=r,n<o.length-1&&(h+=e.spacing)):(y=e.childAlignment===Mo?-l*i+u.left+p*r:e.childAlignment===Po?(1-l)*i-u.right-(1-p)*r:(.5-l)*i+.5*(u.left-u.right)+(p-.5)*r,m=(1-c)*a-u.top-h-(1-g)*f,h+=f,n<o.length-1&&(h+=e.spacing)),s.rect._layoutManaged=!0;const _=t.get(s.entity,ke);_.position.x=y,_.position.y=m,t.insert(s.entity,ke,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};function Co(e,t,n){if(e.has(t,We)&&e.has(t,Ds)){const s=e.get(t,We);s.layer!==n&&(s.layer=n,e.insert(t,We,s)),n++}if(!e.has(t,Le))return n;const s=e.get(t,Le);if(!s||!s.entities)return n;for(const t of s.entities)e.valid(t)&&(n=Co(e,t,n));return n}const Ro=new class{build(e){const t=e.world;e.addSystemToSchedule(dt.PostUpdate,ft([],()=>{let e=0;const n=t.getEntitiesWithComponents([Ar,Ds]);for(const s of n)e=Co(t,s,e)},{name:"UIRenderOrderSystem"}))}};async function Ao(e,t,n){const s=e.getResource(xs);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function Io(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 Fo=Qe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),ko=Qe(null,"PhysicsAPI");function Bo(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Wo(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class $o{constructor(e,t={},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(Fo,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Io(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([ze]);for(const n of t){const t=e.world.get(n,ze);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(dt.PostUpdate,ft([Ze(st)],a=>{const l=i.getEntitiesWithComponents([Ne,ke,Be]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,Ne),l=i.get(r,Be);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=Bo(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),zo(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===Je.Kinematic){const e=Bo(l.rotation);s._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,ke);if(!u)continue;let d=a,h=l,f=c;if(e.world.has(i,De)){const t=e.world.get(i,De);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,Be)){const n=e.world.get(t.entity,Be),s=Bo(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),u=Math.sin(-s);d=(r*i-o*u)/(0!==n.scale.x?n.scale.x:1),h=(r*u+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}u.position.x=d,u.position.y=h;const p=Wo(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(i,ke,u)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Fo,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(ko,Uo._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function zo(e,t,n){const s=e.world;if(s.has(n,Ve)){const e=s.get(n,Ve);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,Ge)){const e=s.get(n,Ge);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,qe)){const e=s.get(n,qe);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 Uo{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(Uo.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 Do(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 Lo(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,u=e.rotation.w,d=a+a,h=l+l,f=c+c,p=a*d,g=a*h,y=a*f,m=l*h,_=l*f,w=c*f,x=u*d,v=u*h,b=u*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 Ho(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){const r=tn(t.type);for(const o of r){if("texture"!==o.type)continue;const r=t.data[o.field];if("string"==typeof r&&r&&void 0===s[r])try{s[r]=Do(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 u={},d=null;if(r&&(d=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),u=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){const i=nn(s.type);if(!i||!s.data)continue;const a=s.data[i.skeletonField],l=s.data[i.atlasField];if(!a||!l)continue;const c=r.resolvePath(a),u=r.resolvePath(l);try{const s=await r.readText(l),i="binary"===x(c)?.contentType;let d,h;if(i){const e=await r.readBinary(a);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await r.readText(a),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const f=n.loadSkeleton(d,h,s,s.length,i);if(t._free(d),f<0)continue;o[a]=f;const p=Lo(s),g=u.substring(0,u.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=Do(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){const t={gravity:i?.gravity??{...ee},fixedTimestep:i?.fixedTimestep??te,subStepCount:i?.subStepCount??4};new $o("",t,()=>Promise.resolve(o)).build(e)}const h=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){const r=tn(t.type).find(e=>"font"===e.type);if(!r)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===s[o])try{let t,r;const i=x(o);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await n.readText(o)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await n.readText(l),r=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(o),r=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[o]=0;continue}const l=r?`${r}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=Do(e,c,!1),d=e.getResourceManager();s[o]=d.loadBitmapFont(t,u,c.width,c.height)}catch{s[o]=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)continue;const r=tn(e.type).find(e=>"material"===e.type);if(!r)continue;const o=e.data[r.field];if("string"==typeof o&&o&&void 0===n[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){n[o]=0;continue}const r=e.vertexSource+e.fragmentSource;let i=s[r];i||(i=Ot.createShader(e.vertexSource,e.fragmentSource),s[r]=i),n[o]=Ot.createFromAsset(e,i)}catch{n[o]=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=tn(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,h,f);const p=ln(e.world,n);if(l&&e.hasResource(xs))for(const t of p.values())e.world.insert(t,Xe,{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){const i=nn(t.type);if(!i||!t.data)continue;const a=n[t.data[i.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=s.get(o.id);void 0!==c&&(r[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return r}(d,n,u,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=Z);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,He)?c.get(o,He):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(i,l*d);let h=0;if(c.has(o,Be)){const e=Oo(c.get(o,Be),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,d,f);const p=n.HEAPU32[d>>2],g=n.HEAPU32[f>>2],y=new Float32Array(n.HEAPF32.buffer,c,8*r),m=new Uint16Array(n.HEAPU8.buffer,u,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,h),t._free(_),t._free(w),n._free(c),n._free(u),n._free(d),n._free(f)}h&&t._free(h)}})}(e,t,r,d,s)}if(a){const t=e.getResource(pn);t&&t.setAddressableManifest(a)}}function jo(e,t,n){return{name:e,data:t,async setup(){await Ho(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class Xo{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)continue;const r=nn(e.type);if(r){const s=e.data[r.skeletonField],o=e.data[r.atlasField];s&&("binary"===x(s)?.contentType?n.add(s):t.add(s)),o&&t.add(o)}const o=tn(e.type);for(const n of o){const r=e.data[n.field];"string"==typeof r&&r&&("font"===n.type?(s.add(r),t.add(r)):"material"===n.type&&t.add(r))}}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 Yo="__preview__";class No{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:Yo,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Yo),this.loadPromise_=t.load(Yo).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 Xo(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.spineInitPromise;if(r){s=(await r).controller.raw}await Ho(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,Yo)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([$e]);for(const s of n){if(e.get(s,$e).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([ze]);for(const r of s){const s=e.get(r,ze);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(xs).getScene(Yo),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,ke,i);const a={isActive:!0,projectionType:Ae.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Ie.ColorAndDepth};e.insert(o,$e,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(Yo),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 Vo={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=us.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:us.getTargetTexture(n),width:e.width,height:e.height}},release(e){us.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(us.releaseRenderTarget(e._handle),Vo.create({width:t,height:n,depth:!0})),begin(e,t){us.begin(t,e._handle)},end(){us.end()},getDepthTexture:e=>us.getTargetDepthTexture(e._handle)};let Go=!1;function qo(e){Go=e}function Jo(){return Go}function Ko(){return!Go}var Qo;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Qo||(Qo={}));class Zo{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Qo[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Qo.Debug:console.debug(t,n);break;case Qo.Info:console.log(t,n);break;case Qo.Warn:console.warn(t,n);break;case Qo.Error:console.error(t,n)}}}class ei{constructor(){this.handlers_=[],this.minLevel_=Qo.Info,this.addHandler(new Zo)}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(Qo.Debug,e,t,n)}info(e,t,n){this.log(Qo.Info,e,t,n)}warn(e,t,n){this.log(Qo.Warn,e,t,n)}error(e,t,n){this.log(Qo.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 ti=new ei;function ni(){return ti}function si(e){ti.setMinLevel(e)}function ri(e,t,n){ti.debug(e,t,n)}function oi(e,t,n){ti.info(e,t,n)}function ii(e,t,n){ti.warn(e,t,n)}function ai(e,t,n){ti.error(e,t,n)}const li=[dr,Sr,Br,Kr,so,Dr,io,lo,ho,eo,Yr,fo,yo,xo,bo,To,Ro];function ci(e,t){return function(e,t){const n=Ms.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Fn(e),Ut(e),qn(e),es(e),ls(e),hs(e);const r=new gs;n.setPipeline(r);let o=h();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,o){o||(o=Cs(e,s,t,r));const i=n.getResource(It);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(It,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=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;us.setClearColor(e.x,e.y,e.z,e.w)}const u=(h()-o)/1e3;let d;if(us.resize(t,l),ss.isInitialized()&&ss.getPassCount()>0&&!ss.isBypassed()&&ss.resize(t,l),n.hasResource(xs)){const e=n.getResource(xs).getActiveScenes();e.length>0&&(d=new Set(e))}r.setActiveScenes(d??null);const f=Cs(e,s,t,l,n.world,d);if(a(t,l,f),0===f.length)r.render({registry:{_cpp:s},viewProjection:Es,width:t,height:l,elapsed:u});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:u})}us.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(dt.First,l),n.addSystemToSchedule(dt.Last,c),n.addPlugin(yn),n.addPlugin(En),n.addPlugin(bt),n.addPlugin(Ss),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:li,...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{Ms as App,gn as AssetPlugin,mn as AssetRefCounter,fn as AssetServer,pn as Assets,Jt as AsyncCache,Oe as BitmapText,Ft as BlendMode,Je as BodyType,Ve as BoxCollider,Tr as Button,Er as ButtonState,$e as Camera,ze as Canvas,qe as CapsuleCollider,Le as Children,Ge as CircleCollider,Ie as ClearFlags,lt as Commands,ut as CommandsInstance,Y as DEFAULT_DESIGN_HEIGHT,X as DEFAULT_DESIGN_WIDTH,Z as DEFAULT_FALLBACK_DT,te as DEFAULT_FIXED_TIMESTEP,q as DEFAULT_FONT_FAMILY,J as DEFAULT_FONT_SIZE,ee as DEFAULT_GRAVITY,K as DEFAULT_LINE_HEIGHT,Q as DEFAULT_MAX_DELTA_TIME,N as DEFAULT_PIXELS_PER_UNIT,ne as DEFAULT_SPINE_SKIN,G as DEFAULT_SPRITE_SIZE,V as DEFAULT_TEXT_CANVAS_SIZE,Xn as DataType,oo as DragState,ro as Draggable,$n as Draw,vo as Dropdown,ct as EntityCommands,zs as FillDirection,Vr as FillMethod,Gr as FillOrigin,jr as FocusManager,Hr as FocusManagerState,Or as Focusable,ps as GLDebug,Qn as Geometry,oe as INVALID_ENTITY,ae as INVALID_FONT,le as INVALID_MATERIAL,ie as INVALID_TEXTURE,qr as Image,Nr as ImageType,xt as Input,vt as InputPlugin,wt as InputState,Mr as Interactable,mo as ListView,ke as LocalTransform,Qo as LogLevel,ei as Logger,Ot as Material,Kt as MaterialLoader,rt as Mut,je as Name,De as Parent,Uo as Physics,Fo as PhysicsEvents,$o as PhysicsPlugin,ss as PostProcess,Sn as PrefabServer,Mn as Prefabs,Pn as PrefabsPlugin,No as PreviewPlugin,no as ProgressBar,to as ProgressBarDirection,Ae as ProjectionType,it as Query,at as QueryInstance,gs as RenderPipeline,os as RenderStage,Vo as RenderTexture,us as Renderer,Ze as Res,et as ResMut,Ne as RigidBody,se as RuntimeConfig,po as SafeArea,Fe as ScaleMode,xs as SceneManager,ws as SceneManagerState,Xe as SceneOwner,dt as Schedule,Ar as ScreenSpace,ao as ScrollView,qt as ShaderSources,uo as Slider,co as SliderDirection,He as SpineAnimation,We as Sprite,_t as SystemRunner,ar as Text,rr as TextAlign,Lr as TextInput,Xr as TextInputPlugin,ir as TextOverflow,ur as TextPlugin,lr as TextRenderer,or as TextVerticalAlign,st as Time,Qr as Toggle,It as UICameraInfo,Cr as UIEventQueue,Rr as UIEvents,Pr as UIInteraction,Ur as UIInteractionPlugin,kr as UILayoutPlugin,hr as UIMask,br as UIMaskPlugin,Ds as UIRect,Ue as Velocity,Xo as WebAssetProvider,At as World,Be as WorldTransform,yt as addStartupSystem,gt as addSystem,mt as addSystemToSchedule,Xs as applyDirectionalFill,re as applyRuntimeConfig,yn as assetPlugin,jn as clearDrawCallbacks,be as clearUserComponents,he as color,Os as computeFillAnchors,js as computeFillSize,Hs as computeHandleAnchors,Us as computeUIRectLayout,vr as createMaskProcessor,jo as createRuntimeSceneConfig,ci as createWebApp,ri as debug,we as defineComponent,Qe as defineResource,ft as defineSystem,xe as defineTag,ai as error,hn as findEntityByName,Ps as flushPendingSystems,b as getAddressableType,S as getAddressableTypeByEditorType,P as getAllAssetExtensions,R as getAssetMimeType,x as getAssetTypeEntry,Ce as getComponent,en as getComponentAssetFields,Ye as getComponentDefaults,T as getCustomExtensions,v as getEditorType,ni as getLogger,t as getPlatform,s as getPlatformType,ve as getUserComponent,C as getWeChatPackOptions,oi as info,Fn as initDrawAPI,hs as initGLDebugAPI,qn as initGeometryAPI,Ut as initMaterialAPI,es as initPostProcessAPI,ls as initRendererAPI,bt as inputPlugin,wn as instantiatePrefab,fr as intersectRects,pr as invertMatrix4,Pe as isBuiltinComponent,A as isCustomExtension,Jo as isEditor,M as isKnownAssetExtension,n as isPlatformInitialized,Ko as isRuntime,kt as isTextureRef,r as isWeChat,o as isWeb,un as loadComponent,Io as loadPhysicsModule,Ho as loadRuntimeScene,ln as loadSceneData,cn as loadSceneWithAssets,E as looksLikeAssetPath,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,wr as pointInOBB,yr as pointInWorldRect,En as prefabsPlugin,fe as quat,Te as registerComponent,Zt as registerComponentAssetFields,rn as registerComponentEntityFields,On as registerDrawCallback,_n as registerEmbeddedAssets,Gt as registerMaterialCallback,Ss as sceneManagerPlugin,gr as screenToWorld,qo as setEditorMode,wo as setListViewRenderer,si as setLogLevel,Tt as setWasmErrorHandler,kn as shutdownDrawAPI,fs as shutdownGLDebugAPI,Jn as shutdownGeometryAPI,Dt as shutdownMaterialAPI,ts as shutdownPostProcessAPI,cs as shutdownRendererAPI,Qs as syncFillSpriteSize,Yr as textInputPlugin,dr as textPlugin,Ao as transitionTo,Dr as uiInteractionPlugin,Br as uiLayoutPlugin,Sr as uiMaskPlugin,li as uiPlugins,Se as unregisterComponent,Hn as unregisterDrawCallback,dn as updateCameraAspectRatio,ce as vec2,ue as vec3,de as vec4,ii as warn,vs as wrapSceneSystem,$ as wxFileExists,z as wxFileExistsSync,L as wxGetImagePixels,D as wxLoadImage,O as wxLoadImagePixels,B as wxReadFile,W 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 u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}function f(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}function p(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 g(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 y=[{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={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},_=new Map,w=new Set;for(const e of y)for(const t of e.extensions)_.set(t,e),w.add(t);function x(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function v(e){return _.get(x(e))}function b(e){return v(e)?.editorType??"unknown"}function S(e){return v(e)?.addressableType??null}function M(e){for(const t of y)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function P(e){return w.has(e.toLowerCase())}function E(){return w}function T(e){return"string"==typeof e&&(!!e.includes("/")&&P(x(e)))}function C(){const e=[];for(const t of y)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function R(){return C().map(e=>({type:"suffix",value:e}))}function A(e){return m[e.toLowerCase()]}function I(e){const t=v(e);return t?.wechatPackInclude??!1}let F=null;function k(){return F||(F=wx.getFileSystemManager()),F}function B(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if(I(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 W(e){return new Promise((t,n)=>{k().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)=>{k().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(B(e,t.errMsg)))}})})}function z(e){return new Promise(t=>{k().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function U(e){const t=k();try{return t.accessSync(e),!0}catch{return!1}}function D(e,t){return new Promise((n,s)=>{k().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function L(e){return new Promise((t,n)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>n(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function O(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){const n=wx.createCanvas();n.width=e,n.height=t;const s=n.getContext("2d");return{canvas:n,ctx:s}}(t,n);s.clearRect(0,0,t,n),s.drawImage(e,0,0);const r=s.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(r.data.buffer)}}async function H(e){return O(await L(e))}let j=!1;const X=new class{constructor(){this.name="wechat"}async fetch(e,t){return p(e,t)}async readFile(e){return W(e)}async readTextFile(e){return $(e)}async fileExists(e){return z(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return g(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)})}},Y=1920,N=1080,V=100,G=512,q={x:100,y:100},J="Arial",K=24,Q=1.2,Z=.5,ee=1/60,te={x:0,y:-9.81},ne=1/60,se="default",re={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function oe(e){e.Text&&(e.Text._default.fontFamily=re.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=re.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=re.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=re.canvasMatchWidthOrHeight)}const ie=0,ae=4294967295,le=4294967295,ce=0,ue=(e=0,t=0)=>({x:e,y:t}),he=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),de=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),fe=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),pe=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function ge(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(ge);const t={};for(const n in e)t[n]=ge(e[n]);return t}let ye=0;function me(e,t){const n=++ye;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...ge(t),...e}:ge(t)}}const _e=new Map;function we(){return"undefined"==typeof window?_e:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function xe(e,t){const n=Te.get(e)??we().get(e);if(n)return n;const s=me(e,t);return we().set(e,s),Te.set(e,s),Pe(e,t,!1),s}function ve(e){const t=Te.get(e)??we().get(e);if(t)return t;const n=me(e,{});return we().set(e,n),Te.set(e,n),Pe(e,{},!0),n}function be(e){return we().get(e)}function Se(){const e=we();for(const t of e.keys())Te.delete(t);e.clear()}function Me(e){we().delete(e),Te.delete(e)}function Pe(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function Ee(e){return!0===e._builtin}const Te=new Map;function Ce(e,t){Te.set(e,t)}function Re(e){return Te.get(e)??be(e)}function Ae(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return Te.set(e,n),n}const Ie={Perspective:0,Orthographic:1},Fe={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ke={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},Be=Ae("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),We=Ae("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),$e=Ae("Sprite",{texture:ae,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}),ze=Ae("Camera",{projectionType:Ie.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:Fe.ColorAndDepth}),Ue=Ae("Canvas",{designResolution:{x:Y,y:N},pixelsPerUnit:100,scaleMode:ke.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),De=Ae("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Le=Ae("Parent",{entity:0}),Oe=Ae("Children",{entities:[]}),He=Ae("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:le,enabled:!0}),je=Ae("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}),Xe={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},Ye=xe("SceneOwner",{scene:"",persistent:!1});function Ne(e){const t=Re(e);return t?ge(t._default):null}Ce("Name",Xe);const Ve=Ae("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Ge=Ae("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),qe=Ae("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Je=Ae("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ke={Static:0,Kinematic:1,Dynamic:2};let Qe=0;function Ze(e,t){const n=++Qe;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function et(e){return{_type:"res",_resource:e}}function tt(e){return{_type:"res_mut",_resource:e}}class nt{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 st{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 nt(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const rt=Ze({delta:0,elapsed:0,frameCount:0},"Time");function ot(e){return{_type:"mut",_component:e}}function it(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function at(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{it(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class lt{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>it(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 u=null;this.world_.beginIteration();try{for(const h of s){if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(h,t[n])){e=!0;break}if(e)continue}a[0]=h;for(let e=0;e<r;e++)a[e+1]=this.world_.get(h,n[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=h}yield a}}finally{if(this.world_.endIteration(),null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function ct(){return{_type:"commands"}}class ut{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=Ee(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class ht{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ut(this,null);return this.spawned_.push(e),e}entity(e){return new ut(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 dt;!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"}(dt||(dt={}));let ft=0;function pt(e,t,n){const s=++ft;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function gt(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function yt(e){gt().push({schedule:dt.Update,system:e})}function mt(e){gt().push({schedule:dt.Startup,system:e})}function _t(e,t){gt().push({schedule:e,system:t})}class wt{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 ht&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new lt(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new ht(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class xt{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 vt=Ze(new xt,"Input");class bt{constructor(e){this.target_=e??null}build(e){const n=new xt;e.insertResource(vt,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(dt.Last,pt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const St=new bt;function Mt(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=Pt(t[e]),o=Pt(r);"null"!==n&&"undefined"!==n&&(n!==o&&null!=r&&s.push({field:e,expected:n,actual:o,value:r}))}return s}function Pt(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Et(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 Tt=null;function Ct(e){Tt=e}function Rt(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Tt&&Tt(e,t)}function At(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}:At(e)}}return t}class It{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,this.nextEntityId_=0}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw Rt(e,"spawn"),e}else e=++this.nextEntityId_;return this.entities_.add(e),this.worldVersion_++,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){Rt(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){Rt(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Rt(t,`removeParent(entity=${e})`)}}insert(e,t,n){return Ee(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return Ee(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return Ee(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(Ee(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return Rt(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.");Ee(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_,s=n[`add${e}`],r=n[`get${e}`],o=n[`has${e}`],i=n[`remove${e}`];if("function"!=typeof s||"function"!=typeof r||"function"!=typeof o||"function"!=typeof i)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:s.bind(n),get:r.bind(n),has:o.bind(n),remove:i.bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const e=Mt(t._name,t._default,s);if(e.length>0)throw new Error(Et(t._name,e))}const r={...t._default,...s};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,At(r))}catch(n){Rt(n,`insertBuiltin(${t._name}, entity=${e})`)}return this.worldVersion_++,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 Rt(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 Rt(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){Rt(n,`removeBuiltin(${t._name}, entity=${e})`)}this.worldVersion_++}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const r=Mt(t._name,t._default,e);if(r.length>0)throw new Error(Et(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}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 Te)if(Ee(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=we();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(!Ee(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.slice()}),a}}const Ft=Ze({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var kt;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"}(kt||(kt={}));let Wt=null,$t=null,zt=1;const Ut=new Map;function Dt(e){Wt=e,$t=e.getResourceManager(),qt()}function Lt(){0!==Xt&&Wt&&(Wt._free(Xt),Xt=0),Ut.clear(),zt=1,jt=!1,Nt.clear(),Vt=null,$t=null,Wt=null}function Ot(){if(!$t)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return $t}const Ht={createShader:(e,t)=>Ot().createShader(e,t),releaseShader(e){e>0&&Ot().releaseShader(e)},create(e){const t=zt++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??kt.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 Ut.set(t,n),t},get:e=>Ut.get(e),setUniform(e,t,n){const s=Ut.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=Ut.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Ut.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Ut.get(e);return t?.blendMode??kt.Normal},setDepthTest(e,t){const n=Ut.get(e);n&&(n.depthTest=t)},getShader(e){const t=Ut.get(e);return t?.shader??0},release(e){Ut.delete(e)},isValid:e=>Ut.has(e),releaseAll(){Ut.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??kt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ut.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=zt++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ut.set(n,s),n},toAssetData(e,t){const n=Ut.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=Ut.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let jt=!1,Xt=0;const Yt=4096,Nt=new Map;let Vt=null;function Gt(e){const t=(0===Xt&&Wt&&(Xt=Wt._malloc(Yt)),Xt);if(0===t||!Wt)return{ptr:0,count:0};let n=0,s=0;const r=Wt.HEAPU8,o=Wt.HEAPU32,i=Wt.HEAPF32;for(const[a,l]of e){if(n+128>Yt)break;let e=Nt.get(a);e||(Vt||(Vt=new TextEncoder),e=Vt.encode(a),Nt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function qt(){if(!Wt||jt)return;Wt.materialDataProvider=(e,t,n,s,r)=>{const o=Ut.get(e);if(!o)return Wt.HEAPU32[t>>2]=0,Wt.HEAPU32[n>>2]=0,Wt.HEAPU32[s>>2]=0,void(Wt.HEAPU32[r>>2]=0);Wt.HEAPU32[t>>2]=o.shader,Wt.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Gt(o.uniforms);Wt.HEAPU32[s>>2]=i,Wt.HEAPU32[r>>2]=a},jt=!0}const Jt={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class Kt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,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 Qt{constructor(e,t=""){this.cache_=new Kt,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ht.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ht.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:Ht.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 Zt=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 en(e,t){Zt.set(e,t)}function tn(e){const t=Zt.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 nn(e){return Zt.get(e)?.fields??[]}function sn(e){return Zt.get(e)?.spine??null}const rn=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function on(e,t){rn.set(e,t)}function an(e,t){const n=rn.get(e.type);if(!n)return;const s=e.data;for(const e of n){const n=s[e];if("number"==typeof n&&0!==n){const r=t.get(n);s[e]=void 0!==r?r:0}}}function ln(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();n.set(s.id,t),e.insert(t,Xe,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;const t=n.get(s.id);for(const r of s.components)an(r,n),dn(e,t,r,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}function cn(e,t){return ln(e,t)}async function un(e,t,n){const s=n?.assetServer,r=n?.assetBaseUrl,o=new Map;s&&await async function(e,t,n,s){e=JSON.parse(JSON.stringify(e));const r=new Map;for(const e of hn.keys())r.set(e,new Set);const o=[],i=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Zt.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}`;i.has(t)||(i.add(t),o.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&r.get(e.type)?.add(t)}}const a=new Map,l=[...hn.entries()].map(async([e,o])=>{const i=await o.load(r.get(e),t,n,s);a.set(e,i)}),c=o.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});await Promise.all([...l,...c]);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Zt.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&(n[e.field]=a.get(e.type)?.get(t)??0)}}}(t,s,r,o);const i=ln(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return i}const hn=new Map([["texture",{async load(e,t,n,s){const r=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,i=await t.loadTexture(o);r.set(e,i.handle),s.set(e,o)}catch(t){console.warn(`Failed to load texture: ${e}`,t),r.set(e,0)}});return await Promise.all(o),r}}],["material",{async load(e,t,n){const s=new Map,r=[...e].map(async e=>{try{const r=await t.loadMaterial(e,n);s.set(e,r.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(r),s}}],["font",{async load(e,t,n){const s=new Map,r=[...e].map(async e=>{try{const r=await t.loadBitmapFont(e,n);s.set(e,r)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(r),s}}]]);function dn(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=Re(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 fn(e,t){const n=e.getEntitiesWithComponents([ze]);for(const s of n){const n=e.get(s,ze);n&&(n.aspectRatio=t,e.insert(s,ze,n))}}function pn(e,t){const n=e.getEntitiesWithComponents([Xe]);for(const s of n){const n=e.get(s,Xe);if(n&&n.value===t)return s}return null}class gn{constructor(e){this.textureCache_=new Kt,this.shaderCache_=new Kt,this.jsonCache_=new Kt,this.textCache_=new Kt,this.binaryCache_=new Kt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Kt,this.prefabCache_=new Kt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.module_=e,this.canvas_=h(re.textCanvasSize,re.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 Qt(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(),Ht.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),u="binary"===v(e)?.contentType,h=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(h,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),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=v(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 un(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 Ht.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 Ht.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 yn=Ze(null,"Assets");class mn{build(e){const t=e.wasmModule;t?e.insertResource(yn,new gn(t)):console.warn("AssetPlugin: No WASM module available")}}const _n=new mn;class wn{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 xn(e,t){const n=e.getResource(yn);n&&n.registerEmbeddedAssets(t)}async function vn(e,t,n){const{entities:s,rootId:r}=await Sn(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 un(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 bn=10;async function Sn(e,t,n,s,r,o=0){if(o>bn)throw new Error(`Prefab nesting depth exceeded ${bn}. 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 Sn(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),u=s.prefabEntityId===e.rootEntityId,h={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:u?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};Mn(h,t),l.push(h)}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 Mn(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 Pn{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 vn(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const En=Ze(null,"Prefabs");class Tn{constructor(){this.name="PrefabsPlugin",this.dependencies=[yn]}build(e){const t=e.getResource(yn);e.insertResource(En,new Pn(e.world,t))}}const Cn=new Tn;let Rn=null,An=0,In=0,Fn=0;const kn=new Float32Array(256);function Bn(e){Rn=e,An=Rn._malloc(64),In=Rn._malloc(64),Fn=Rn._malloc(1024)}function Wn(){Rn&&(An&&(Rn._free(An),An=0),In&&(Rn._free(In),In=0),Fn&&(Rn._free(Fn),Fn=0)),Rn=null}function $n(){if(!Rn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Rn}const zn={r:1,g:1,b:1,a:1},Un={begin(e){const t=$n();try{t.HEAPF32.set(e,An/4),t.draw_begin(An)}catch(e){Rt(e,"Draw.begin")}},end(){try{$n().draw_end()}catch(e){Rt(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){Rt(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){Rt(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){Rt(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){Rt(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){Rt(e,"Draw.circleOutline")}},texture(e,t,n,s=zn){try{$n().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){Rt(e,"Draw.texture")}},textureRotated(e,t,n,s,r=zn){try{$n().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)}catch(e){Rt(e,"Draw.textureRotated")}},setLayer(e){$n().draw_setLayer(e)},setDepth(e){$n().draw_setDepth(e)},getDrawCallCount:()=>Rn?Rn.draw_getDrawCallCount():0,getPrimitiveCount:()=>Rn?Rn.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,In/4),s.draw_mesh(e,t,In)}catch(n){Rt(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=$n(),r=Ht.get(t);if(!r)return;if(Un.setBlendMode(r.blendMode),Un.setDepthTest(r.depthTest),0===r.uniforms.size)return void Un.drawMesh(e,r.shader,n);let o;if(s.HEAPF32.set(n,In/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,n]of r.uniforms){const s=On(t);if(!(s<0)){if(Bt(n))kn[o++]=10,kn[o++]=s,kn[o++]=n.slot??e++,kn[o++]=n.textureId;else if("number"==typeof n)kn[o++]=1,kn[o++]=s,kn[o++]=n;else if(Array.isArray(n)){kn[o++]=n.length,kn[o++]=s;for(let e=0;e<n.length;e++)kn[o++]=n[e]}else"w"in n?(kn[o++]=4,kn[o++]=s,kn[o++]=n.x,kn[o++]=n.y,kn[o++]=n.z,kn[o++]=n.w):"z"in n?(kn[o++]=3,kn[o++]=s,kn[o++]=n.x,kn[o++]=n.y,kn[o++]=n.z):(kn[o++]=2,kn[o++]=s,kn[o++]=n.x,kn[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(kn.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void s.draw_mesh(e,r.shader,In);s.HEAPF32.set(r.cachedBuffer_.subarray(0,o),Fn/4),s.draw_meshWithUniforms(e,r.shader,In,Fn,o)}catch(n){Rt(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Dn={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 On(e){const t=Dn[e];return void 0!==t?t:(Ln.has(e)||(Ln.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Dn).join(", ")}`)),-1)}const Hn=new Map;function jn(e,t,n){Hn.set(e,{fn:t,scene:n??""})}function Xn(e){Hn.delete(e)}function Yn(){Hn.clear()}var Nn;!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"}(Nn||(Nn={}));let Vn=null,Gn=0,qn=0,Jn=0;function Kn(e){Vn=e,Gn=Vn._malloc(262144),qn=Vn._malloc(65536),Jn=Vn._malloc(256)}function Qn(){Vn&&(Gn&&Vn._free(Gn),qn&&Vn._free(qn),Jn&&Vn._free(Jn),Gn=0,qn=0,Jn=0),Vn=null}function Zn(){if(!Vn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Vn}const es={create(e){const t=Zn(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,Gn/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Jn,r).set(o),t.geometry_init(n,Gn,s,Jn,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,qn,s).set(e.indices),t.geometry_setIndices16(n,qn,s)}else{new Uint32Array(t.HEAPU8.buffer,qn,s).set(e.indices),t.geometry_setIndices32(n,qn,s)}}return n},updateVertices(e,t,n=0){const s=Zn(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,Gn/4),s.geometry_updateVertices(e,Gn,r,n)},release(e){e>0&&Zn().geometry_release(e)},isValid:e=>!(!Vn||e<=0)&&Vn.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return es.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:Nn.Float2},{name:"a_texCoord",type:Nn.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 es.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Nn.Float2},{name:"a_texCoord",type:Nn.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 es.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Nn.Float2},{name:"a_texCoord",type:Nn.Float2}],indices:new Uint16Array(i)})}};let ts=null;function ns(e){ts=e}function ss(){ts&&os.isInitialized()&&os.shutdown(),ts=null}function rs(){if(!ts)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return ts}const os={init(e,t){try{return rs().postprocess_init(e,t)}catch(n){return Rt(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{rs().postprocess_shutdown()}catch(e){Rt(e,"PostProcess.shutdown")}},resize(e,t){try{rs().postprocess_resize(e,t)}catch(n){Rt(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return rs().postprocess_addPass(e,t)}catch(t){return Rt(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{rs().postprocess_removePass(e)}catch(t){Rt(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{rs().postprocess_setPassEnabled(e,t)}catch(t){Rt(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return rs().postprocess_isPassEnabled(e)}catch(t){return Rt(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{rs().postprocess_setUniformFloat(e,t,n)}catch(n){Rt(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{rs().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){Rt(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{rs().postprocess_begin()}catch(e){Rt(e,"PostProcess.begin")}},end(){try{rs().postprocess_end()}catch(e){Rt(e,"PostProcess.end")}},getPassCount(){try{return rs().postprocess_getPassCount()}catch(e){return Rt(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!ts)return!1;try{return ts.postprocess_isInitialized()}catch(e){return Rt(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{rs().postprocess_setBypass(e)}catch(e){Rt(e,"PostProcess.setBypass")}},isBypassed(){if(!ts)return!0;try{return ts.postprocess_isBypassed()}catch(e){return Rt(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Ht.createShader(is,"#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:()=>Ht.createShader(is,"#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:()=>Ht.createShader(is,"#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:()=>Ht.createShader(is,"#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")},is="#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 as;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(as||(as={}));let ls=null,cs=0;function us(e){ls=e,cs=ls._malloc(64)}function hs(){ls&&cs&&(ls._free(cs),cs=0),ls=null}const ds={init(e,t){ls?.renderer_init(e,t)},resize(e,t){ls?.renderer_resize(e,t)},begin(e,t){if(ls&&cs)try{ls.HEAPF32.set(e,cs/4),ls.renderer_begin(cs,t??0)}catch(e){Rt(e,"Renderer.begin")}},flush(){try{ls?.renderer_flush()}catch(e){Rt(e,"Renderer.flush")}},end(){try{ls?.renderer_end()}catch(e){Rt(e,"Renderer.end")}},submitSprites(e){if(ls)try{ls.renderer_submitSprites(e._cpp)}catch(e){Rt(e,"Renderer.submitSprites")}},submitBitmapText(e){if(ls)try{ls.renderer_submitBitmapText(e._cpp)}catch(e){Rt(e,"Renderer.submitBitmapText")}},submitSpine(e){if(ls)try{ls.renderer_submitSpine?.(e._cpp)}catch(e){Rt(e,"Renderer.submitSpine")}},setStage(e){ls?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>ls?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){ls?.renderer_releaseTarget(e)},getTargetTexture:e=>ls?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>ls?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){ls?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){ls?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){ls?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){ls?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>ls?ls.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>ls?{drawCalls:ls.renderer_getDrawCalls(),triangles:ls.renderer_getTriangles(),sprites:ls.renderer_getSprites(),text:ls.renderer_getText(),spine:ls.renderer_getSpine?.()??0,meshes:ls.renderer_getMeshes(),culled:ls.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let fs=null;function ps(e){fs=e}function gs(){fs=null}const ys={enable(){fs?.gl_enableErrorCheck(!0)},disable(){fs?.gl_enableErrorCheck(!1)},check:e=>fs?.gl_checkErrors(e)??0,diagnose(){fs?.renderer_diagnose()}};class ms{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_||(ds.resize(s,r),os.isInitialized()&&os.getPassCount()>0&&os.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),ds.setViewport(0,0,s,r),ds.clearBuffers(3),ds.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),ds.submitSprites(t),ds.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):ds.submitSpine(t),ds.flush(),this.executeDrawCallbacks(n,o),ds.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;ds.setViewport(s.x,s.y,s.w,s.h),ds.setScissor(s.x,s.y,s.w,s.h,!0),ds.clearBuffers(r),ds.setScissor(0,0,0,0,!1),ds.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),ds.submitSprites(t),ds.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):ds.submitSpine(t),ds.flush(),this.executeDrawCallbacks(n,o),ds.end()}executeDrawCallbacks(e,t){const n=Hn;if(n.size>0){Un.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)}Un.end();for(const e of s)Xn(e)}}}const _s="__scene_transition_overlay__";class ws{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class xs{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,Ye,{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),jn(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=os.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){os.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,Ye)){const n=this.app_.world.get(e,Ye);n.persistent=t,this.app_.world.insert(e,Ye,n)}}}class vs{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??re.sceneTransitionDuration,r=t.color??{...re.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:r,targetScene:e,options:t,resolve:n},jn(_s,()=>{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;Un.setLayer(9999),Un.setDepth(9999),Un.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()=>{try{n&&n!==e&&await this.unload(n,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,Xn(_s),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Xn(_s),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 ws(t);this.scenes_.set(e,n);const s=new xs(n,this.app_);this.contexts_.set(e,s);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(yn)?this.app_.getResource(yn):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(yn)&&(t.assetServer=this.app_.getResource(yn));const s=await un(this.app_.world,r,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,Ye,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=Ss(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 ws(t);this.scenes_.set(e,n);const s=new xs(n,this.app_);this.contexts_.set(e,s);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(yn)?this.app_.getResource(yn):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(yn)&&(t.assetServer=this.app_.getResource(yn));const s=await un(this.app_.world,r,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,Ye,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=Ss(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,Ye)){if(this.app_.world.get(e,Ye).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())Xn(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{os.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)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s={};let r=!1;if(n.has(e,$e)){const t=n.get(e,$e);s.sprite=t.color.a,t.color={...t.color,a:0},n.insert(e,$e,t),r=!0}if(n.has(e,je)){const t=n.get(e,je);s.spine=t.color.a,t.color={...t.color,a:0},n.insert(e,je,t),r=!0}if(n.has(e,He)){const t=n.get(e,He);s.bitmapText=t.color.a,t.color={...t.color,a:0},n.insert(e,He,t),r=!0}r&&t.savedAlphas.set(e,s)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s=t.savedAlphas.get(e);if(s){if(void 0!==s.sprite&&n.has(e,$e)){const t=n.get(e,$e);t.color={...t.color,a:s.sprite},n.insert(e,$e,t)}if(void 0!==s.spine&&n.has(e,je)){const t=n.get(e,je);t.color={...t.color,a:s.spine},n.insert(e,je,t)}if(void 0!==s.bitmapText&&n.has(e,He)){const t=n.get(e,He);t.color={...t.color,a:s.bitmapText},n.insert(e,He,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{os.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 bs=Ze(null,"SceneManager");function Ss(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(bs).getSceneStatus(t)&&n._fn(...s)}}}const Ms=pt([tt(bs),et(rt)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Ps={name:"SceneManager",build(e){const t=new vs(e);e.insertResource(bs,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(bs),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(dt.Startup,n),e.addSystemToSchedule(dt.Last,Ms)}};class Es{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(dt.Last);else{this.runSchedule(dt.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(dt.FixedPreUpdate),this.runSchedule(dt.FixedUpdate),this.runSchedule(dt.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(dt.PreUpdate),this.runSchedule(dt.Update),this.runSchedule(dt.PostUpdate),this.runSchedule(dt.Last),this.step_pending_&&(this.step_pending_=!1)}requestAnimationFrame(this.mainLoop)},this.world_=new It,this.resources_=new st;for(const e of Object.values(dt))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Es}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(dt.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(dt.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 Ct(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(bs).register(e),this}setInitialScene(e){return this.getResource(bs).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new wt(this.world_,this.resources_),this.resources_.insert(rt,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(dt.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Yn();for(const e of this.installed_plugins_)try{e.cleanup?.()}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.clear();const e=[gs,hs,ss,Qn,Lt,Wn];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(rt);t.delta=e,t.elapsed+=e,t.frameCount++}}function Ts(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 Cs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Rs(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case ke.FixedWidth:return o;case ke.FixedHeight:return i;case ke.Expand:return Math.max(o,i);case ke.Shrink:return Math.min(o,i);case ke.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function As(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,Ye);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 u,h=0,d=0;if(r.projectionType===Ie.Orthographic){if(d=r.orthoSize,l){d=Rs(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}h=d*a,u=Fs(-h,h,-d,d,-r.farPlane,r.farPlane)}else u=Bs(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(Us(u,f)),viewportRect:i,clearFlags:r.clearFlags,priority:r.priority,halfW:h,halfH:d,cameraX:o.position.x,cameraY:o.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const Is=new Float32Array(16);function Fs(e,t,n,s,r,o){const i=Is;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 ks=new Float32Array(16);function Bs(e,t,n,s){const r=ks;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 Ws=new Float32Array(16);function $s(e,t,n){const s=Ws;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 zs=new Float32Array(16);function Us(e,t){const n=zs;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}const Ds={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function Ls(e,t,n,s,r,o,i={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,u=o.left+t.x*a,h=o.bottom+e.y*l,d=o.bottom+t.y*l;let f,p,g,y;e.x===t.x?(f=c+n.x-r.x*i.x,g=f+r.x):(f=c+n.x,g=u+s.x),e.y===t.y?(p=h+n.y-r.y*i.y,y=p+r.y):(p=h+n.y,y=d+s.y);const m=Math.max(0,g-f),_=Math.max(0,y-p);return{originX:f+i.x*m,originY:p+i.y*_,width:m,height:_,rect:{left:f,bottom:p,right:g,top:y}}}const Os=xe("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},_dirty:!0,_computedWidth:void 0,_computedHeight:void 0,_layoutManaged:void 0});function Hs(e,t){e.has(t,$e)||e.insert(t,$e,{texture:ae,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0})}function js(e,t){switch(e){case Ds.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Ds.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Ds.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function Xs(e,t){switch(e){case Ds.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case Ds.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case Ds.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1-t}};default:return{anchorMin:{x:t,y:0},anchorMax:{x:t,y:1}}}}function Ys(e,t,n,s){switch(e){case Ds.BottomToTop:case Ds.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function Ns(e,t,n,s){if(!e.has(t,Os))return;const r=e.get(t,Os),o=js(n,s);r.anchorMin=o.anchorMin,r.anchorMax=o.anchorMax,r.offsetMin=o.offsetMin,r.offsetMax=o.offsetMax,o.anchorMin.x===o.anchorMax.x&&(r.size={...r.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(r.size={...r.size,y:0}),e.insert(t,Os,r)}function Vs(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Gs(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function qs(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(let o=0;o<t.length;o++){const i=t[o],a=s+i;if(e.measureText(a).width>n&&s){if(Gs(i.charCodeAt(0))&&s.length>0&&Gs(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!Gs(s.charCodeAt(t))){e=t;break}e>=0?(r.push(s.substring(0,e+1)),s=s.substring(e+1)+i):(r.push(s),s=i)}else r.push(s),s=i}else s=a}s&&r.push(s)}return r.length>0?r:[""]}function Js(e){let t=1;for(;t<e;)t*=2;return t}function Ks(e,t){let n=0,s=t;for(;e.has(s,Le);){const t=e.get(s,Le).entity;if(!e.valid(t))break;n++,s=t}return n}function Qs(e){return e._computedWidth??e.size.x}function Zs(e){return e._computedHeight??e.size.y}function er(e,t,n,s,r,o){if(!e.has(t,$e))return;const i=e.get(t,$e);let a,l;switch(n){case Ds.BottomToTop:case Ds.TopToBottom:a=r,l=o*s;break;default:a=r*s,l=o}i.size.x===a&&i.size.y===l||(i.size.x=a,i.size.y=l,e.insert(t,$e,i))}function tr(e,t,n){let s=t;for(;e.has(s,Le);){const t=e.get(s,Le).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function nr(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function sr(e,t,n,s,r){if(!e.has(t,Os))return;const o=e.get(t,Os),i=Ls(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,n,o.pivot),a=i.rect.right-i.rect.left,l=i.rect.top-i.rect.bottom;if(o._computedWidth=a,o._computedHeight=l,e.has(t,$e)){const n=e.get(t,$e);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,$e,n))}if(!o._layoutManaged&&e.has(t,Be)){const n=e.get(t,Be);n.position.x=i.originX-s,n.position.y=i.originY-r,e.insert(t,Be,n)}}function rr(e){const t=Object.keys(e),n=t.map(t=>e[t]);return{take(e){const s={};for(let r=0;r<t.length;r++)s[t[r]]=n[r](e);return s},changed(e,s){for(let r=0;r<t.length;r++)if(e[t[r]]!==n[r](s))return!0;return!1},update(e,s){for(let r=0;r<t.length;r++)e[t[r]]=n[r](s)}}}const or={r:.3,g:.5,b:.8,a:1},ir={Left:0,Center:1,Right:2},ar={Top:0,Middle:1,Bottom:2},lr={Visible:0,Clip:1,Ellipsis:2},cr=xe("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:ir.Left,verticalAlign:ar.Top,wordWrap:!0,overflow:lr.Visible,lineHeight:1.2});class ur{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(re.textCanvasSize,re.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,Js(this.frameMaxW_)),e.height=Math.max(e.height,Js(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Js(this.frameMaxW_),e.height=Js(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const 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=qs(n,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=r?Math.ceil(o):h+2*u,p=r?Math.ceil(i):d+2*u;if(r&&e.overflow===lr.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)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,Js(f)),s.height=Math.max(s.height,Js(p)));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===lr.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 ar.Top:x=u;break;case ar.Middle:x=u+(p-2*u-w)/2;break;case ar.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of l){let s;switch(e.align){case ir.Left:s=u;break;case ir.Center:s=f/2;break;case ir.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=c}r&&e.overflow===lr.Clip&&n.restore();const b=n.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),M=this.module.getResourceManager(),P=this.module._malloc(S.length);this.module.HEAPU8.set(S,P);const E=M.createTexture(f,p,P,S.length,1,!0);return this.module._free(P),{textureHandle:E,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()}measureWidth(e){let t=0;for(const n of e)t=Math.max(t,this.ctx.measureText(n).width);return t}mapAlign(e){switch(e){case ir.Left:return"left";case ir.Center:return"center";case ir.Right:return"right"}}}const hr=rr({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?Qs(e.uiRect):0,containerHeight:e=>e.uiRect?Zs(e.uiRect):0});class dr{build(e){Ce("Text",cr);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new ur(t),s=e.world,r=new Map;e.addSystemToSchedule(dt.PreUpdate,pt([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,cr));for(const e of r.keys())if(!s.valid(e)||!s.has(e,cr)){if(s.valid(e)&&s.has(e,$e)){const t=s.get(e,$e);t.texture=ae,s.insert(e,$e,t)}r.delete(e)}const e=s.getEntitiesWithComponents([cr]);for(const t of e){const e=s.get(t,cr),o=s.has(t,Os)?s.get(t,Os):null,i={text:e,uiRect:o},a=r.get(t);if(a&&!hr.changed(a,i))continue;Hs(s,t);const l=n.renderForEntity(t,e,o),c=s.get(t,$e);c.texture=l.textureHandle,c.size.x=l.width,c.size.y=l.height,c.uvOffset.x=0,c.uvOffset.y=0,c.uvScale.x=1,c.uvScale.y=1,s.insert(t,$e,c),r.set(t,hr.take(i))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const fr=new dr,pr=xe("UIMask",{enabled:!0,mode:"scissor"});function gr(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 yr(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],h=e[8],d=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*u-i*a,b=r*c-o*l,S=r*u-i*l,M=o*u-i*c,P=h*y-d*g,E=h*m-f*g,T=h*_-p*g,C=d*m-f*y,R=d*_-p*y,A=f*_-p*m;let I=w*A-x*R+v*C+b*T-S*E+M*P;return 0===I||(I=1/I,n[0]=(l*A-c*R+u*C)*I,n[1]=(o*R-r*A-i*C)*I,n[2]=(y*M-m*S+_*b)*I,n[3]=(f*S-d*M-p*b)*I,n[4]=(c*T-a*A-u*E)*I,n[5]=(s*A-o*T+i*E)*I,n[6]=(m*v-g*M-_*x)*I,n[7]=(h*M-f*v+p*x)*I,n[8]=(a*R-l*T+u*P)*I,n[9]=(r*T-s*R-i*P)*I,n[10]=(g*S-y*v+_*w)*I,n[11]=(d*v-h*S-p*w)*I,n[12]=(l*E-a*C-c*P)*I,n[13]=(s*C-r*E+o*P)*I,n[14]=(y*x-g*b-m*w)*I,n[15]=(h*b-d*x+f*w)*I),n}function mr(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:u/h}}function _r(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 wr(e,t){return 2*Math.atan2(e,t)}function xr(e,t,n,s,r,o,i){const a=n[0]*e+n[4]*t+n[12],l=n[1]*e+n[5]*t+n[13],c=n[3]*e+n[7]*t+n[15];return[s+(.5*(a/c)+.5)*o,r+(.5*(l/c)+.5)*i]}function vr(e,t,n,s,r,o,i,a,l,c){const u=wr(l,c),h=Math.sin(-u),d=Math.cos(-u),f=e-n,p=t-s,g=f*d-p*h+n,y=f*h+p*d+s;return g>=n-r*i&&g<=n+r*(1-i)&&y>=s-o*a&&y<=s+o*(1-a)}function br(e,t,n,s,r,o,i){if(!e.has(t,Os)||!e.has(t,We))return null;const a=e.get(t,Os),l=e.get(t,We),c=Qs(a)*l.scale.x,u=Zs(a)*l.scale.y,h=l.position.x,d=l.position.y,f=a.pivot.x,p=a.pivot.y,g=-c*f,y=c*(1-f),m=-u*p,_=u*(1-p),w=wr(l.rotation.z,l.rotation.w),x=Math.cos(w),v=Math.sin(w),b=[[h+g*x-m*v,d+g*v+m*x],[h+y*x-m*v,d+y*v+m*x],[h+y*x-_*v,d+y*v+_*x],[h+g*x-_*v,d+g*v+_*x]];let S=1/0,M=1/0,P=-1/0,E=-1/0;for(const[e,t]of b){const[a,l]=xr(e,t,n,s,r,o,i);S=Math.min(S,a),M=Math.min(M,l),P=Math.max(P,a),E=Math.max(E,l)}return{x:Math.round(S),y:Math.round(M),w:Math.round(P-S),h:Math.round(E-M)}}function Sr(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([pr]);if(0===l.length)return;const c=[],u=[],h=new Set,d=new Set;for(const e of l){const n=t.get(e,pr);n.enabled&&(h.add(e),"stencil"===n.mode?(u.push(e),d.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,r,o,i,a,l,c){const u=[];for(const e of s){let n=!0;tr(t,e,e=>{if(r.has(e)){if("scissor"===t.get(e,pr).mode)return n=!1,!0}return!1}),n&&u.push(e)}function h(s,u){const d=e.getChildEntities(n,s);for(const n of d){let s=u;if(r.has(n)){if("scissor"===t.get(n,pr).mode){const e=br(t,n,o,i,a,l,c);e&&(s=gr(u,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of u){const n=br(t,e,o,i,a,l,c);n&&h(e,n)}}(e,t,n,c,h,s,r,o,i,a),u.length>0&&function(e,t,n,s,r){e.renderer_clearStencil();const o=[];for(const e of s){let n=!0;tr(t,e,e=>!!r.has(e)&&(n=!1,!0)),n&&o.push(e)}let i=1,a=!1;function l(){return i>255?(a||console.warn("Stencil mask overflow"),a=!0,null):i++}function c(t,s){if(a)return;e.renderer_setEntityStencilMask(t,s);const o=e.getChildEntities(n,t);for(const t of o)if(r.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),u(t,s)}function u(t,s){if(a)return;const o=e.getChildEntities(n,t);for(const t of o)if(r.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),u(t,s)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,n,u,d)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class Mr{build(e){if(Ce("UIMask",pr),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Sr(e.wasmModule,e.world))}}const Pr=new Mr,Er=xe("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),Tr=xe("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Cr={Normal:0,Hovered:1,Pressed:2,Disabled:3},Rr=xe("Button",{state:Cr.Normal,transition:null});class Ar{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 Ir=Ze(new Ar,"UIEvents"),Fr=ve("ScreenSpace"),kr=rr({anchorMinX:e=>e.anchorMin.x,anchorMinY:e=>e.anchorMin.y,anchorMaxX:e=>e.anchorMax.x,anchorMaxY:e=>e.anchorMax.y,offsetMinX:e=>e.offsetMin.x,offsetMinY:e=>e.offsetMin.y,offsetMaxX:e=>e.offsetMax.x,offsetMaxY:e=>e.offsetMax.y,sizeX:e=>e.size.x,sizeY:e=>e.size.y});function Br(e,t,n,s,r,o){if(!e.has(t,Os))return;const i=e.get(t,Os),a=Ls(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n,i.pivot),l=a.rect.right-a.rect.left,c=a.rect.top-a.rect.bottom;if(i._computedWidth=l,i._computedHeight=c,e.has(t,$e)){const n=e.get(t,$e);n.size.x===l&&n.size.y===c||(n.size.x=l,n.size.y=c,e.insert(t,$e,n))}if(!i._layoutManaged){const n=e.get(t,Be);o?(n.position.x=a.originX,n.position.y=a.originY):(n.position.x=a.originX-s,n.position.y=a.originY-r),e.insert(t,Be,n)}if(!e.has(t,Oe))return;const u=e.get(t,Oe);if(u&&u.entities)for(const t of u.entities)e.valid(t)&&Br(e,t,a.rect,a.originX,a.originY,!1)}class Wr{build(e){Ce("UIRect",Os);const t=e.world,n=new Map,s=new Map;let r=NaN,o=NaN,i=NaN,a=NaN;function l(e){let n=s.get(e);return void 0!==n||(n=function(e,t){let n=t;for(;;){if(e.has(n,Fr))return n;if(!e.has(n,Le))return null;const t=e.get(n,Le);if(!e.valid(t.entity))return null;n=t.entity}}(t,e),s.set(e,n)),n}function c(e){if(s.delete(e),!t.has(e,Oe))return;const n=t.get(e,Oe);if(n&&n.entities)for(const e of n.entities)t.valid(e)&&c(e)}e.addSystemToSchedule(dt.PreUpdate,pt([et(Ft)],e=>{if(!e.valid)return;const u={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},h=.5*(u.left+u.right),d=.5*(u.bottom+u.top),f=r!==e.worldLeft||o!==e.worldBottom||i!==e.worldRight||a!==e.worldTop;r=e.worldLeft,o=e.worldBottom,i=e.worldRight,a=e.worldTop;const p=new Set;if(f){s.clear();const e=t.getEntitiesWithComponents([Fr,Os,Be]);for(const t of e)p.add(t)}for(const e of n.keys())t.valid(e)&&t.has(e,Os)||(n.delete(e),s.delete(e));const g=t.getEntitiesWithComponents([Os]);for(const e of g){const s=t.get(e,Os),r=n.get(e);if(s._dirty||!r||kr.changed(r,s)){s._dirty=!1,c(e);const t=l(e);null!==t&&p.add(t)}}for(const e of p)Br(t,e,u,h,d,!0);for(const e of g){const s=t.get(e,Os),r=n.get(e);r?kr.update(r,s):n.set(e,kr.take(s))}},{name:"UILayoutSystem"}))}}const $r=new Wr,zr=function(){const e=new Float32Array(16),t=new Float32Array(16);let n=!0;return{update(e){for(let s=0;s<16;s++)if(t[s]!==e[s]){t.set(e),n=!0;break}},getInverse:t=>(n&&(yr(t,e),n=!1),e)}}();function Ur(e,t,n,s){let r=!1;return tr(e,t,t=>{if(!e.has(t,pr))return!1;if(!e.get(t,pr).enabled||!e.has(t,Os)||!e.has(t,We))return!1;const o=e.get(t,We),i=e.get(t,Os),a=Qs(i)*o.scale.x,l=Zs(i)*o.scale.y;return!vr(n,s,o.position.x,o.position.y,a,l,i.pivot.x,i.pivot.y,o.rotation.z,o.rotation.w)&&(r=!0,!0)}),r}function Dr(e,t,n,s){t.emit(n,s,n),tr(e,n,r=>{if(!e.has(r,Er))return!1;const o=e.get(r,Er);return o.enabled&&t.emit(r,s,n),o.blockRaycast})}class Lr{build(e){Ce("Interactable",Er),Ce("Button",Rr);const t=e.world,n=new Ar;e.insertResource(Ir,n);let s=null,r=null;e.addSystemToSchedule(dt.PreUpdate,pt([et(vt),et(Ft)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([Tr]);for(const e of i){const n=t.get(e,Tr);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a=f(),l=e.mouseX*a,c=o.screenH-e.mouseY*a;zr.update(o.viewProjection);const u=mr(l,c,zr.getInverse(o.viewProjection),o.vpX,o.vpY,o.vpW,o.vpH);o.worldMouseX=u.x,o.worldMouseY=u.y;const h=t.getEntitiesWithComponents([Er,Os,We]);let d=null,p=-1/0;for(const e of h){nr(t,e,Tr);const n=t.get(e,Er);if(!n.enabled)continue;if(!n.raycastTarget)continue;const s=t.get(e,We),r=t.get(e,Os),o=Qs(r)*s.scale.x,i=Zs(r)*s.scale.y;if(vr(u.x,u.y,s.position.x,s.position.y,o,i,r.pivot.x,r.pivot.y,s.rotation.z,s.rotation.w)){if(Ur(t,e,u.x,u.y))continue;let n=0;t.has(e,$e)&&(n=t.get(e,$e).layer),n>p&&(p=n,d=e)}}if(null===s||t.valid(s)||(s=null),s!==d){if(null!==s&&t.valid(s)&&t.has(s,Tr)){t.get(s,Tr).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,Tr).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,Tr);e.pressed=!0,e.justPressed=!0,r=d,Dr(t,n,d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Tr)){const e=t.get(r,Tr);e.pressed=!1,e.justReleased=!0,Dr(t,n,r,"release"),r===s&&Dr(t,n,r,"click")}r=null}},{name:"UIInteractionSystem"}));const o=new Set;e.addSystemToSchedule(dt.Update,pt([],()=>{const e=t.getEntitiesWithComponents([Rr]);for(const n of e){if(nr(t,n,Er,{enabled:!0}),!t.has(n,Tr))continue;const e=t.get(n,Tr),s=t.get(n,Rr),r=t.get(n,Er),i=!o.has(n),a=s.state;if(r.enabled?e.pressed?s.state=Cr.Pressed:e.hovered?s.state=Cr.Hovered:s.state=Cr.Normal:s.state=Cr.Disabled,i&&o.add(n),(i||a!==s.state)&&s.transition&&t.has(n,$e)){const o=t.get(n,$e);o.color=Vs(s.transition,r.enabled,e.pressed,e.hovered),t.insert(n,$e,o)}}},{name:"ButtonSystem"}))}}const Or=new Lr,Hr=xe("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}),jr=xe("Focusable",{tabIndex:0,isFocused:!1});class Xr{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 Yr=Ze(new Xr,"FocusManager");class Nr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){Ce("TextInput",Hr);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=h(re.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let i=!1,a=!0,l=0,c=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 d=u;function f(){const t=e.getResource(Yr);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,Hr)?s:null}const p=()=>{i||null===f()||w()},g=()=>{i=!0},y=()=>{i=!1,w()},m=t=>{const s=f();if(null===s)return;if("Escape"===t.key)return void x();const r=n.get(s,Hr);if("Enter"===t.key&&!r.multiline){t.preventDefault();return e.getResource(Ir).emit(s,"submit"),void x()}let o=r.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,r.cursorPos-1):"ArrowRight"===t.key?o=Math.min(r.value.length,r.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=r.value.length),o!==r.cursorPos&&(r.cursorPos=o,d.selectionStart=o,d.selectionEnd=o,r.dirty=!0,v())},_=()=>{const t=f();if(null!==t){const s=n.get(t,Hr);s.focused=!1,s.dirty=!0;e.getResource(Yr).blur()}};function w(){const t=f();if(null===t)return;const s=n.get(t,Hr);if(s.readOnly)return;let r=d.value;if(s.maxLength>0&&r.length>s.maxLength&&(r=r.substring(0,s.maxLength),d.value=r),r!==s.value){s.value=r;e.getResource(Ir).emit(t,"change")}s.cursorPos=d.selectionStart??r.length,s.dirty=!0,v()}function x(){const t=f();if(null!==t){const e=n.get(t,Hr);e.focused=!1,e.dirty=!0}e.getResource(Yr).blur(),d.blur()}function v(){a=!0,l=0}d.addEventListener("input",p),d.addEventListener("compositionstart",g),d.addEventListener("compositionend",y),d.addEventListener("keydown",m),d.addEventListener("blur",_),this.cleanupListeners_=()=>{d.removeEventListener("input",p),d.removeEventListener("compositionstart",g),d.removeEventListener("compositionend",y),d.removeEventListener("keydown",m),d.removeEventListener("blur",_),d.remove();const e=t.getResourceManager();for(const t of s.values())e.releaseTexture(t);s.clear()};let b=null;function S(e,i,l,c){(r.width<l||r.height<c)&&(r.width=Js(Math.max(r.width,l)),r.height=Js(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,l,c),o.save(),o.beginPath(),o.rect(i.padding,0,l-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const h=0===i.value.length,d=h?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=h?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=qs(o,d,l-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&&a){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=qs(o,i.value,l-2*g);let r=0,a=0,c=0;for(let t=0;t<e.length;t++){const n=e[t].length;if(r+n>=i.cursorPos){a=t,c=i.cursorPos-r;break}r+=n,t<e.length-1&&r<i.value.length&&"\n"===i.value[r]&&r++,a=t+1,c=0}const u=a<e.length?e[a].substring(0,c):"";t=g+o.measureText(u).width,n=g+a*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,l,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(l,c,w,m.length,1,!0);s.set(e,v),t._free(w);const b=n.get(e,$e);b.texture=v,b.size.x=l,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,$e,b)}e.addSystemToSchedule(dt.Update,pt([et(Yr)],e=>{const t=n.getEntitiesWithComponents([Hr]);for(const e of t)nr(n,e,jr,{tabIndex:0,isFocused:!1}),nr(n,e,Er,{enabled:!0,blockRaycast:!0});const s=f();if(s!==b){if(null!==b&&n.valid(b)&&n.has(b,Hr)){const e=n.get(b,Hr);e.focused=!1,e.dirty=!0,d.blur()}null!==s&&function(e){const t=n.get(e,Hr);t.readOnly||(t.focused=!0,t.dirty=!0,d.value=t.value,d.selectionStart=t.cursorPos,d.selectionEnd=t.cursorPos,d.focus(),v())}(s),b=s}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(dt.PreUpdate,pt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let r=0===c?0:(e-c)/1e3;c=e,r=Math.min(r,.1);const o=f();if(null!==o&&(l+=r,l>=.5)){l-=.5,a=!a;n.get(o,Hr).dirty=!0}const i=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Hr)||(i.releaseTexture(t),s.delete(e));const u=n.getEntitiesWithComponents([Hr,Os]);for(const e of u){const t=n.get(e,Hr);if(!t.dirty)continue;const s=n.get(e,Os),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(Hs(n,e),S(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Vr=new Nr,Gr={Simple:0,Sliced:1,Tiled:2,Filled:3},qr={Horizontal:0,Vertical:1},Jr={Left:0,Right:1,Bottom:2,Top:3},Kr=xe("Image",{texture:ae,color:{r:1,g:1,b:1,a:1},imageType:Gr.Simple,fillMethod:qr.Horizontal,fillOrigin:Jr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Qr=rr({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,layer:e=>e.image.layer,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?Qs(e.uiRect):0,rectHeight:e=>e.uiRect?Zs(e.uiRect):0,enabled:e=>e.image.enabled});const Zr=new class{build(e){Ce("Image",Kr);const t=e.world,n=new Map;e.addSystemToSchedule(dt.PreUpdate,pt([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,Kr)||n.delete(e);const e=t.getEntitiesWithComponents([Kr]);for(const s of e){const e=t.get(s,Kr),r=t.has(s,Os)?t.get(s,Os):null,o={image:e,uiRect:r},i=n.get(s);if(i&&!Qr.changed(i,o))continue;Hs(t,s);const a=t.get(s,$e);if(e.enabled){if(a.texture=e.texture,a.color.r=e.color.r,a.color.g=e.color.g,a.color.b=e.color.b,a.color.a=e.color.a,a.layer=e.layer,a.material=e.material,r&&(a.size.x=Qs(r),a.size.y=Zs(r)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Gr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===qr.Horizontal?e.fillOrigin===Jr.Left?(a.uvScale.x=t,a.size.x=n*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=n*t):e.fillOrigin===Jr.Bottom?(a.uvScale.y=t,a.size.y=s*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=s*t)}else e.imageType===Gr.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale.x=a.size.x/e.tileSize.x,a.uvScale.y=a.size.y/e.tileSize.y);t.insert(s,$e,a),n.set(s,Qr.take(o))}else a.color.a=0,t.insert(s,$e,a),n.set(s,Qr.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},eo=xe("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),to=xe("ToggleGroup",{allowSwitchOff:!1});const no=new class{build(e){Ce("Toggle",eo),Ce("ToggleGroup",to);const t=e.world,n=new Set;e.addSystemToSchedule(dt.Update,pt([et(Ir)],e=>{const s=t.getEntitiesWithComponents([eo]),r=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,eo);s.isOn&&0!==s.group&&t.valid(s.group)&&(r.has(s.group)?s.isOn=!1:r.set(s.group,e))}const o=new Map;for(const e of s){const n=t.get(e,eo);if(0!==n.group&&t.valid(n.group)){let t=o.get(n.group);t||(t=[],o.set(n.group,t)),t.push(e)}}for(const n of s){if(nr(t,n,Er,{enabled:!0}),!t.has(n,Tr))continue;const s=t.get(n,Tr),r=t.get(n,eo),i=t.get(n,Er);if(s.justPressed&&i.enabled){const s=r.group,i=0!==s&&t.valid(s)&&t.has(s,to);if(r.isOn&&i){if(!t.get(s,to).allowSwitchOff)continue}if(r.isOn=!r.isOn,r.isOn&&i){const r=o.get(s);if(r)for(const s of r){if(s===n)continue;const r=t.get(s,eo);r.isOn&&(r.isOn=!1,e.emit(s,"change"))}}e.emit(n,"change")}if(r.graphicEntity&&t.valid(r.graphicEntity)&&t.has(r.graphicEntity,$e)){const e=t.get(r.graphicEntity,$e);e.enabled=r.isOn,t.insert(r.graphicEntity,$e,e)}if(r.transition&&t.has(n,$e)){const e=t.get(n,$e);e.color=Vs(r.transition,i.enabled,s.pressed,s.hovered),t.insert(n,$e,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},so=Ds,ro=xe("ProgressBar",{value:0,fillEntity:0,direction:Ds.LeftToRight});const oo=new class{build(e){Ce("ProgressBar",ro);const t=e.world;e.addSystemToSchedule(dt.PreUpdate,pt([],()=>{const e=t.getEntitiesWithComponents([ro,Os]);for(const n of e){const e=t.get(n,ro);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=Math.max(0,Math.min(1,e.value));Ns(t,e.fillEntity,e.direction,s)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}},io=xe("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),ao=xe("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}});const lo=new class{build(e){Ce("Draggable",io),Ce("DragState",ao);const t=e.world,n=e.getResource(Ir);let s=null,r={x:0,y:0},o=null;e.addSystemToSchedule(dt.PreUpdate,pt([et(vt),et(Ft)],(e,i)=>{if(!i.valid)return;const a={x:i.worldMouseX,y:i.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([io,Tr]);let n=null,o=-1/0,i=-1;for(const s of e){if(!t.get(s,io).enabled)continue;if(t.get(s,Tr).hovered){let e=0;t.has(s,$e)&&(e=t.get(s,$e).layer);const r=Ks(t,s);(e>o||e===o&&r>=i)&&(o=e,i=r,n=s)}}if(null!==n){s=n,r={x:a.x,y:a.y},t.has(n,ao)||t.insert(n,ao);const e=t.get(n,ao),o=t.get(n,We);e.startWorldPos={x:o.position.x,y:o.position.y},e.currentWorldPos={x:o.position.x,y:o.position.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,ao)){t.get(s,ao).isDragging=!1}s=null}if(null!==s&&null===o){if(!t.valid(s))return void(s=null);const e=a.x-r.x,l=a.y-r.y,c=Math.sqrt(e*e+l*l),u=t.get(s,io);if(c*(i.vpW/(i.worldRight-i.worldLeft))>=u.dragThreshold){o=s,s=null;t.get(o,ao).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,ao))return void(o=null);const s=t.get(o,ao),r=t.get(o,io),i=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+i,u=s.startWorldPos.y+l;const h=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,u);c=h.x,u=h.y;const d=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-d,y:u-f},s.currentWorldPos={x:c,y:u},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:u-s.startWorldPos.y},t.has(o,Be)){const e=function(e,t,n,s){if(!e.has(t,Le))return{x:n,y:s};const r=e.get(t,Le).entity;if(!e.valid(r)||!e.has(r,We))return{x:n,y:s};const o=e.get(r,We),i=0!==o.scale.x?o.scale.x:1,a=0!==o.scale.y?o.scale.y:1,l=wr(o.rotation.z,o.rotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(n*u-s*c)/i,y:(n*c+s*u)/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"}))}},co=xe("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135});const uo=new class{build(e){Ce("ScrollView",co);const t=e.world,n=new Map;let s=0;e.addSystemToSchedule(dt.PreUpdate,pt([et(vt),et(Ft)],(e,r)=>{const o=performance.now()/1e3,i=s>0?Math.min(o-s,.05):0;if(s=o,!r.valid)return;for(const[e]of n)t.valid(e)||n.delete(e);const a={x:r.worldMouseX,y:r.worldMouseY},l=t.getEntitiesWithComponents([co,Os]);for(const s of l){nr(t,s,Er,{enabled:!0,blockRaycast:!0}),nr(t,s,pr,{enabled:!0,mode:"scissor"});const r=t.get(s,co),o=t.get(s,Os);let l=n.get(s);l||(l={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0},n.set(s,l));const c=t.has(s,Tr)?t.get(s,Tr):null;if(c?.justPressed&&(l.isDragging=!0,l.lastWorldX=a.x,l.lastWorldY=a.y,l.velocityX=0,l.velocityY=0),l.isDragging&&e.isMouseButtonDown(0)){const e=a.x-l.lastWorldX,t=a.y-l.lastWorldY;if(r.horizontalEnabled){r.scrollX-=e;const t=i>0?-e/i:0;l.velocityX=.8*l.velocityX+.2*t}if(r.verticalEnabled){r.scrollY-=t;const e=i>0?-t/i:0;l.velocityY=.8*l.velocityY+.2*e}l.lastWorldX=a.x,l.lastWorldY=a.y}if(l.isDragging&&e.isMouseButtonReleased(0)&&(l.isDragging=!1),c?.hovered){const t=e.getScrollDelta();r.verticalEnabled&&0!==t.y&&(r.scrollY+=.1*t.y,l.velocityY=0),r.horizontalEnabled&&0!==t.x&&(r.scrollX+=.1*t.x,l.velocityX=0)}if(!l.isDragging&&r.inertia&&i>0){const e=Math.pow(r.decelerationRate,60*i);r.horizontalEnabled&&Math.abs(l.velocityX)>.1?(r.scrollX+=l.velocityX*i,l.velocityX*=e):l.velocityX=0,r.verticalEnabled&&Math.abs(l.velocityY)>.1?(r.scrollY+=l.velocityY*i,l.velocityY*=e):l.velocityY=0}const u=Qs(o),h=Zs(o),d=Math.max(0,r.contentWidth-u),f=Math.max(0,r.contentHeight-h),p=r.scrollX,g=r.scrollY;if(r.scrollX=Math.max(0,Math.min(r.scrollX,d)),r.scrollY=Math.max(0,Math.min(r.scrollY,f)),r.scrollX!==p&&(l.velocityX=0),r.scrollY!==g&&(l.velocityY=0),0!==r.contentEntity&&t.valid(r.contentEntity)&&t.has(r.contentEntity,Be)){const e=t.get(r.contentEntity,Be);e.position.x=-r.scrollX,e.position.y=r.scrollY,t.insert(r.contentEntity,Be,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UIInteractionSystem"]})}},ho=Ds,fo=xe("Slider",{value:0,minValue:0,maxValue:1,direction:Ds.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});const po=new class{build(e){Ce("Slider",fo);const t=e.world;let n=null;e.addSystemToSchedule(dt.PreUpdate,pt([et(vt),et(Ft),et(Ir)],(e,s,r)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const o=s.worldMouseX,i=s.worldMouseY,a=t.getEntitiesWithComponents([fo,Os,We]);for(const s of a){nr(t,s,Er,{enabled:!0,blockRaycast:!0});const a=t.get(s,fo),l=t.get(s,Os),c=t.get(s,We),u=t.has(s,Tr)?t.get(s,Tr):null,h=a.handleEntity;if(0!==h&&t.valid(h)&&(nr(t,h,Er,{enabled:!0,blockRaycast:!1}),t.has(h,Er))){const e=t.get(h,Er);e.blockRaycast&&(e.blockRaycast=!1,t.insert(h,Er,e))}let d=u?.justPressed??!1;if(!d&&0!==h&&t.valid(h)&&t.has(h,Tr)){d=t.get(h,Tr).justPressed}if(d&&(n=s),n===s&&e.isMouseButtonDown(0)){const e=Qs(l),n=Zs(l),u=e*c.scale.x,h=n*c.scale.y,d=wr(c.rotation.z,c.rotation.w),f=Math.sin(-d),p=Math.cos(-d),g=o-c.position.x,y=i-c.position.y,m=g*p-y*f,_=g*f+y*p,w=-l.pivot.x*u,x=-l.pivot.y*h;let v;switch(a.direction){case Ds.LeftToRight:v=u>0?(m-w)/u:0;break;case Ds.RightToLeft:v=u>0?1-(m-w)/u:0;break;case Ds.BottomToTop:v=h>0?(_-x)/h:0;break;case Ds.TopToBottom:v=h>0?1-(_-x)/h:0}v=Math.max(0,Math.min(1,v));let b=a.minValue+v*(a.maxValue-a.minValue);a.wholeNumbers&&(b=Math.round(b));const S=a.value;a.value=Math.max(a.minValue,Math.min(a.maxValue,b)),t.insert(s,fo,a),a.value!==S&&r.emit(s,"change")}n===s&&e.isMouseButtonReleased(0)&&(n=null);const f=a.maxValue-a.minValue,p=f>0?(a.value-a.minValue)/f:0,g=Qs(l),y=Zs(l),m=l.pivot,_={left:-m.x*g,bottom:-m.y*y,right:(1-m.x)*g,top:(1-m.y)*y};if(0!==a.fillEntity&&t.valid(a.fillEntity)&&(Ns(t,a.fillEntity,a.direction,p),sr(t,a.fillEntity,_,0,0)),0!==a.handleEntity&&t.valid(a.handleEntity)){if(t.has(a.handleEntity,Os)){const e=t.get(a.handleEntity,Os);switch(e.offsetMin={x:0,y:0},e.offsetMax={x:0,y:0},a.direction){case Ds.LeftToRight:e.anchorMin={x:p,y:0},e.anchorMax={x:p,y:1};break;case Ds.RightToLeft:e.anchorMin={x:1-p,y:0},e.anchorMax={x:1-p,y:1};break;case Ds.BottomToTop:e.anchorMin={x:0,y:p},e.anchorMax={x:1,y:p};break;case Ds.TopToBottom:e.anchorMin={x:0,y:1-p},e.anchorMax={x:1,y:1-p}}t.insert(a.handleEntity,Os,e)}sr(t,a.handleEntity,_,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}};const go=new class{build(e){Ce("Focusable",jr);const t=e.world,n=new Xr;e.insertResource(Yr,n),e.addSystemToSchedule(dt.Update,pt([et(vt),et(Ir)],(e,s)=>{null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const r=t.getEntitiesWithComponents([jr]);for(const e of r){if(!t.has(e,Tr))continue;t.get(e,Tr).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of r){if(!t.valid(n))continue;if(t.has(n,Er)){if(!t.get(n,Er).enabled)continue}const s=t.get(n,jr);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,jr)){t.get(r,jr).isFocused=!1,s.emit(r,"blur",r)}n.focus(e);t.get(e,jr).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},yo=xe("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function mo(){return r()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:n,screenWidth:s,screenHeight:r}=t;return{top:n.top,bottom:r-n.bottom,left:n.left,right:s-n.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}const _o=new class{build(e){Ce("SafeArea",yo);const t=e.world;let n=mo(),s=!0,o=0,i=0;if(r()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=mo(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=mo(),s=!0});e.addSystemToSchedule(dt.PreUpdate,pt([et(Ft)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===i||(o=e.screenH,i=a,s=!0),!s)return;s=!1;const l=f(),c=r()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([yo,Os]);for(const e of u){const s=t.get(e,yo),r=t.get(e,Os),o=s.applyTop?n.top*c:0,i=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let u=!1;r.offsetMin.x===a&&r.offsetMin.y===i||(r.offsetMin={x:a,y:i},u=!0),r.offsetMax.x===-l&&r.offsetMax.y===-o||(r.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,Os,r)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},wo=xe("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let xo=null;function vo(e,t){if(!xo)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=xo.get(e);n?n.renderer=t:xo.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const bo=new class{build(e){Ce("ListView",wo);const t=e.world,n=new Map;xo=n,e.addSystemToSchedule(dt.PreUpdate,pt([et(vt)],e=>{for(const[e,s]of n)if(!t.valid(e)){for(const e of s.itemEntities.values())t.valid(e)&&t.despawn(e);n.delete(e)}const s=t.getEntitiesWithComponents([wo,Os]);for(const r of s){nr(t,r,Er,{enabled:!0,blockRaycast:!0}),nr(t,r,pr,{enabled:!0,mode:"scissor"});let s=n.get(r);s||(s={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(r,s));const o=t.get(r,wo),i=t.get(r,Os),a=i._computedHeight??i.size.y,l=i._computedWidth??i.size.x,c=t.has(r,Tr)?t.get(r,Tr):null;if(c?.hovered){const t=e.getScrollDelta();0!==t.y&&(o.scrollY+=.1*t.y)}const u=Math.max(0,o.itemCount*o.itemHeight-a);o.scrollY=Math.max(0,Math.min(o.scrollY,u));const h=Math.max(0,Math.floor(o.scrollY/o.itemHeight)-o.overscan),d=Math.min(o.itemCount,Math.ceil((o.scrollY+a)/o.itemHeight)+o.overscan);for(const[e,n]of s.itemEntities)(e<h||e>=d)&&(t.valid(n)&&t.despawn(n),s.itemEntities.delete(e));for(let e=h;e<d;e++){let n=s.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,Xe,{value:`ListItem_${e}`}),t.insert(n,Os,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:l,y:o.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,r),s.itemEntities.set(e,n),s.renderer&&s.renderer(e,n)),t.has(n,Be)){const s=t.get(n,Be);s.position.y=-(e*o.itemHeight-o.scrollY),t.insert(n,Be,s)}}s.visibleStart=h,s.visibleEnd=d}},{name:"ListViewSystem"}))}},So=xe("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const Mo=new class{build(e){Ce("Dropdown",So);const t=e.world,n=new Map;function s(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const r=n.listEntity;if(0===r||!t.valid(r))return;l(r,!0),t.has(r,pr)||t.insert(r,pr,{enabled:!0,mode:"scissor"}),a(s);const o=t.has(r,Os)?t.get(r,Os):null,i=o?o.size.x:160;for(let e=0;e<n.options.length;e++){const o=t.spawn();t.insert(o,Xe,{value:`Option_${e}`}),t.insert(o,Os,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:i,y:30},pivot:{x:.5,y:1}}),t.insert(o,Be,{position:{x:0,y:-30*e,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(o,cr,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:1,g:1,b:1,a:1},align:ir.Left,verticalAlign:ar.Middle,wordWrap:!1,overflow:lr.Clip,lineHeight:1.2}),t.insert(o,$e,{texture:0,color:{r:1,g:1,b:1,a:0},size:{x:i,y:30},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,Er,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,r),s.optionEntities.push(o)}o&&(o.size.y=30*n.options.length,t.insert(r,Os,o)),c(s)}function r(e,t,n){t.isOpen=!1,a(n),l(t.listEntity,!1)}function o(e,t,n,s,o){t.selectedIndex=s,r(0,t,n),o.emit(e,"change")}function i(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,cr))return;const s=t.get(n,cr),r=e.selectedIndex>=0&&e.selectedIndex<e.options.length?e.options[e.selectedIndex]:"";s.content!==r&&(s.content=r,t.insert(n,cr,s))}function a(e){for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[]}function l(e,n){if(0!==e&&t.valid(e)){if(t.has(e,Er)){const s=t.get(e,Er);s.enabled=n,t.insert(e,Er,s)}if(t.has(e,$e)){const s=t.get(e,$e);s.enabled=n,t.insert(e,$e,s)}}}function c(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s)||!t.has(s,$e))continue;const r=t.get(s,$e);n===e.highlightIndex?r.color={...or}:r.color={r:1,g:1,b:1,a:0},t.insert(s,$e,r)}}function u(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,Tr))continue;if(t.get(n,Tr).hovered)return!0}return!1}e.addSystemToSchedule(dt.Update,pt([et(vt),et(Ir)],(e,a)=>{for(const[e]of n)t.valid(e)||n.delete(e);const l=t.getEntitiesWithComponents([So]);for(const h of l){nr(t,h,Er,{enabled:!0,blockRaycast:!0});const l=t.get(h,So),d=t.has(h,Tr)?t.get(h,Tr):null;let f=n.get(h);if(f||(f={optionEntities:[],highlightIndex:-1},n.set(h,f)),d?.justPressed&&(l.isOpen?r(h,l,f):s(h,l,f)),l.isOpen){for(let e=0;e<f.optionEntities.length;e++){const n=f.optionEntities[e];if(!t.valid(n)||!t.has(n,Tr))continue;if(t.get(n,Tr).justPressed){o(h,l,f,e,a);break}}e.isKeyPressed("ArrowDown")?(f.highlightIndex>=l.options.length-1?f.highlightIndex=0:f.highlightIndex++,c(f)):e.isKeyPressed("ArrowUp")?(f.highlightIndex<=0?f.highlightIndex=l.options.length-1:f.highlightIndex--,c(f)):e.isKeyPressed("Enter")&&f.highlightIndex>=0?o(h,l,f,f.highlightIndex,a):e.isKeyPressed("Escape")&&r(h,l,f),e.isMouseButtonPressed(0)&&(d?.hovered||u(f)||r(h,l,f))}i(l)}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},Po=0,Eo=0,To=2,Co=xe("LayoutGroup",{direction:Po,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Eo,reverseOrder:!1});const Ro=new class{build(e){Ce("LayoutGroup",Co);const t=e.world;e.addSystemToSchedule(dt.PreUpdate,pt([],()=>{const e=t.getEntitiesWithComponents([Co,Os,Oe]);for(const n of e){const e=t.get(n,Co),s=t.get(n,Os),r=t.get(n,Oe);if(!r.entities||0===r.entities.length)continue;const o=[];for(const e of r.entities)t.valid(e)&&t.has(e,Os)&&t.has(e,Be)&&o.push({entity:e,rect:t.get(e,Os)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const i=s._computedWidth??s.size.x,a=s._computedHeight??s.size.y,l=s.pivot.x,c=s.pivot.y,u=e.padding,h=e.direction===Po;let d=0;for(let n=0;n<o.length;n++){const s=o[n],r=s.rect._computedWidth??s.rect.size.x,f=s.rect._computedHeight??s.rect.size.y,p=s.rect.pivot.x,g=s.rect.pivot.y;let y,m;h?(y=-l*i+u.left+d+p*r,m=e.childAlignment===Eo?(1-c)*a-u.top-(1-g)*f:e.childAlignment===To?-c*a+u.bottom+g*f:(.5-c)*a+.5*(u.bottom-u.top)+(g-.5)*f,d+=r,n<o.length-1&&(d+=e.spacing)):(y=e.childAlignment===Eo?-l*i+u.left+p*r:e.childAlignment===To?(1-l)*i-u.right-(1-p)*r:(.5-l)*i+.5*(u.left-u.right)+(p-.5)*r,m=(1-c)*a-u.top-d-(1-g)*f,d+=f,n<o.length-1&&(d+=e.spacing)),s.rect._layoutManaged=!0;const _=t.get(s.entity,Be);_.position.x=y,_.position.y=m,t.insert(s.entity,Be,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};function Ao(e,t,n){if(e.has(t,$e)&&e.has(t,Os)){const s=e.get(t,$e);s.layer!==n&&(s.layer=n,e.insert(t,$e,s)),n++}if(!e.has(t,Oe))return n;const s=e.get(t,Oe);if(!s||!s.entities)return n;for(const t of s.entities)e.valid(t)&&(n=Ao(e,t,n));return n}const Io=new class{build(e){const t=e.world;e.addSystemToSchedule(dt.PostUpdate,pt([],()=>{let e=0;const n=t.getEntitiesWithComponents([Fr,Os]);for(const s of n)e=Ao(t,s,e)},{name:"UIRenderOrderSystem"}))}};async function Fo(e,t,n){const s=e.getResource(bs);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function ko(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 Bo=Ze({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Wo=Ze(null,"PhysicsAPI");function $o(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function zo(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Uo{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(Bo,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=ko(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([Ue]);for(const n of t){const t=e.world.get(n,Ue);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(dt.PostUpdate,pt([et(rt)],a=>{const l=i.getEntitiesWithComponents([Ve,Be,We]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,Ve),l=i.get(r,We);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=$o(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),Do(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===Ke.Kinematic){const e=$o(l.rotation);s._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,Be);if(!u)continue;let h=a,d=l,f=c;if(e.world.has(i,Le)){const t=e.world.get(i,Le);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,We)){const n=e.world.get(t.entity,We),s=$o(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),u=Math.sin(-s);h=(r*i-o*u)/(0!==n.scale.x?n.scale.x:1),d=(r*u+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}u.position.x=h,u.position.y=d;const p=zo(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(i,Be,u)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Bo,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(Wo,Lo._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function Do(e,t,n){const s=e.world;if(s.has(n,Ge)){const e=s.get(n,Ge);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,qe)){const e=s.get(n,qe);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,Je)){const e=s.get(n,Je);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 Lo{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(Lo.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 Oo(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 Ho(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 jo(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,h=a+a,d=l+l,f=c+c,p=a*h,g=a*d,y=a*f,m=l*d,_=l*f,w=c*f,x=u*h,v=u*d,b=u*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 Xo(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){const r=nn(t.type);for(const o of r){if("texture"!==o.type)continue;const r=t.data[o.field];if("string"==typeof r&&r&&void 0===s[r])try{s[r]=Oo(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 u={},h=null;if(r&&(h=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),u=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){const i=sn(s.type);if(!i||!s.data)continue;const a=s.data[i.skeletonField],l=s.data[i.atlasField];if(!a||!l)continue;const c=r.resolvePath(a),u=r.resolvePath(l);try{const s=await r.readText(l),i="binary"===v(c)?.contentType;let h,d;if(i){const e=await r.readBinary(a);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=await r.readText(a),n=(new TextEncoder).encode(e);d=n.length,h=t._malloc(d+1),t.HEAPU8.set(n,h),t.HEAPU8[h+d]=0}const f=n.loadSkeleton(h,d,s,s.length,i);if(t._free(h),f<0)continue;o[a]=f;const p=Ho(s),g=u.substring(0,u.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=Oo(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,h,n,s)),o){const t={gravity:i?.gravity??{...te},fixedTimestep:i?.fixedTimestep??ne,subStepCount:i?.subStepCount??4};new Uo("",t,()=>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){const r=nn(t.type).find(e=>"font"===e.type);if(!r)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===s[o])try{let t,r;const i=v(o);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await n.readText(o)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await n.readText(l),r=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(o),r=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[o]=0;continue}const l=r?`${r}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=Oo(e,c,!1),h=e.getResourceManager();s[o]=h.loadBitmapFont(t,u,c.width,c.height)}catch{s[o]=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)continue;const r=nn(e.type).find(e=>"material"===e.type);if(!r)continue;const o=e.data[r.field];if("string"==typeof o&&o&&void 0===n[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){n[o]=0;continue}const r=e.vertexSource+e.fragmentSource;let i=s[r];i||(i=Ht.createShader(e.vertexSource,e.fragmentSource),s[r]=i),n[o]=Ht.createFromAsset(e,i)}catch{n[o]=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=nn(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=cn(e.world,n);if(l&&e.hasResource(bs))for(const t of p.values())e.world.insert(t,Ye,{scene:l,persistent:!1});if(r&&h){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){const i=sn(t.type);if(!i||!t.data)continue;const a=n[t.data[i.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=s.get(o.id);void 0!==c&&(r[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return r}(h,n,u,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=ee);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,je)?c.get(o,je):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&s.update(i,l*h);let d=0;if(c.has(o,We)){const e=jo(c.get(o,We),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),u=n._malloc(l),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,h,f);const p=n.HEAPU32[h>>2],g=n.HEAPU32[f>>2],y=new Float32Array(n.HEAPF32.buffer,c,8*r),m=new Uint16Array(n.HEAPU8.buffer,u,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,d),t._free(_),t._free(w),n._free(c),n._free(u),n._free(h),n._free(f)}d&&t._free(d)}})}(e,t,r,h,s)}if(a){const t=e.getResource(yn);t&&t.setAddressableManifest(a)}}function Yo(e,t,n){return{name:e,data:t,async setup(){await Xo(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class No{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)continue;const r=sn(e.type);if(r){const s=e.data[r.skeletonField],o=e.data[r.atlasField];s&&("binary"===v(s)?.contentType?n.add(s):t.add(s)),o&&t.add(o)}const o=nn(e.type);for(const n of o){const r=e.data[n.field];"string"==typeof r&&r&&("font"===n.type?(s.add(r),t.add(r)):"material"===n.type&&t.add(r))}}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=v(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 Vo="__preview__";class Go{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(bs);t.register({name:Vo,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Vo),this.loadPromise_=t.load(Vo).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 No(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.spineInitPromise;if(r){s=(await r).controller.raw}await Xo(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,Vo)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([ze]);for(const s of n){if(e.get(s,ze).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([Ue]);for(const r of s){const s=e.get(r,Ue);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(bs).getScene(Vo),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:Ie.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Fe.ColorAndDepth};e.insert(o,ze,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(bs);await e.switchTo(Vo),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 qo={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=ds.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:ds.getTargetTexture(n),width:e.width,height:e.height}},release(e){ds.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(ds.releaseRenderTarget(e._handle),qo.create({width:t,height:n,depth:!0})),begin(e,t){ds.begin(t,e._handle)},end(){ds.end()},getDepthTexture:e=>ds.getTargetDepthTexture(e._handle)};let Jo=!1;function Ko(e){Jo=e}function Qo(){return Jo}function Zo(){return!Jo}var ei;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(ei||(ei={}));class ti{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${ei[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case ei.Debug:console.debug(t,n);break;case ei.Info:console.log(t,n);break;case ei.Warn:console.warn(t,n);break;case ei.Error:console.error(t,n)}}}class ni{constructor(){this.handlers_=[],this.minLevel_=ei.Info,this.addHandler(new ti)}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(ei.Debug,e,t,n)}info(e,t,n){this.log(ei.Info,e,t,n)}warn(e,t,n){this.log(ei.Warn,e,t,n)}error(e,t,n){this.log(ei.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 si=new ni;function ri(){return si}function oi(e){si.setMinLevel(e)}function ii(e,t,n){si.debug(e,t,n)}function ai(e,t,n){si.info(e,t,n)}function li(e,t,n){si.warn(e,t,n)}function ci(e,t,n){si.error(e,t,n)}const ui=[fr,Pr,$r,Zr,oo,Or,lo,uo,po,no,Vr,go,_o,bo,Mo,Ro,Io];function hi(e,t){return function(e,t){const n=Es.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Bn(e),Dt(e),Kn(e),ns(e),us(e),ps(e);const r=new ms;n.setPipeline(r);let o=d();const i=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,r,o){o||(o=As(e,s,t,r));const i=n.getResource(Ft);if(o.length>0){const e=o[0],n=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(n.x*t),i.vpY=Math.round((1-n.y-n.h)*r),i.vpW=Math.round(n.w*t),i.vpH=Math.round(n.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}n.insertResource(Ft,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY: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;ds.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-o)/1e3;let h;if(ds.resize(t,l),os.isInitialized()&&os.getPassCount()>0&&!os.isBypassed()&&os.resize(t,l),n.hasResource(bs)){const e=n.getResource(bs).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const f=As(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)r.render({registry:{_cpp:s},viewProjection:Cs,width:t,height:l,elapsed:u});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:u})}ds.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(dt.First,l),n.addSystemToSchedule(dt.Last,c),n.addPlugin(_n),n.addPlugin(Cn),n.addPlugin(St),n.addPlugin(Ps),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:ui,...t})}j||(j=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await p(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 g(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=X;export{Es as App,mn as AssetPlugin,wn as AssetRefCounter,gn as AssetServer,yn as Assets,Kt as AsyncCache,He as BitmapText,kt as BlendMode,Ke as BodyType,Ge as BoxCollider,Rr as Button,Cr as ButtonState,ze as Camera,Ue as Canvas,Je as CapsuleCollider,Oe as Children,qe as CircleCollider,Fe as ClearFlags,ct as Commands,ht as CommandsInstance,N as DEFAULT_DESIGN_HEIGHT,Y as DEFAULT_DESIGN_WIDTH,ee as DEFAULT_FALLBACK_DT,ne as DEFAULT_FIXED_TIMESTEP,J as DEFAULT_FONT_FAMILY,K as DEFAULT_FONT_SIZE,te as DEFAULT_GRAVITY,Q as DEFAULT_LINE_HEIGHT,Z as DEFAULT_MAX_DELTA_TIME,V as DEFAULT_PIXELS_PER_UNIT,se as DEFAULT_SPINE_SKIN,q as DEFAULT_SPRITE_SIZE,G as DEFAULT_TEXT_CANVAS_SIZE,Nn as DataType,ao as DragState,io as Draggable,Un as Draw,So as Dropdown,ut as EntityCommands,Ds as FillDirection,qr as FillMethod,Jr as FillOrigin,Yr as FocusManager,Xr as FocusManagerState,jr as Focusable,ys as GLDebug,es as Geometry,ie as INVALID_ENTITY,le as INVALID_FONT,ce as INVALID_MATERIAL,ae as INVALID_TEXTURE,Kr as Image,Gr as ImageType,vt as Input,bt as InputPlugin,xt as InputState,Er as Interactable,wo as ListView,Be as LocalTransform,ei as LogLevel,ni as Logger,Ht as Material,Qt as MaterialLoader,ot as Mut,Xe as Name,Le as Parent,Lo as Physics,Bo as PhysicsEvents,Uo as PhysicsPlugin,os as PostProcess,Pn as PrefabServer,En as Prefabs,Tn as PrefabsPlugin,Go as PreviewPlugin,ro as ProgressBar,so as ProgressBarDirection,Ie as ProjectionType,at as Query,lt as QueryInstance,ms as RenderPipeline,as as RenderStage,qo as RenderTexture,ds as Renderer,et as Res,tt as ResMut,Ve as RigidBody,re as RuntimeConfig,yo as SafeArea,ke as ScaleMode,bs as SceneManager,vs as SceneManagerState,Ye as SceneOwner,dt as Schedule,Fr as ScreenSpace,co as ScrollView,Jt as ShaderSources,fo as Slider,ho as SliderDirection,je as SpineAnimation,$e as Sprite,wt as SystemRunner,cr as Text,ir as TextAlign,Hr as TextInput,Nr as TextInputPlugin,lr as TextOverflow,dr as TextPlugin,ur as TextRenderer,ar as TextVerticalAlign,rt as Time,eo as Toggle,Ft as UICameraInfo,Ar as UIEventQueue,Ir as UIEvents,Tr as UIInteraction,Lr as UIInteractionPlugin,Wr as UILayoutPlugin,pr as UIMask,Mr as UIMaskPlugin,Os as UIRect,De as Velocity,No as WebAssetProvider,It as World,We as WorldTransform,mt as addStartupSystem,yt as addSystem,_t as addSystemToSchedule,Ns as applyDirectionalFill,oe as applyRuntimeConfig,_n as assetPlugin,Yn as clearDrawCallbacks,Se as clearUserComponents,fe as color,js as computeFillAnchors,Ys as computeFillSize,Xs as computeHandleAnchors,Ls as computeUIRectLayout,Sr as createMaskProcessor,Yo as createRuntimeSceneConfig,hi as createWebApp,ii as debug,xe as defineComponent,Ze as defineResource,pt as defineSystem,ve as defineTag,ci as error,pn as findEntityByName,Ts as flushPendingSystems,S as getAddressableType,M as getAddressableTypeByEditorType,E as getAllAssetExtensions,A as getAssetMimeType,v as getAssetTypeEntry,Re as getComponent,tn as getComponentAssetFields,Ne as getComponentDefaults,C as getCustomExtensions,b as getEditorType,ri as getLogger,t as getPlatform,s as getPlatformType,be as getUserComponent,R as getWeChatPackOptions,ai as info,Bn as initDrawAPI,ps as initGLDebugAPI,Kn as initGeometryAPI,Dt as initMaterialAPI,ns as initPostProcessAPI,us as initRendererAPI,St as inputPlugin,vn as instantiatePrefab,gr as intersectRects,yr as invertMatrix4,Ee as isBuiltinComponent,I as isCustomExtension,Qo as isEditor,P as isKnownAssetExtension,n as isPlatformInitialized,Zo as isRuntime,Bt as isTextureRef,r as isWeChat,o as isWeb,dn as loadComponent,ko as loadPhysicsModule,Xo as loadRuntimeScene,cn as loadSceneData,un as loadSceneWithAssets,T as looksLikeAssetPath,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,vr as pointInOBB,_r as pointInWorldRect,Cn as prefabsPlugin,pe as quat,Ce as registerComponent,en as registerComponentAssetFields,on as registerComponentEntityFields,jn as registerDrawCallback,xn as registerEmbeddedAssets,qt as registerMaterialCallback,Ps as sceneManagerPlugin,mr as screenToWorld,Ko as setEditorMode,vo as setListViewRenderer,oi as setLogLevel,Ct as setWasmErrorHandler,Wn as shutdownDrawAPI,gs as shutdownGLDebugAPI,Qn as shutdownGeometryAPI,Lt as shutdownMaterialAPI,ss as shutdownPostProcessAPI,hs as shutdownRendererAPI,er as syncFillSpriteSize,Vr as textInputPlugin,fr as textPlugin,Fo as transitionTo,Or as uiInteractionPlugin,$r as uiLayoutPlugin,Pr as uiMaskPlugin,ui as uiPlugins,Me as unregisterComponent,Xn as unregisterDrawCallback,fn as updateCameraAspectRatio,ue as vec2,he as vec3,de as vec4,li as warn,Ss as wrapSceneSystem,z as wxFileExists,U as wxFileExistsSync,O as wxGetImagePixels,L as wxLoadImage,H as wxLoadImagePixels,W as wxReadFile,$ as wxReadTextFile,D as wxWriteFile};//# sourceMappingURL=index.wechat.js.mapdiff --git a/desktop/public/sdk/esm/esengine.d.ts b/desktop/public/sdk/esm/esengine.d.tsindex 52e97ecca..8c79a3002 100644--- a/desktop/public/sdk/esm/esengine.d.ts+++ b/desktop/public/sdk/esm/esengine.d.ts@@ -1616,6 +1616,7 @@ interface Plugin {name?: string;dependencies?: ResourceDef<any>[];build(app: App): void;+ cleanup?(): void;}declare class App {private readonly world_;diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.jsindex 08bbf86a7..ee27d4b63 100644--- a/desktop/public/sdk/esm/esengine.js+++ b/desktop/public/sdk/esm/esengine.js@@ -1,2 +1,2 @@-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function i(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function r(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.module}}createImage(){return new Image}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),i=t=>e.onKeyUp(t.code),o=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},r=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},u=()=>{e.onPointerUp(0)},h=t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)};document.addEventListener("keydown",s),document.addEventListener("keyup",i),n.addEventListener("mousemove",o),n.addEventListener("mousedown",r),document.addEventListener("mouseup",a),n.addEventListener("touchstart",l),n.addEventListener("touchmove",c),n.addEventListener("touchend",u),n.addEventListener("wheel",h),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",i),n.removeEventListener("mousemove",o),n.removeEventListener("mousedown",r),document.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",u),n.removeEventListener("wheel",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=1920,g=1080,y=100,m=512,_={x:100,y:100},x="Arial",w=24,v=1.2,b=.5,S=1/60,M={x:0,y:-9.81},P=1/60,E="default",T={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function C(e){e.Text&&(e.Text._default.fontFamily=T.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=T.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=T.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=T.canvasMatchWidthOrHeight)}const R=0,A=4294967295,I=4294967295,F=0,k=(e=0,t=0)=>({x:e,y:t}),B=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),z=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),U=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),$=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function D(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(D);const t={};for(const n in e)t[n]=D(e[n]);return t}let L=0;function W(e,t){const n=++L;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...D(t),...e}:D(t)}}const O=new Map;function H(){return"undefined"==typeof window?O:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function j(e,t){const n=J.get(e)??H().get(e);if(n)return n;const s=W(e,t);return H().set(e,s),J.set(e,s),G(e,t,!1),s}function X(e){const t=J.get(e)??H().get(e);if(t)return t;const n=W(e,{});return H().set(e,n),J.set(e,n),G(e,{},!0),n}function Y(e){return H().get(e)}function N(){const e=H();for(const t of e.keys())J.delete(t);e.clear()}function V(e){H().delete(e),J.delete(e)}function G(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function q(e){return!0===e._builtin}const J=new Map;function K(e,t){J.set(e,t)}function Q(e){return J.get(e)??Y(e)}function Z(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return J.set(e,n),n}const ee={Perspective:0,Orthographic:1},te={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ne={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},se=Z("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),ie=Z("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),oe=Z("Sprite",{texture:A,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}),re=Z("Camera",{projectionType:ee.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:te.ColorAndDepth}),ae=Z("Canvas",{designResolution:{x:p,y:g},pixelsPerUnit:100,scaleMode:ne.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),le=Z("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),ce=Z("Parent",{entity:0}),ue=Z("Children",{entities:[]}),he=Z("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:I,enabled:!0}),de=Z("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),fe={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},pe=j("SceneOwner",{scene:"",persistent:!1});function ge(e){const t=Q(e);return t?D(t._default):null}K("Name",fe);const ye=Z("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),me=Z("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),_e=Z("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),xe=Z("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),we={Static:0,Kinematic:1,Dynamic:2};let ve=0;function be(e,t){const n=++ve;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function Se(e){return{_type:"res",_resource:e}}function Me(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 Ee{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 Te=be({delta:0,elapsed:0,frameCount:0},"Time");function Ce(e){return{_type:"mut",_component:e}}function Re(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Ae(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{Re(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class Ie{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>Re(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),i=n.length,o=e.length>0,r=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let u=null;this.world_.beginIteration();try{for(const h of s){if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}if(r){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(h,t[n])){e=!0;break}if(e)continue}a[0]=h;for(let e=0;e<i;e++)a[e+1]=this.world_.get(h,n[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=h}yield a}}finally{if(this.world_.endIteration(),null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function Fe(){return{_type:"commands"}}class ke{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=q(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 Be{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ke(this,null);return this.spawned_.push(e),e}entity(e){return new ke(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,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 ze;!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(ze||(ze={}));let Ue=0;function $e(e,t,n){const s=++Ue;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function De(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Le(e){De().push({schedule:ze.Update,system:e})}function We(e){De().push({schedule:ze.Startup,system:e})}function Oe(e,t){De().push({schedule:e,system:t})}class He{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 Be&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new Ie(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Be(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class je{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 Xe=be(new je,"Input");class Ye{constructor(e){this.target_=e??null}build(e){const n=new je;e.insertResource(Xe,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(ze.Last,$e([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Ne=new Ye;function Ve(e,t,n){const s=[];for(const[e,i]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const n=Ge(t[e]),o=Ge(i);"null"!==n&&"undefined"!==n&&(n!==o&&null!=i&&s.push({field:e,expected:n,actual:o,value:i}))}return s}function Ge(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function qe(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 Je=null;function Ke(e){Je=e}function Qe(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Je&&Je(e,t)}function Ze(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}:Ze(e)}}return t}class et{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,this.nextEntityId_=0}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw Qe(e,"spawn"),e}else e=++this.nextEntityId_;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){Qe(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){Qe(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Qe(t,`removeParent(entity=${e})`)}}insert(e,t,n){return q(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return q(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return q(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(q(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return Qe(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.");q(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_,s=n[`add${e}`],i=n[`get${e}`],o=n[`has${e}`],r=n[`remove${e}`];if("function"!=typeof s||"function"!=typeof i||"function"!=typeof o||"function"!=typeof r)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:s.bind(n),get:i.bind(n),has:o.bind(n),remove:r.bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const e=Ve(t._name,t._default,s);if(e.length>0)throw new Error(qe(t._name,e))}const i={...t._default,...s};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,Ze(i))}catch(n){Qe(n,`insertBuiltin(${t._name}, entity=${e})`)}return i}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return this.getBuiltinMethods(t._cppName).get(e)}catch(n){return Qe(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 Qe(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){Qe(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 i=Ve(t._name,t._default,e);if(i.length>0)throw new Error(qe(t._name,i));s=e}const i=t.create(s);this.getStorage(t).set(e,i),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),i}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.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 J)if(q(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=H();for(const s of n)for(const[n,i]of e)if(i._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 i=this.queryCache_.get(s);if(i&&i.version===this.worldVersion_)return i.result;let o=null,r=1/0;for(const t of e)if(!q(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<r&&(r=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 tt=be({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var nt;function st(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"}(nt||(nt={}));let it=null,ot=null,rt=1;const at=new Map;function lt(e){it=e,ot=e.getResourceManager(),_t()}function ct(){0!==ft&&it&&(it._free(ft),ft=0),at.clear(),rt=1,dt=!1,gt.clear(),yt=null,ot=null,it=null}function ut(){if(!ot)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return ot}const ht={createShader:(e,t)=>ut().createShader(e,t),releaseShader(e){e>0&&ut().releaseShader(e)},create(e){const t=rt++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??nt.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 at.set(t,n),t},get:e=>at.get(e),setUniform(e,t,n){const s=at.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=at.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=at.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=at.get(e);return t?.blendMode??nt.Normal},setDepthTest(e,t){const n=at.get(e);n&&(n.depthTest=t)},getShader(e){const t=at.get(e);return t?.shader??0},release(e){at.delete(e)},isValid:e=>at.has(e),releaseAll(){at.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??nt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=at.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=rt++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return at.set(n,s),n},toAssetData(e,t){const n=at.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=at.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let dt=!1,ft=0;const pt=4096,gt=new Map;let yt=null;function mt(e){const t=(0===ft&&it&&(ft=it._malloc(pt)),ft);if(0===t||!it)return{ptr:0,count:0};let n=0,s=0;const i=it.HEAPU8,o=it.HEAPU32,r=it.HEAPF32;for(const[a,l]of e){if(n+128>pt)break;let e=gt.get(a);e||(yt||(yt=new TextEncoder),e=yt.encode(a),gt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,i.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)r[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function _t(){if(!it||dt)return;it.materialDataProvider=(e,t,n,s,i)=>{const o=at.get(e);if(!o)return it.HEAPU32[t>>2]=0,it.HEAPU32[n>>2]=0,it.HEAPU32[s>>2]=0,void(it.HEAPU32[i>>2]=0);it.HEAPU32[t>>2]=o.shader,it.HEAPU32[n>>2]=o.blendMode;const{ptr:r,count:a}=mt(o.uniforms);it.HEAPU32[s>>2]=r,it.HEAPU32[i>>2]=a},dt=!0}const xt={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class wt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.pending_.get(e);if(i&&!i.aborted)return i.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const s=t(),i=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{o.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return o.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class vt{constructor(e,t=""){this.cache_=new wt,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(ht.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())ht.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(i);return{handle:ht.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 bt=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 St(e,t){bt.set(e,t)}function Mt(e){const t=bt.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 bt.get(e)?.fields??[]}function Et(e){return bt.get(e)?.spine??null}const Tt=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Ct(e,t){Tt.set(e,t)}function Rt(e,t){const n=Tt.get(e.type);if(!n)return;const s=e.data;for(const e of n){const n=s[e];if("number"==typeof n&&0!==n){const i=t.get(n);s[e]=void 0!==i?i:0}}}function At(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();n.set(s.id,t),e.insert(t,fe,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;const t=n.get(s.id);for(const i of s.components)Rt(i,n),kt(e,t,i,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),i=n.get(s.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return n}function It(e,t){return At(e,t)}async function Ft(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl,o=new Map;s&&await async function(e,t,n,s){e=JSON.parse(JSON.stringify(e));const i=new Set,o=new Set,r=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=bt.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":i.add(t);break;case"material":o.add(t);break;case"font":r.add(t)}}}const c=new Map,u=new Map,h=new Map,d=[];for(const e of i)d.push((async()=>{try{const i=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(i);c.set(e,o.handle),s.set(e,i)}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);u.set(e,s.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of r)d.push((async()=>{try{const s=await t.loadBitmapFont(e,n);h.set(e,s)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),h.set(e,0)}})());for(const e of a)d.push((async()=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)})());await Promise.all(d);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=bt.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":n[e.field]=c.get(t)??0;break;case"material":n[e.field]=u.get(t)??0;break;case"font":n[e.field]=h.get(t)??0}}}}(t,s,i,o);const r=At(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}function kt(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 i=Q(n.type);if(i)e.insert(t,i,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function Bt(e,t){const n=e.getEntitiesWithComponents([re]);for(const s of n){const n=e.get(s,re);n&&(n.aspectRatio=t,e.insert(s,re,n))}}function zt(e,t){const n=e.getEntitiesWithComponents([fe]);for(const s of n){const n=e.get(s,fe);if(n&&n.value===t)return s}return null}const Ut=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],$t={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},Dt=new Map,Lt=new Set;for(const e of Ut)for(const t of e.extensions)Dt.set(t,e),Lt.add(t);function Wt(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function Ot(e){return Dt.get(Wt(e))}function Ht(e){return Ot(e)?.editorType??"unknown"}function jt(e){return Ot(e)?.addressableType??null}function Xt(e){for(const t of Ut)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function Yt(e){return Lt.has(e.toLowerCase())}function Nt(){return Lt}function Vt(e){return"string"==typeof e&&(!!e.includes("/")&&Yt(Wt(e)))}function Gt(){const e=[];for(const t of Ut)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function qt(){return Gt().map(e=>({type:"suffix",value:e}))}function Jt(e){return $t[e.toLowerCase()]}function Kt(e){const t=Ot(e);return t?.wechatPackInclude??!1}class Qt{constructor(e){this.textureCache_=new wt,this.shaderCache_=new wt,this.jsonCache_=new wt,this.textCache_=new wt,this.binaryCache_=new wt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new wt,this.prefabCache_=new wt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.module_=e,this.canvas_=h(T.textCanvasSize,T.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 vt(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),i=this.textureCache_.get(s);if(!i)continue;const o=(this.textureRefCounts_.get(s)??1)-1;o<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),ht.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const i=this.resolveUrl(t,n),o=await this.fetchText(i);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=r?`${r}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u="binary"===Ot(e)?.contentType,h=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(h,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),i=l.find(e=>e.name===n);if(i){const n=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,i.info.width,i.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=Ot(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const i=n?`${n}/${s}`:s;return this.loadFntFile(i)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${s}`:s,r=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,r.handle,r.width,r.height)}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 Ft(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const i=s.metadata?.atlas;i&&n.push(this.loadSpine(s.path,i).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const 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 i=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=i})}createTextureFromImage(e,t){const{width:n,height:s}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,i){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const r=this.module_.GL,a=r.getNewId(r.textures);r.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const i=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(o);const r=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=r.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:i}=this.parseEsShader(t);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return ht.createShader(s,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:o}=this.parseEsShader(s);if(!i||!o)throw new Error(`Invalid shader format: ${e}`);return ht.createShader(i,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}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 r(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.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 r(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.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 r(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let i="";for(const e of s){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Zt=be(null,"Assets");class en{build(e){const t=e.wasmModule;t?e.insertResource(Zt,new Qt(t)):console.warn("AssetPlugin: No WASM module available")}}const tn=new en;class nn{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 sn(e,t){const n=e.getResource(Zt);n&&n.registerEmbeddedAssets(t)}async function on(e,t,n){const{entities:s,rootId:i}=await an(t,n?.overrides??[],n,void 0,new Set),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},r=await Ft(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=r.get(i);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:r}}const rn=10;async function an(e,t,n,s,i,o=0){if(o>rn)throw new Error(`Prefab nesting depth exceeded ${rn}. Check for deep or circular nesting in: ${e.name}`);const r=new Map;let a;if(void 0===s){a=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=s;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(i?.has(s.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${s.nestedPrefab.prefabPath}`);continue}i?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await an(e,s.nestedPrefab.overrides,n,a,i,o+1);r.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?r.get(s.parent)??null:null),l.push(...t.entities);continue}const c=r.get(s.prefabEntityId),u=s.prefabEntityId===e.rootEntityId,h={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:u?null:null!==s.parent?r.get(s.parent)??null:null,children:s.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};ln(h,t),l.push(h)}const c=r.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function ln(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 cn{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,i=await this.assetServer_.loadPrefab(s,t?.baseUrl);return on(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const un=be(null,"Prefabs");class hn{constructor(){this.name="PrefabsPlugin",this.dependencies=[Zt]}build(e){const t=e.getResource(Zt);e.insertResource(un,new cn(e.world,t))}}const dn=new hn;let fn=null,pn=0,gn=0,yn=0;const mn=new Float32Array(256);function _n(e){fn=e,pn=fn._malloc(64),gn=fn._malloc(64),yn=fn._malloc(1024)}function xn(){fn&&(pn&&(fn._free(pn),pn=0),gn&&(fn._free(gn),gn=0),yn&&(fn._free(yn),yn=0)),fn=null}function wn(){if(!fn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return fn}const vn={r:1,g:1,b:1,a:1},bn={begin(e){const t=wn();try{t.HEAPF32.set(e,pn/4),t.draw_begin(pn)}catch(e){Qe(e,"Draw.begin")}},end(){try{wn().draw_end()}catch(e){Qe(e,"Draw.end")}},line(e,t,n,s=1){try{wn().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Qe(e,"Draw.line")}},rect(e,t,n,s=!0){try{wn().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Qe(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{wn().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Qe(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{wn().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Qe(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{wn().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Qe(e,"Draw.circleOutline")}},texture(e,t,n,s=vn){try{wn().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){Qe(e,"Draw.texture")}},textureRotated(e,t,n,s,i=vn){try{wn().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){Qe(e,"Draw.textureRotated")}},setLayer(e){wn().draw_setLayer(e)},setDepth(e){wn().draw_setDepth(e)},getDrawCallCount:()=>fn?fn.draw_getDrawCallCount():0,getPrimitiveCount:()=>fn?fn.draw_getPrimitiveCount():0,setBlendMode(e){wn().draw_setBlendMode(e)},setDepthTest(e){wn().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=wn();s.HEAPF32.set(n,gn/4),s.draw_mesh(e,t,gn)}catch(n){Qe(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=wn(),i=ht.get(t);if(!i)return;if(bn.setBlendMode(i.blendMode),bn.setDepthTest(i.depthTest),0===i.uniforms.size)return void bn.drawMesh(e,i.shader,n);let o;if(s.HEAPF32.set(n,gn/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,n]of i.uniforms){const s=Pn(t);if(!(s<0)){if(st(n))mn[o++]=10,mn[o++]=s,mn[o++]=n.slot??e++,mn[o++]=n.textureId;else if("number"==typeof n)mn[o++]=1,mn[o++]=s,mn[o++]=n;else if(Array.isArray(n)){mn[o++]=n.length,mn[o++]=s;for(let e=0;e<n.length;e++)mn[o++]=n[e]}else"w"in n?(mn[o++]=4,mn[o++]=s,mn[o++]=n.x,mn[o++]=n.y,mn[o++]=n.z,mn[o++]=n.w):"z"in n?(mn[o++]=3,mn[o++]=s,mn[o++]=n.x,mn[o++]=n.y,mn[o++]=n.z):(mn[o++]=2,mn[o++]=s,mn[o++]=n.x,mn[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<o)&&(i.cachedBuffer_=new Float32Array(o)),i.cachedBuffer_.set(mn.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void s.draw_mesh(e,i.shader,gn);s.HEAPF32.set(i.cachedBuffer_.subarray(0,o),yn/4),s.draw_meshWithUniforms(e,i.shader,gn,yn,o)}catch(n){Qe(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Sn={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17},Mn=new Set;function Pn(e){const t=Sn[e];return void 0!==t?t:(Mn.has(e)||(Mn.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Sn).join(", ")}`)),-1)}const En=new Map;function Tn(e,t,n){En.set(e,{fn:t,scene:n??""})}function Cn(e){En.delete(e)}function Rn(){En.clear()}var An;!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"}(An||(An={}));let In=null,Fn=0,kn=0,Bn=0;function zn(e){In=e,Fn=In._malloc(262144),kn=In._malloc(65536),Bn=In._malloc(256)}function Un(){In&&(Fn&&In._free(Fn),kn&&In._free(kn),Bn&&In._free(Bn),Fn=0,kn=0,Bn=0),In=null}function $n(){if(!In)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return In}const Dn={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,Fn/4);const i=e.layout.length,o=new Int32Array(i);for(let t=0;t<i;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Bn,i).set(o),t.geometry_init(n,Fn,s,Bn,i,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,kn,s).set(e.indices),t.geometry_setIndices16(n,kn,s)}else{new Uint32Array(t.HEAPU8.buffer,kn,s).set(e.indices),t.geometry_setIndices32(n,kn,s)}}return n},updateVertices(e,t,n=0){const s=$n(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,Fn/4),s.geometry_updateVertices(e,Fn,i,n)},release(e){e>0&&$n().geometry_release(e)},isValid:e=>!(!In||e<=0)&&In.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Dn.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:An.Float2},{name:"a_texCoord",type:An.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const i=s/t*Math.PI*2,o=Math.cos(i)*e,r=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;n.push(o,r,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return Dn.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:An.Float2},{name:"a_texCoord",type:An.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,i=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(s-t),a=(r.y-n)/(i-n);o.push(r.x,r.y,e,a)}const r=[];for(let t=1;t<e.length-1;t++)r.push(0,t,t+1);return Dn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:An.Float2},{name:"a_texCoord",type:An.Float2}],indices:new Uint16Array(r)})}};let Ln=null;function Wn(e){Ln=e}function On(){Ln&&jn.isInitialized()&&jn.shutdown(),Ln=null}function Hn(){if(!Ln)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ln}const jn={init(e,t){try{return Hn().postprocess_init(e,t)}catch(n){return Qe(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Hn().postprocess_shutdown()}catch(e){Qe(e,"PostProcess.shutdown")}},resize(e,t){try{Hn().postprocess_resize(e,t)}catch(n){Qe(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Hn().postprocess_addPass(e,t)}catch(t){return Qe(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Hn().postprocess_removePass(e)}catch(t){Qe(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Hn().postprocess_setPassEnabled(e,t)}catch(t){Qe(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Hn().postprocess_isPassEnabled(e)}catch(t){return Qe(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{Hn().postprocess_setUniformFloat(e,t,n)}catch(n){Qe(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{Hn().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){Qe(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Hn().postprocess_begin()}catch(e){Qe(e,"PostProcess.begin")}},end(){try{Hn().postprocess_end()}catch(e){Qe(e,"PostProcess.end")}},getPassCount(){try{return Hn().postprocess_getPassCount()}catch(e){return Qe(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Ln)return!1;try{return Ln.postprocess_isInitialized()}catch(e){return Qe(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Hn().postprocess_setBypass(e)}catch(e){Qe(e,"PostProcess.setBypass")}},isBypassed(){if(!Ln)return!0;try{return Ln.postprocess_isBypassed()}catch(e){return Qe(e,"PostProcess.isBypassed"),!0}},createBlur:()=>ht.createShader(Xn,"#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:()=>ht.createShader(Xn,"#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:()=>ht.createShader(Xn,"#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:()=>ht.createShader(Xn,"#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")},Xn="#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 Yn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Yn||(Yn={}));let Nn=null,Vn=0;function Gn(e){Nn=e,Vn=Nn._malloc(64)}function qn(){Nn&&Vn&&(Nn._free(Vn),Vn=0),Nn=null}const Jn={init(e,t){Nn?.renderer_init(e,t)},resize(e,t){Nn?.renderer_resize(e,t)},begin(e,t){if(Nn&&Vn)try{Nn.HEAPF32.set(e,Vn/4),Nn.renderer_begin(Vn,t??0)}catch(e){Qe(e,"Renderer.begin")}},flush(){try{Nn?.renderer_flush()}catch(e){Qe(e,"Renderer.flush")}},end(){try{Nn?.renderer_end()}catch(e){Qe(e,"Renderer.end")}},submitSprites(e){if(Nn)try{Nn.renderer_submitSprites(e._cpp)}catch(e){Qe(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Nn)try{Nn.renderer_submitBitmapText(e._cpp)}catch(e){Qe(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Nn)try{Nn.renderer_submitSpine?.(e._cpp)}catch(e){Qe(e,"Renderer.submitSpine")}},setStage(e){Nn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Nn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Nn?.renderer_releaseTarget(e)},getTargetTexture:e=>Nn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Nn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Nn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Nn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){Nn?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){Nn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Nn?Nn.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Nn?{drawCalls:Nn.renderer_getDrawCalls(),triangles:Nn.renderer_getTriangles(),sprites:Nn.renderer_getSprites(),text:Nn.renderer_getText(),spine:Nn.renderer_getSpine?.()??0,meshes:Nn.renderer_getMeshes(),culled:Nn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Kn=null;function Qn(e){Kn=e}function Zn(){Kn=null}const es={enable(){Kn?.gl_enableErrorCheck(!0)},disable(){Kn?.gl_enableErrorCheck(!1)},check:e=>Kn?.gl_checkErrors(e)??0,diagnose(){Kn?.renderer_diagnose()}};class ts{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:o}=e;s===this.lastWidth_&&i===this.lastHeight_||(Jn.resize(s,i),jn.isInitialized()&&jn.getPassCount()>0&&jn.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),Jn.setViewport(0,0,s,i),Jn.clearBuffers(3),Jn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),Jn.submitSprites(t),Jn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Jn.submitSpine(t),Jn.flush(),this.executeDrawCallbacks(n,o),Jn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:o}=e;Jn.setViewport(s.x,s.y,s.w,s.h),Jn.setScissor(s.x,s.y,s.w,s.h,!0),Jn.clearBuffers(i),Jn.setScissor(0,0,0,0,!1),Jn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Jn.submitSprites(t),Jn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Jn.submitSpine(t),Jn.flush(),this.executeDrawCallbacks(n,o),Jn.end()}executeDrawCallbacks(e,t){const n=En;if(n.size>0){bn.begin(e);const s=[];for(const[e,i]of n.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}bn.end();for(const e of s)Cn(e)}}}const ns="__scene_transition_overlay__";class ss{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class is{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,pe,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),Tn(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=jn.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){jn.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,pe)){const n=this.app_.world.get(e,pe);n.persistent=t,this.app_.world.insert(e,pe,n)}}}class os{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??T.sceneTransitionDuration,i=t.color??{...T.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},Tn(ns,()=>{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;bn.setLayer(9999),bn.setDepth(9999),bn.rect({x:0,y:0},{x:2e4,y:2e4},{r:i.r,g:i.g,b:i.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{try{n&&n!==e&&await this.unload(n,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,Cn(ns),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Cn(ns),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 ss(t);this.scenes_.set(e,n);const s=new is(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Zt)?this.app_.getResource(Zt):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}if(i){const t={};this.app_.hasResource(Zt)&&(t.assetServer=this.app_.getResource(Zt));const s=await Ft(this.app_.world,i,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,pe,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=as(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,i);try{return await i}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new ss(t);this.scenes_.set(e,n);const s=new is(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Zt)?this.app_.getResource(Zt):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}if(i){const t={};this.app_.hasResource(Zt)&&(t.assetServer=this.app_.getResource(Zt));const s=await Ft(this.app_.world,i,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,pe,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=as(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,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const i=t?.keepPersistent??!0;for(const e of n.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,pe)){if(this.app_.world.get(e,pe).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())Cn(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{jn.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)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s={};let i=!1;if(n.has(e,oe)){const t=n.get(e,oe);s.sprite=t.color.a,t.color={...t.color,a:0},n.insert(e,oe,t),i=!0}if(n.has(e,de)){const t=n.get(e,de);s.spine=t.color.a,t.color={...t.color,a:0},n.insert(e,de,t),i=!0}if(n.has(e,he)){const t=n.get(e,he);s.bitmapText=t.color.a,t.color={...t.color,a:0},n.insert(e,he,t),i=!0}i&&t.savedAlphas.set(e,s)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s=t.savedAlphas.get(e);if(s){if(void 0!==s.sprite&&n.has(e,oe)){const t=n.get(e,oe);t.color={...t.color,a:s.sprite},n.insert(e,oe,t)}if(void 0!==s.spine&&n.has(e,de)){const t=n.get(e,de);t.color={...t.color,a:s.spine},n.insert(e,de,t)}if(void 0!==s.bitmapText&&n.has(e,he)){const t=n.get(e,he);t.color={...t.color,a:s.bitmapText},n.insert(e,he,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{jn.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=be(null,"SceneManager");function as(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 ls=$e([Me(rs),Se(Te)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),cs={name:"SceneManager",build(e){const t=new os(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(ze.Startup,n),e.addSystemToSchedule(ze.Last,ls)}};class us{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(ze.Last);else{this.runSchedule(ze.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ze.FixedPreUpdate),this.runSchedule(ze.FixedUpdate),this.runSchedule(ze.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(ze.PreUpdate),this.runSchedule(ze.Update),this.runSchedule(ze.PostUpdate),this.runSchedule(ze.Last),this.step_pending_&&(this.step_pending_=!1)}requestAnimationFrame(this.mainLoop)},this.world_=new et,this.resources_=new Ee;for(const e of Object.values(ze))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new us}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(ze.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(ze.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}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 Ke(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 He(this.world_,this.resources_),this.resources_.insert(Te,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(ze.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Rn();const e=[Zn,qn,On,Un,ct,xn];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 i=t.get(s);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,i=new Set,o=r=>{if(s.has(r))return;if(i.has(r)){const t=e[r].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(r);const a=e[r];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&o(n)}i.delete(r),s.add(r),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));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(Te);t.delta=e,t.elapsed+=e,t.frameCount++}}function hs(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 ds=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function fs(e,t,n,s,i){const o=e*t/n,r=e;switch(s){case ne.FixedWidth:return o;case ne.FixedHeight:return r;case ne.Expand:return Math.max(o,r);case ne.Shrink:return Math.min(o,r);case ne.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}function ps(e,t,n,s,i,o){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,pe);return!t||""===t.scene||o.has(t.scene)}):r;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),o=t.getLocalTransform(e),r={x:i.viewportX,y:i.viewportY,w:i.viewportW,h:i.viewportH},a=r.w*n/(r.h*s);let u,h=0,d=0;if(i.projectionType===ee.Orthographic){if(d=i.orthoSize,l){d=fs(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}h=d*a,u=ys(-h,h,-d,d,-i.farPlane,i.farPlane)}else u=_s(i.fov*Math.PI/180,a,i.nearPlane,i.farPlane);const f=ws(o.position.x,o.position.y,o.position.z);c.push({entity:e,viewProjection:new Float32Array(bs(u,f)),viewportRect:r,clearFlags:i.clearFlags,priority:i.priority,halfW:h,halfH:d,cameraX:o.position.x,cameraY:o.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const gs=new Float32Array(16);function ys(e,t,n,s,i,o){const r=gs;r.fill(0);const a=t-e,l=s-n,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(s+n)/l,r[14]=-(o+i)/c,r[15]=1,r}const ms=new Float32Array(16);function _s(e,t,n,s){const i=ms;i.fill(0);const o=1/Math.tan(e/2),r=n-s;return i[0]=o/t,i[5]=o,i[10]=(s+n)/r,i[11]=-1,i[14]=2*s*n/r,i}const xs=new Float32Array(16);function ws(e,t,n){const s=xs;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 vs=new Float32Array(16);function bs(e,t){const n=vs;for(let s=0;s<4;s++)for(let i=0;i<4;i++)n[4*i+s]=e[0+s]*t[4*i+0]+e[4+s]*t[4*i+1]+e[8+s]*t[4*i+2]+e[12+s]*t[4*i+3];return n}const Ss={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function Ms(e,t,n,s,i,o,r={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,u=o.left+t.x*a,h=o.bottom+e.y*l,d=o.bottom+t.y*l;let f,p,g,y;e.x===t.x?(f=c+n.x-i.x*r.x,g=f+i.x):(f=c+n.x,g=u+s.x),e.y===t.y?(p=h+n.y-i.y*r.y,y=p+i.y):(p=h+n.y,y=d+s.y);const m=Math.max(0,g-f),_=Math.max(0,y-p);return{originX:f+r.x*m,originY:p+r.y*_,width:m,height:_,rect:{left:f,bottom:p,right:g,top:y}}}const Ps=j("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},_dirty:!0,_computedWidth:void 0,_computedHeight:void 0,_layoutManaged:void 0});function Es(e,t){e.has(t,oe)||e.insert(t,oe,{texture:A,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0})}function Ts(e,t){switch(e){case Ss.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Ss.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Ss.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function Cs(e,t){switch(e){case Ss.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case Ss.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case Ss.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1-t}};default:return{anchorMin:{x:t,y:0},anchorMax:{x:t,y:1}}}}function Rs(e,t,n,s){switch(e){case Ss.BottomToTop:case Ss.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function As(e,t,n,s){if(!e.has(t,Ps))return;const i=e.get(t,Ps),o=Ts(n,s);i.anchorMin=o.anchorMin,i.anchorMax=o.anchorMax,i.offsetMin=o.offsetMin,i.offsetMax=o.offsetMax,e.insert(t,Ps,i)}function Is(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Fs(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function ks(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),i=[];for(const t of s){if(!t){i.push("");continue}let s="";for(let o=0;o<t.length;o++){const r=t[o],a=s+r;if(e.measureText(a).width>n&&s){if(Fs(r.charCodeAt(0))&&s.length>0&&Fs(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!Fs(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+r):(i.push(s),s=r)}else i.push(s),s=r}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function Bs(e){let t=1;for(;t<e;)t*=2;return t}function zs(e,t){let n=0,s=t;for(;e.has(s,ce);){const t=e.get(s,ce).entity;if(!e.valid(t))break;n++,s=t}return n}function Us(e){return e._computedWidth??e.size.x}function $s(e){return e._computedHeight??e.size.y}function Ds(e,t,n,s,i,o){if(!e.has(t,oe))return;const r=e.get(t,oe);let a,l;switch(n){case Ss.BottomToTop:case Ss.TopToBottom:a=i,l=o*s;break;default:a=i*s,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,oe,r))}function Ls(e,t,n){let s=t;for(;e.has(s,ce);){const t=e.get(s,ce).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function Ws(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function Os(e,t,n,s,i){if(!e.has(t,Ps))return;const o=e.get(t,Ps),r=Ms(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,n,o.pivot),a=r.rect.right-r.rect.left,l=r.rect.top-r.rect.bottom;if(o._computedWidth=a,o._computedHeight=l,e.has(t,oe)){const n=e.get(t,oe);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,oe,n))}if(!o._layoutManaged&&e.has(t,se)){const n=e.get(t,se);n.position.x=r.originX-s,n.position.y=r.originY-i,e.insert(t,se,n)}}function Hs(e){const t=Object.keys(e),n=t.map(t=>e[t]);return{take(e){const s={};for(let i=0;i<t.length;i++)s[t[i]]=n[i](e);return s},changed(e,s){for(let i=0;i<t.length;i++)if(e[t[i]]!==n[i](s))return!0;return!1},update(e,s){for(let i=0;i<t.length;i++)e[t[i]]=n[i](s)}}}const js={r:.3,g:.5,b:.8,a:1},Xs={Left:0,Center:1,Right:2},Ys={Top:0,Middle:1,Bottom:2},Ns={Visible:0,Clip:1,Ellipsis:2},Vs=j("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Xs.Left,verticalAlign:Ys.Top,wordWrap:!0,overflow:Ns.Visible,lineHeight:1.2});class Gs{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(T.textCanvasSize,T.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,Bs(this.frameMaxW_)),e.height=Math.max(e.height,Bs(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Bs(this.frameMaxW_),e.height=Bs(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,o=i?t.size.x:0,r=i?t.size.y:0,a=e.wordWrap&&i;let l=ks(n,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=i?Math.ceil(o):h+2*u,p=i?Math.ceil(r):d+2*u;if(i&&e.overflow===Ns.Ellipsis&&d>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,Bs(f)),s.height=Math.max(s.height,Bs(p)));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}, ${_})`,i&&e.overflow===Ns.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const x=l.length*c;let w;if(i)switch(e.verticalAlign){case Ys.Top:w=u;break;case Ys.Middle:w=u+(p-2*u-x)/2;break;case Ys.Bottom:w=p-x-u;break;default:w=u}else w=u;let v=w;for(const t of l){let s;switch(e.align){case Xs.Left:s=u;break;case Xs.Center:s=f/2;break;case Xs.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=c}i&&e.overflow===Ns.Clip&&n.restore();const b=n.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),M=this.module.getResourceManager(),P=this.module._malloc(S.length);this.module.HEAPU8.set(S,P);const E=M.createTexture(f,p,P,S.length,1,!0);return this.module._free(P),{textureHandle:E,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const i=this.renderText(t,n);return this.cache.set(e,i),i}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}measureWidth(e){let t=0;for(const n of e)t=Math.max(t,this.ctx.measureText(n).width);return t}mapAlign(e){switch(e){case Xs.Left:return"left";case Xs.Center:return"center";case Xs.Right:return"right"}}}const qs=Hs({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?Us(e.uiRect):0,containerHeight:e=>e.uiRect?$s(e.uiRect):0});class Js{build(e){K("Text",Vs);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Gs(t),s=e.world,i=new Map;e.addSystemToSchedule(ze.PreUpdate,$e([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Vs));for(const e of i.keys())if(!s.valid(e)||!s.has(e,Vs)){if(s.valid(e)&&s.has(e,oe)){const t=s.get(e,oe);t.texture=A,s.insert(e,oe,t)}i.delete(e)}const e=s.getEntitiesWithComponents([Vs]);for(const t of e){const e=s.get(t,Vs),o=s.has(t,Ps)?s.get(t,Ps):null,r={text:e,uiRect:o},a=i.get(t);if(a&&!qs.changed(a,r))continue;Es(s,t);const l=n.renderForEntity(t,e,o),c=s.get(t,oe);c.texture=l.textureHandle,c.size.x=l.width,c.size.y=l.height,c.uvOffset.x=0,c.uvOffset.y=0,c.uvScale.x=1,c.uvScale.y=1,s.insert(t,oe,c),i.set(t,qs.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Ks=new Js,Qs=j("UIMask",{enabled:!0,mode:"scissor"});function Zs(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),i=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,i-n),h:Math.max(0,o-s)}}function ei(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],o=e[2],r=e[3],a=e[4],l=e[5],c=e[6],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],g=e[12],y=e[13],m=e[14],_=e[15],x=s*l-i*a,w=s*c-o*a,v=s*u-r*a,b=i*c-o*l,S=i*u-r*l,M=o*u-r*c,P=h*y-d*g,E=h*m-f*g,T=h*_-p*g,C=d*m-f*y,R=d*_-p*y,A=f*_-p*m;let I=x*A-w*R+v*C+b*T-S*E+M*P;return 0===I||(I=1/I,n[0]=(l*A-c*R+u*C)*I,n[1]=(o*R-i*A-r*C)*I,n[2]=(y*M-m*S+_*b)*I,n[3]=(f*S-d*M-p*b)*I,n[4]=(c*T-a*A-u*E)*I,n[5]=(s*A-o*T+r*E)*I,n[6]=(m*v-g*M-_*w)*I,n[7]=(h*M-f*v+p*w)*I,n[8]=(a*R-l*T+u*P)*I,n[9]=(i*T-s*R-r*P)*I,n[10]=(g*S-y*v+_*x)*I,n[11]=(d*v-h*S-p*x)*I,n[12]=(l*E-a*C-c*P)*I,n[13]=(s*C-i*E+o*P)*I,n[14]=(y*w-g*b-m*x)*I,n[15]=(h*b-d*w+f*x)*I),n}function ti(e,t,n,s,i,o,r){const a=(e-s)/o*2-1,l=(t-i)/r*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:u/h}}function ni(e,t,n,s,i,o,r,a){return e>=n-i*r&&e<=n+i*(1-r)&&t>=s-o*a&&t<=s+o*(1-a)}function si(e,t){return 2*Math.atan2(e,t)}function ii(e,t,n,s,i,o,r){const a=n[0]*e+n[4]*t+n[12],l=n[1]*e+n[5]*t+n[13],c=n[3]*e+n[7]*t+n[15];return[s+(.5*(a/c)+.5)*o,i+(.5*(l/c)+.5)*r]}function oi(e,t,n,s,i,o,r,a,l,c){const u=si(l,c),h=Math.sin(-u),d=Math.cos(-u),f=e-n,p=t-s,g=f*d-p*h+n,y=f*h+p*d+s;return g>=n-i*r&&g<=n+i*(1-r)&&y>=s-o*a&&y<=s+o*(1-a)}function ri(e,t,n,s,i,o,r){if(!e.has(t,Ps)||!e.has(t,ie))return null;const a=e.get(t,Ps),l=e.get(t,ie),c=Us(a)*l.scale.x,u=$s(a)*l.scale.y,h=l.position.x,d=l.position.y,f=a.pivot.x,p=a.pivot.y,g=-c*f,y=c*(1-f),m=-u*p,_=u*(1-p),x=si(l.rotation.z,l.rotation.w),w=Math.cos(x),v=Math.sin(x),b=[[h+g*w-m*v,d+g*v+m*w],[h+y*w-m*v,d+y*v+m*w],[h+y*w-_*v,d+y*v+_*w],[h+g*w-_*v,d+g*v+_*w]];let S=1/0,M=1/0,P=-1/0,E=-1/0;for(const[e,t]of b){const[a,l]=ii(e,t,n,s,i,o,r);S=Math.min(S,a),M=Math.min(M,l),P=Math.max(P,a),E=Math.max(E,l)}return{x:Math.round(S),y:Math.round(M),w:Math.round(P-S),h:Math.round(E-M)}}function ai(e,t){return(n,s,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Qs]);if(0===l.length)return;const c=[],u=[],h=new Set,d=new Set;for(const e of l){const n=t.get(e,Qs);n.enabled&&(h.add(e),"stencil"===n.mode?(u.push(e),d.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,i,o,r,a,l,c){const u=[];for(const e of s){let n=!0;Ls(t,e,e=>{if(i.has(e)){if("scissor"===t.get(e,Qs).mode)return n=!1,!0}return!1}),n&&u.push(e)}function h(s,u){const d=e.getChildEntities(n,s);for(const n of d){let s=u;if(i.has(n)){if("scissor"===t.get(n,Qs).mode){const e=ri(t,n,o,r,a,l,c);e&&(s=Zs(u,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of u){const n=ri(t,e,o,r,a,l,c);n&&h(e,n)}}(e,t,n,c,h,s,i,o,r,a),u.length>0&&function(e,t,n,s,i){e.renderer_clearStencil();const o=[];for(const e of s){let n=!0;Ls(t,e,e=>!!i.has(e)&&(n=!1,!0)),n&&o.push(e)}let r=1,a=!1;function l(){return r>255?(a||console.warn("Stencil mask overflow"),a=!0,null):r++}function c(t,s){if(a)return;e.renderer_setEntityStencilMask(t,s);const o=e.getChildEntities(n,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),u(t,s)}function u(t,s){if(a)return;const o=e.getChildEntities(n,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),u(t,s)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,n,u,d)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class li{build(e){if(K("UIMask",Qs),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(ai(e.wasmModule,e.world))}}const ci=new li,ui=j("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),hi=j("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),di={Normal:0,Hovered:1,Pressed:2,Disabled:3},fi=j("Button",{state:di.Normal,transition:null});class pi{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 gi=be(new pi,"UIEvents"),yi=X("ScreenSpace"),mi=Hs({anchorMinX:e=>e.anchorMin.x,anchorMinY:e=>e.anchorMin.y,anchorMaxX:e=>e.anchorMax.x,anchorMaxY:e=>e.anchorMax.y,offsetMinX:e=>e.offsetMin.x,offsetMinY:e=>e.offsetMin.y,offsetMaxX:e=>e.offsetMax.x,offsetMaxY:e=>e.offsetMax.y,sizeX:e=>e.size.x,sizeY:e=>e.size.y});function _i(e,t,n,s,i,o){if(!e.has(t,Ps))return;const r=e.get(t,Ps),a=Ms(r.anchorMin,r.anchorMax,r.offsetMin,r.offsetMax,r.size,n,r.pivot),l=a.rect.right-a.rect.left,c=a.rect.top-a.rect.bottom;if(r._computedWidth=l,r._computedHeight=c,e.has(t,oe)){const n=e.get(t,oe);n.size.x===l&&n.size.y===c||(n.size.x=l,n.size.y=c,e.insert(t,oe,n))}if(!r._layoutManaged){const n=e.get(t,se);o?(n.position.x=a.originX,n.position.y=a.originY):(n.position.x=a.originX-s,n.position.y=a.originY-i),e.insert(t,se,n)}if(!e.has(t,ue))return;const u=e.get(t,ue);if(u&&u.entities)for(const t of u.entities)e.valid(t)&&_i(e,t,a.rect,a.originX,a.originY,!1)}class xi{build(e){K("UIRect",Ps);const t=e.world,n=new Map,s=new Map;let i=NaN,o=NaN,r=NaN,a=NaN;function l(e){let n=s.get(e);return void 0!==n||(n=function(e,t){let n=t;for(;;){if(e.has(n,yi))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}}(t,e),s.set(e,n)),n}function c(e){if(s.delete(e),!t.has(e,ue))return;const n=t.get(e,ue);if(n&&n.entities)for(const e of n.entities)t.valid(e)&&c(e)}e.addSystemToSchedule(ze.PreUpdate,$e([Se(tt)],e=>{if(!e.valid)return;const u={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},h=.5*(u.left+u.right),d=.5*(u.bottom+u.top),f=i!==e.worldLeft||o!==e.worldBottom||r!==e.worldRight||a!==e.worldTop;i=e.worldLeft,o=e.worldBottom,r=e.worldRight,a=e.worldTop;const p=new Set;if(f){s.clear();const e=t.getEntitiesWithComponents([yi,Ps,se]);for(const t of e)p.add(t)}for(const e of n.keys())t.valid(e)&&t.has(e,Ps)||(n.delete(e),s.delete(e));const g=t.getEntitiesWithComponents([Ps]);for(const e of g){const s=t.get(e,Ps),i=n.get(e);if(s._dirty||!i||mi.changed(i,s)){s._dirty=!1,c(e);const t=l(e);null!==t&&p.add(t)}}for(const e of p)_i(t,e,u,h,d,!0);for(const e of g){const s=t.get(e,Ps),i=n.get(e);i?mi.update(i,s):n.set(e,mi.take(s))}},{name:"UILayoutSystem"}))}}const wi=new xi,vi=function(){const e=new Float32Array(16),t=new Float32Array(16);let n=!0;return{update(e){for(let s=0;s<16;s++)if(t[s]!==e[s]){t.set(e),n=!0;break}},getInverse:t=>(n&&(ei(t,e),n=!1),e)}}();function bi(e,t,n,s){let i=!1;return Ls(e,t,t=>{if(!e.has(t,Qs))return!1;if(!e.get(t,Qs).enabled||!e.has(t,Ps)||!e.has(t,ie))return!1;const o=e.get(t,ie),r=e.get(t,Ps),a=Us(r)*o.scale.x,l=$s(r)*o.scale.y;return!oi(n,s,o.position.x,o.position.y,a,l,r.pivot.x,r.pivot.y,o.rotation.z,o.rotation.w)&&(i=!0,!0)}),i}function Si(e,t,n,s){t.emit(n,s,n),Ls(e,n,i=>{if(!e.has(i,ui))return!1;const o=e.get(i,ui);return o.enabled&&t.emit(i,s,n),o.blockRaycast})}class Mi{build(e){K("Interactable",ui),K("Button",fi);const t=e.world,n=new pi;e.insertResource(gi,n);let s=null,i=null;e.addSystemToSchedule(ze.PreUpdate,$e([Se(Xe),Se(tt)],(e,o)=>{n.drain();const r=t.getEntitiesWithComponents([hi]);for(const e of r){const n=t.get(e,hi);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a="undefined"!=typeof window&&window.devicePixelRatio||1,l=e.mouseX*a,c=o.screenH-e.mouseY*a;vi.update(o.viewProjection);const u=ti(l,c,vi.getInverse(o.viewProjection),o.vpX,o.vpY,o.vpW,o.vpH);o.worldMouseX=u.x,o.worldMouseY=u.y;const h=t.getEntitiesWithComponents([ui,Ps,ie]);let d=null,f=-1/0;for(const e of h){Ws(t,e,hi);const n=t.get(e,ui);if(!n.enabled)continue;if(!n.raycastTarget)continue;const s=t.get(e,ie),i=t.get(e,Ps),o=Us(i)*s.scale.x,r=$s(i)*s.scale.y;if(oi(u.x,u.y,s.position.x,s.position.y,o,r,i.pivot.x,i.pivot.y,s.rotation.z,s.rotation.w)){if(bi(t,e,u.x,u.y))continue;let n=0;t.has(e,oe)&&(n=t.get(e,oe).layer),n>f&&(f=n,d=e)}}if(null===s||t.valid(s)||(s=null),s!==d){if(null!==s&&t.valid(s)&&t.has(s,hi)){t.get(s,hi).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,hi).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,hi);e.pressed=!0,e.justPressed=!0,i=d,Si(t,n,d,"press")}if(e.isMouseButtonReleased(0)&&null!==i){if(t.valid(i)&&t.has(i,hi)){const e=t.get(i,hi);e.pressed=!1,e.justReleased=!0,Si(t,n,i,"release"),i===s&&Si(t,n,i,"click")}i=null}},{name:"UIInteractionSystem"}));const o=new Set;e.addSystemToSchedule(ze.Update,$e([],()=>{const e=t.getEntitiesWithComponents([fi]);for(const n of e){if(Ws(t,n,ui,{enabled:!0}),!t.has(n,hi))continue;const e=t.get(n,hi),s=t.get(n,fi),i=t.get(n,ui),r=!o.has(n),a=s.state;if(i.enabled?e.pressed?s.state=di.Pressed:e.hovered?s.state=di.Hovered:s.state=di.Normal:s.state=di.Disabled,r&&o.add(n),(r||a!==s.state)&&s.transition&&t.has(n,oe)){const o=t.get(n,oe);o.color=Is(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,oe,o)}}},{name:"ButtonSystem"}))}}const Pi=new Mi,Ei=j("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}),Ti=j("Focusable",{tabIndex:0,isFocused:!1});class Ci{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 Ri=be(new Ci,"FocusManager");class Ai{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){K("TextInput",Ei);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,i=h(T.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=!1,a=!0,l=0,c=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 d=u;function f(){const t=e.getResource(Ri);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,Ei)?s:null}const p=()=>{r||null===f()||x()},g=()=>{r=!0},y=()=>{r=!1,x()},m=t=>{const s=f();if(null===s)return;if("Escape"===t.key)return void w();const i=n.get(s,Ei);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(gi).emit(s,"submit"),void w()}let o=i.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?o=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=i.value.length),o!==i.cursorPos&&(i.cursorPos=o,d.selectionStart=o,d.selectionEnd=o,i.dirty=!0,v())},_=()=>{const t=f();if(null!==t){const s=n.get(t,Ei);s.focused=!1,s.dirty=!0;e.getResource(Ri).blur()}};function x(){const t=f();if(null===t)return;const s=n.get(t,Ei);if(s.readOnly)return;let i=d.value;if(s.maxLength>0&&i.length>s.maxLength&&(i=i.substring(0,s.maxLength),d.value=i),i!==s.value){s.value=i;e.getResource(gi).emit(t,"change")}s.cursorPos=d.selectionStart??i.length,s.dirty=!0,v()}function w(){const t=f();if(null!==t){const e=n.get(t,Ei);e.focused=!1,e.dirty=!0}e.getResource(Ri).blur(),d.blur()}function v(){a=!0,l=0}d.addEventListener("input",p),d.addEventListener("compositionstart",g),d.addEventListener("compositionend",y),d.addEventListener("keydown",m),d.addEventListener("blur",_),this.cleanupListeners_=()=>{d.removeEventListener("input",p),d.removeEventListener("compositionstart",g),d.removeEventListener("compositionend",y),d.removeEventListener("keydown",m),d.removeEventListener("blur",_),d.remove();const e=t.getResourceManager();for(const t of s.values())e.releaseTexture(t);s.clear()};let b=null;function S(e,r,l,c){(i.width<l||i.height<c)&&(i.width=Bs(Math.max(i.width,l)),i.height=Bs(Math.max(i.height,c))),o.clearRect(0,0,i.width,i.height);const u=r.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,l,c),o.save(),o.beginPath(),o.rect(r.padding,0,l-2*r.padding,c),o.clip(),o.font=`${r.fontSize}px ${r.fontFamily}`,o.textBaseline="top",o.textAlign="left";const h=0===r.value.length,d=h?r.placeholder:r.password?"●".repeat(r.value.length):r.value,f=h?r.placeholderColor:r.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*r.fontSize),g=r.padding;if(r.multiline){const e=ks(o,d,l-2*g);let t=g;for(const n of e)o.fillText(n,g,t),t+=p}else{const e=(c-r.fontSize)/2;o.fillText(d,g,e)}if(r.focused&&a){const e=r.password?"●".repeat(r.cursorPos):r.value.substring(0,r.cursorPos);let t,n,s;if(r.multiline){const e=ks(o,r.value,l-2*g);let i=0,a=0,c=0;for(let t=0;t<e.length;t++){const n=e[t].length;if(i+n>=r.cursorPos){a=t,c=r.cursorPos-i;break}i+=n,t<e.length-1&&i<r.value.length&&"\n"===r.value[i]&&i++,a=t+1,c=0}const u=a<e.length?e[a].substring(0,c):"";t=g+o.measureText(u).width,n=g+a*p,s=p}else t=g+o.measureText(e).width,n=(c-r.fontSize)/2,s=r.fontSize;o.fillStyle=`rgba(${Math.round(255*r.color.r)}, ${Math.round(255*r.color.g)}, ${Math.round(255*r.color.b)}, ${r.color.a})`,o.fillRect(t,n,2,s)}o.restore();const y=o.getImageData(0,0,l,c),m=new Uint8Array(y.data.buffer),_=t.getResourceManager(),x=t._malloc(m.length);t.HEAPU8.set(m,x);const w=s.get(e);void 0!==w&&_.releaseTexture(w);const v=_.createTexture(l,c,x,m.length,1,!0);s.set(e,v),t._free(x);const b=n.get(e,oe);b.texture=v,b.size.x=l,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,oe,b)}e.addSystemToSchedule(ze.Update,$e([Se(Ri)],e=>{const t=n.getEntitiesWithComponents([Ei]);for(const e of t)Ws(n,e,Ti,{tabIndex:0,isFocused:!1}),Ws(n,e,ui,{enabled:!0,blockRaycast:!0});const s=f();if(s!==b){if(null!==b&&n.valid(b)&&n.has(b,Ei)){const e=n.get(b,Ei);e.focused=!1,e.dirty=!0,d.blur()}null!==s&&function(e){const t=n.get(e,Ei);t.readOnly||(t.focused=!0,t.dirty=!0,d.value=t.value,d.selectionStart=t.cursorPos,d.selectionEnd=t.cursorPos,d.focus(),v())}(s),b=s}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(ze.PreUpdate,$e([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===c?0:(e-c)/1e3;c=e,i=Math.min(i,.1);const o=f();if(null!==o&&(l+=i,l>=.5)){l-=.5,a=!a;n.get(o,Ei).dirty=!0}const r=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Ei)||(r.releaseTexture(t),s.delete(e));const u=n.getEntitiesWithComponents([Ei,Ps]);for(const e of u){const t=n.get(e,Ei);if(!t.dirty)continue;const s=n.get(e,Ps),i=Math.ceil(s.size.x),o=Math.ceil(s.size.y);i<=0||o<=0||(Es(n,e),S(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Ii=new Ai,Fi={Simple:0,Sliced:1,Tiled:2,Filled:3},ki={Horizontal:0,Vertical:1},Bi={Left:0,Right:1,Bottom:2,Top:3},zi=j("Image",{texture:A,color:{r:1,g:1,b:1,a:1},imageType:Fi.Simple,fillMethod:ki.Horizontal,fillOrigin:Bi.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Ui=Hs({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,layer:e=>e.image.layer,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?Us(e.uiRect):0,rectHeight:e=>e.uiRect?$s(e.uiRect):0,enabled:e=>e.image.enabled});const $i=new class{build(e){K("Image",zi);const t=e.world,n=new Map;e.addSystemToSchedule(ze.PreUpdate,$e([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,zi)||n.delete(e);const e=t.getEntitiesWithComponents([zi]);for(const s of e){const e=t.get(s,zi),i=t.has(s,Ps)?t.get(s,Ps):null,o={image:e,uiRect:i},r=n.get(s);if(r&&!Ui.changed(r,o))continue;Es(t,s);const a=t.get(s,oe);if(e.enabled){if(a.texture=e.texture,a.color.r=e.color.r,a.color.g=e.color.g,a.color.b=e.color.b,a.color.a=e.color.a,a.layer=e.layer,a.material=e.material,i&&(a.size.x=Us(i),a.size.y=$s(i)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Fi.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===ki.Horizontal?e.fillOrigin===Bi.Left?(a.uvScale.x=t,a.size.x=n*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=n*t):e.fillOrigin===Bi.Bottom?(a.uvScale.y=t,a.size.y=s*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=s*t)}else e.imageType===Fi.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale.x=a.size.x/e.tileSize.x,a.uvScale.y=a.size.y/e.tileSize.y);t.insert(s,oe,a),n.set(s,Ui.take(o))}else a.color.a=0,t.insert(s,oe,a),n.set(s,Ui.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},Di=j("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Li=j("ToggleGroup",{allowSwitchOff:!1});const Wi=new class{build(e){K("Toggle",Di),K("ToggleGroup",Li);const t=e.world,n=new Set;e.addSystemToSchedule(ze.Update,$e([Se(gi)],e=>{const s=t.getEntitiesWithComponents([Di]),i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,Di);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?s.isOn=!1:i.set(s.group,e))}const o=new Map;for(const e of s){const n=t.get(e,Di);if(0!==n.group&&t.valid(n.group)){let t=o.get(n.group);t||(t=[],o.set(n.group,t)),t.push(e)}}for(const n of s){if(Ws(t,n,ui,{enabled:!0}),!t.has(n,hi))continue;const s=t.get(n,hi),i=t.get(n,Di),r=t.get(n,ui);if(s.justPressed&&r.enabled){const s=i.group,r=0!==s&&t.valid(s)&&t.has(s,Li);if(i.isOn&&r){if(!t.get(s,Li).allowSwitchOff)continue}if(i.isOn=!i.isOn,i.isOn&&r){const i=o.get(s);if(i)for(const s of i){if(s===n)continue;const i=t.get(s,Di);i.isOn&&(i.isOn=!1,e.emit(s,"change"))}}e.emit(n,"change")}if(i.graphicEntity&&t.valid(i.graphicEntity)&&t.has(i.graphicEntity,oe)){const e=t.get(i.graphicEntity,oe);e.enabled=i.isOn,t.insert(i.graphicEntity,oe,e)}if(i.transition&&t.has(n,oe)){const e=t.get(n,oe);e.color=Is(i.transition,r.enabled,s.pressed,s.hovered),t.insert(n,oe,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},Oi=Ss,Hi=j("ProgressBar",{value:0,fillEntity:0,direction:Ss.LeftToRight});const ji=new class{build(e){K("ProgressBar",Hi);const t=e.world;e.addSystemToSchedule(ze.PreUpdate,$e([],()=>{const e=t.getEntitiesWithComponents([Hi,Ps]);for(const n of e){const e=t.get(n,Hi);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=Math.max(0,Math.min(1,e.value));As(t,e.fillEntity,e.direction,s)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}},Xi=j("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Yi=j("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}});const Ni=new class{build(e){K("Draggable",Xi),K("DragState",Yi);const t=e.world,n=e.getResource(gi);let s=null,i={x:0,y:0},o=null;e.addSystemToSchedule(ze.PreUpdate,$e([Se(Xe),Se(tt)],(e,r)=>{if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Xi,hi]);let n=null,o=-1/0,r=-1;for(const s of e){if(!t.get(s,Xi).enabled)continue;if(t.get(s,hi).hovered){let e=0;t.has(s,oe)&&(e=t.get(s,oe).layer);const i=zs(t,s);(e>o||e===o&&i>=r)&&(o=e,r=i,n=s)}}if(null!==n){s=n,i={x:a.x,y:a.y},t.has(n,Yi)||t.insert(n,Yi);const e=t.get(n,Yi),o=t.get(n,ie);e.startWorldPos={x:o.position.x,y:o.position.y},e.currentWorldPos={x:o.position.x,y:o.position.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,Yi)){t.get(s,Yi).isDragging=!1}s=null}if(null!==s&&null===o){if(!t.valid(s))return void(s=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),u=t.get(s,Xi);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=s,s=null;t.get(o,Yi).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Yi))return void(o=null);const s=t.get(o,Yi),i=t.get(o,Xi),r=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+r,u=s.startWorldPos.y+l;const h=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,o=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:i,y:o}}(i,s,c,u);c=h.x,u=h.y;const d=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-d,y:u-f},s.currentWorldPos={x:c,y:u},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:u-s.startWorldPos.y},t.has(o,se)){const e=function(e,t,n,s){if(!e.has(t,ce))return{x:n,y:s};const i=e.get(t,ce).entity;if(!e.valid(i)||!e.has(i,ie))return{x:n,y:s};const o=e.get(i,ie),r=0!==o.scale.x?o.scale.x:1,a=0!==o.scale.y?o.scale.y:1,l=si(o.rotation.z,o.rotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(n*u-s*c)/r,y:(n*c+s*u)/a}}(t,o,s.deltaWorld.x,s.deltaWorld.y),n=t.get(o,se);n.position.x+=e.x,n.position.y+=e.y,t.insert(o,se,n)}n.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},Vi=j("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135});const Gi=new class{build(e){K("ScrollView",Vi);const t=e.world,n=new Map;let s=0;e.addSystemToSchedule(ze.PreUpdate,$e([Se(Xe),Se(tt)],(e,i)=>{const o=performance.now()/1e3,r=s>0?Math.min(o-s,.05):0;if(s=o,!i.valid)return;for(const[e]of n)t.valid(e)||n.delete(e);const a={x:i.worldMouseX,y:i.worldMouseY},l=t.getEntitiesWithComponents([Vi,Ps]);for(const s of l){Ws(t,s,ui,{enabled:!0,blockRaycast:!0}),Ws(t,s,Qs,{enabled:!0,mode:"scissor"});const i=t.get(s,Vi),o=t.get(s,Ps);let l=n.get(s);l||(l={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0},n.set(s,l));const c=t.has(s,hi)?t.get(s,hi):null;if(c?.justPressed&&(l.isDragging=!0,l.lastWorldX=a.x,l.lastWorldY=a.y,l.velocityX=0,l.velocityY=0),l.isDragging&&e.isMouseButtonDown(0)){const e=a.x-l.lastWorldX,t=a.y-l.lastWorldY;if(i.horizontalEnabled){i.scrollX-=e;const t=r>0?-e/r:0;l.velocityX=.8*l.velocityX+.2*t}if(i.verticalEnabled){i.scrollY-=t;const e=r>0?-t/r:0;l.velocityY=.8*l.velocityY+.2*e}l.lastWorldX=a.x,l.lastWorldY=a.y}if(l.isDragging&&e.isMouseButtonReleased(0)&&(l.isDragging=!1),c?.hovered){const t=e.getScrollDelta();i.verticalEnabled&&0!==t.y&&(i.scrollY+=.1*t.y,l.velocityY=0),i.horizontalEnabled&&0!==t.x&&(i.scrollX+=.1*t.x,l.velocityX=0)}if(!l.isDragging&&i.inertia&&r>0){const e=Math.pow(i.decelerationRate,60*r);i.horizontalEnabled&&Math.abs(l.velocityX)>.1?(i.scrollX+=l.velocityX*r,l.velocityX*=e):l.velocityX=0,i.verticalEnabled&&Math.abs(l.velocityY)>.1?(i.scrollY+=l.velocityY*r,l.velocityY*=e):l.velocityY=0}const u=Us(o),h=$s(o),d=Math.max(0,i.contentWidth-u),f=Math.max(0,i.contentHeight-h),p=i.scrollX,g=i.scrollY;if(i.scrollX=Math.max(0,Math.min(i.scrollX,d)),i.scrollY=Math.max(0,Math.min(i.scrollY,f)),i.scrollX!==p&&(l.velocityX=0),i.scrollY!==g&&(l.velocityY=0),0!==i.contentEntity&&t.valid(i.contentEntity)&&t.has(i.contentEntity,se)){const e=t.get(i.contentEntity,se);e.position.x=-i.scrollX,e.position.y=i.scrollY,t.insert(i.contentEntity,se,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UIInteractionSystem"]})}},qi=Ss,Ji=j("Slider",{value:0,minValue:0,maxValue:1,direction:Ss.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});const Ki=new class{build(e){K("Slider",Ji);const t=e.world;let n=null;e.addSystemToSchedule(ze.PreUpdate,$e([Se(Xe),Se(tt),Se(gi)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const o=s.worldMouseX,r=s.worldMouseY,a=t.getEntitiesWithComponents([Ji,Ps,ie]);for(const s of a){Ws(t,s,ui,{enabled:!0,blockRaycast:!0});const a=t.get(s,Ji),l=t.get(s,Ps),c=t.get(s,ie),u=t.has(s,hi)?t.get(s,hi):null,h=a.handleEntity;if(0!==h&&t.valid(h)&&(Ws(t,h,ui,{enabled:!0,blockRaycast:!1}),t.has(h,ui))){const e=t.get(h,ui);e.blockRaycast&&(e.blockRaycast=!1,t.insert(h,ui,e))}let d=u?.justPressed??!1;if(!d&&0!==h&&t.valid(h)&&t.has(h,hi)){d=t.get(h,hi).justPressed}if(d&&(n=s),n===s&&e.isMouseButtonDown(0)){const e=Us(l),n=$s(l),u=e*c.scale.x,h=n*c.scale.y,d=si(c.rotation.z,c.rotation.w),f=Math.sin(-d),p=Math.cos(-d),g=o-c.position.x,y=r-c.position.y,m=g*p-y*f,_=g*f+y*p,x=-l.pivot.x*u,w=-l.pivot.y*h;let v;switch(a.direction){case Ss.LeftToRight:v=u>0?(m-x)/u:0;break;case Ss.RightToLeft:v=u>0?1-(m-x)/u:0;break;case Ss.BottomToTop:v=h>0?(_-w)/h:0;break;case Ss.TopToBottom:v=h>0?1-(_-w)/h:0}v=Math.max(0,Math.min(1,v));let b=a.minValue+v*(a.maxValue-a.minValue);a.wholeNumbers&&(b=Math.round(b));const S=a.value;a.value=Math.max(a.minValue,Math.min(a.maxValue,b)),t.insert(s,Ji,a),a.value!==S&&i.emit(s,"change")}n===s&&e.isMouseButtonReleased(0)&&(n=null);const f=a.maxValue-a.minValue,p=f>0?(a.value-a.minValue)/f:0,g=Us(l),y=$s(l),m=l.pivot,_={left:-m.x*g,bottom:-m.y*y,right:(1-m.x)*g,top:(1-m.y)*y};if(0!==a.fillEntity&&t.valid(a.fillEntity)&&(As(t,a.fillEntity,a.direction,p),Os(t,a.fillEntity,_,0,0)),0!==a.handleEntity&&t.valid(a.handleEntity)){if(t.has(a.handleEntity,Ps)){const e=t.get(a.handleEntity,Ps);switch(e.offsetMin={x:0,y:0},e.offsetMax={x:0,y:0},a.direction){case Ss.LeftToRight:e.anchorMin={x:p,y:0},e.anchorMax={x:p,y:1};break;case Ss.RightToLeft:e.anchorMin={x:1-p,y:0},e.anchorMax={x:1-p,y:1};break;case Ss.BottomToTop:e.anchorMin={x:0,y:p},e.anchorMax={x:1,y:p};break;case Ss.TopToBottom:e.anchorMin={x:0,y:1-p},e.anchorMax={x:1,y:1-p}}t.insert(a.handleEntity,Ps,e)}Os(t,a.handleEntity,_,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}};const Qi=new class{build(e){K("Focusable",Ti);const t=e.world,n=new Ci;e.insertResource(Ri,n),e.addSystemToSchedule(ze.Update,$e([Se(Xe),Se(gi)],(e,s)=>{null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([Ti]);for(const e of i){if(!t.has(e,hi))continue;t.get(e,hi).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){if(!t.valid(n))continue;if(t.has(n,ui)){if(!t.get(n,ui).enabled)continue}const s=t.get(n,Ti);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const r=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?s.length-1:0:a?(r-1+s.length)%s.length:(r+1)%s.length,o(s[l])}function o(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Ti)){t.get(i,Ti).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,Ti).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},Zi=j("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function eo(){return i()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:n,screenWidth:s,screenHeight:i}=t;return{top:n.top,bottom:i-n.bottom,left:n.left,right:s-n.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}const to=new class{build(e){K("SafeArea",Zi);const t=e.world;let n=eo(),s=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=eo(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=eo(),s=!0});e.addSystemToSchedule(ze.PreUpdate,$e([Se(tt)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===r||(o=e.screenH,r=a,s=!0),!s)return;s=!1;const l="undefined"!=typeof window&&window.devicePixelRatio||1,c=i()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([Zi,Ps]);for(const e of u){const s=t.get(e,Zi),i=t.get(e,Ps),o=s.applyTop?n.top*c:0,r=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let u=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},u=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,Ps,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},no=j("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let so=null;function io(e,t){if(!so)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=so.get(e);n?n.renderer=t:so.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const oo=new class{build(e){K("ListView",no);const t=e.world,n=new Map;so=n,e.addSystemToSchedule(ze.PreUpdate,$e([Se(Xe)],e=>{for(const[e,s]of n)if(!t.valid(e)){for(const e of s.itemEntities.values())t.valid(e)&&t.despawn(e);n.delete(e)}const s=t.getEntitiesWithComponents([no,Ps]);for(const i of s){Ws(t,i,ui,{enabled:!0,blockRaycast:!0}),Ws(t,i,Qs,{enabled:!0,mode:"scissor"});let s=n.get(i);s||(s={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(i,s));const o=t.get(i,no),r=t.get(i,Ps),a=r._computedHeight??r.size.y,l=r._computedWidth??r.size.x,c=t.has(i,hi)?t.get(i,hi):null;if(c?.hovered){const t=e.getScrollDelta();0!==t.y&&(o.scrollY+=.1*t.y)}const u=Math.max(0,o.itemCount*o.itemHeight-a);o.scrollY=Math.max(0,Math.min(o.scrollY,u));const h=Math.max(0,Math.floor(o.scrollY/o.itemHeight)-o.overscan),d=Math.min(o.itemCount,Math.ceil((o.scrollY+a)/o.itemHeight)+o.overscan);for(const[e,n]of s.itemEntities)(e<h||e>=d)&&(t.valid(n)&&t.despawn(n),s.itemEntities.delete(e));for(let e=h;e<d;e++){let n=s.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,fe,{value:`ListItem_${e}`}),t.insert(n,Ps,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:l,y:o.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,i),s.itemEntities.set(e,n),s.renderer&&s.renderer(e,n)),t.has(n,se)){const s=t.get(n,se);s.position.y=-(e*o.itemHeight-o.scrollY),t.insert(n,se,s)}}s.visibleStart=h,s.visibleEnd=d}},{name:"ListViewSystem"}))}},ro=j("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const ao=new class{build(e){K("Dropdown",ro);const t=e.world,n=new Map;function s(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;l(i,!0),t.has(i,Qs)||t.insert(i,Qs,{enabled:!0,mode:"scissor"}),a(s);const o=t.has(i,Ps)?t.get(i,Ps):null,r=o?o.size.x:160;for(let e=0;e<n.options.length;e++){const o=t.spawn();t.insert(o,fe,{value:`Option_${e}`}),t.insert(o,Ps,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:30},pivot:{x:.5,y:1}}),t.insert(o,se,{position:{x:0,y:-30*e,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(o,Vs,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:1,g:1,b:1,a:1},align:Xs.Left,verticalAlign:Ys.Middle,wordWrap:!1,overflow:Ns.Clip,lineHeight:1.2}),t.insert(o,oe,{texture:0,color:{r:1,g:1,b:1,a:0},size:{x:r,y:30},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,ui,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),s.optionEntities.push(o)}o&&(o.size.y=30*n.options.length,t.insert(i,Ps,o)),c(s)}function i(e,t,n){t.isOpen=!1,a(n),l(t.listEntity,!1)}function o(e,t,n,s,o){t.selectedIndex=s,i(0,t,n),o.emit(e,"change")}function r(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,Vs))return;const s=t.get(n,Vs),i=e.selectedIndex>=0&&e.selectedIndex<e.options.length?e.options[e.selectedIndex]:"";s.content!==i&&(s.content=i,t.insert(n,Vs,s))}function a(e){for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[]}function l(e,n){if(0!==e&&t.valid(e)){if(t.has(e,ui)){const s=t.get(e,ui);s.enabled=n,t.insert(e,ui,s)}if(t.has(e,oe)){const s=t.get(e,oe);s.enabled=n,t.insert(e,oe,s)}}}function c(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s)||!t.has(s,oe))continue;const i=t.get(s,oe);n===e.highlightIndex?i.color={...js}:i.color={r:1,g:1,b:1,a:0},t.insert(s,oe,i)}}function u(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,hi))continue;if(t.get(n,hi).hovered)return!0}return!1}e.addSystemToSchedule(ze.Update,$e([Se(Xe),Se(gi)],(e,a)=>{for(const[e]of n)t.valid(e)||n.delete(e);const l=t.getEntitiesWithComponents([ro]);for(const h of l){Ws(t,h,ui,{enabled:!0,blockRaycast:!0});const l=t.get(h,ro),d=t.has(h,hi)?t.get(h,hi):null;let f=n.get(h);if(f||(f={optionEntities:[],highlightIndex:-1},n.set(h,f)),d?.justPressed&&(l.isOpen?i(h,l,f):s(h,l,f)),l.isOpen){for(let e=0;e<f.optionEntities.length;e++){const n=f.optionEntities[e];if(!t.valid(n)||!t.has(n,hi))continue;if(t.get(n,hi).justPressed){o(h,l,f,e,a);break}}e.isKeyPressed("ArrowDown")?(f.highlightIndex>=l.options.length-1?f.highlightIndex=0:f.highlightIndex++,c(f)):e.isKeyPressed("ArrowUp")?(f.highlightIndex<=0?f.highlightIndex=l.options.length-1:f.highlightIndex--,c(f)):e.isKeyPressed("Enter")&&f.highlightIndex>=0?o(h,l,f,f.highlightIndex,a):e.isKeyPressed("Escape")&&i(h,l,f),e.isMouseButtonPressed(0)&&(d?.hovered||u(f)||i(h,l,f))}r(l)}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},lo=0,co=0,uo=2,ho=j("LayoutGroup",{direction:lo,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:co,reverseOrder:!1});const fo=new class{build(e){K("LayoutGroup",ho);const t=e.world;e.addSystemToSchedule(ze.PreUpdate,$e([],()=>{const e=t.getEntitiesWithComponents([ho,Ps,ue]);for(const n of e){const e=t.get(n,ho),s=t.get(n,Ps),i=t.get(n,ue);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,Ps)&&t.has(e,se)&&o.push({entity:e,rect:t.get(e,Ps)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=s._computedWidth??s.size.x,a=s._computedHeight??s.size.y,l=s.pivot.x,c=s.pivot.y,u=e.padding,h=e.direction===lo;let d=0;for(let n=0;n<o.length;n++){const s=o[n],i=s.rect._computedWidth??s.rect.size.x,f=s.rect._computedHeight??s.rect.size.y,p=s.rect.pivot.x,g=s.rect.pivot.y;let y,m;h?(y=-l*r+u.left+d+p*i,m=e.childAlignment===co?(1-c)*a-u.top-(1-g)*f:e.childAlignment===uo?-c*a+u.bottom+g*f:(.5-c)*a+.5*(u.bottom-u.top)+(g-.5)*f,d+=i,n<o.length-1&&(d+=e.spacing)):(y=e.childAlignment===co?-l*r+u.left+p*i:e.childAlignment===uo?(1-l)*r-u.right-(1-p)*i:(.5-l)*r+.5*(u.left-u.right)+(p-.5)*i,m=(1-c)*a-u.top-d-(1-g)*f,d+=f,n<o.length-1&&(d+=e.spacing)),s.rect._layoutManaged=!0;const _=t.get(s.entity,se);_.position.x=y,_.position.y=m,t.insert(s.entity,se,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};function po(e,t,n){if(e.has(t,oe)&&e.has(t,Ps)){const s=e.get(t,oe);s.layer!==n&&(s.layer=n,e.insert(t,oe,s)),n++}if(!e.has(t,ue))return n;const s=e.get(t,ue);if(!s||!s.entities)return n;for(const t of s.entities)e.valid(t)&&(n=po(e,t,n));return n}const go=new class{build(e){const t=e.world;e.addSystemToSchedule(ze.PostUpdate,$e([],()=>{let e=0;const n=t.getEntitiesWithComponents([yi,Ps]);for(const s of n)e=po(t,s,e)},{name:"UIRenderOrderSystem"}))}};async function yo(e,t,n){const s=e.getResource(rs);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function mo(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 _o=be({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),xo=be(null,"PhysicsAPI");function wo(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function vo(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class bo{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(_o,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=mo(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const i=function(e){const t=e.world.getEntitiesWithComponents([ae]);for(const n of t){const t=e.world.get(n,ae);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/i,r=e.world;e.addSystemToSchedule(ze.PostUpdate,$e([Se(Te)],a=>{const l=r.getEntitiesWithComponents([ye,se,ie]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,ye),l=r.get(i,ie);if(t.has(i)){const e=n.get(i);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(i,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const r=wo(l.rotation);s._physics_createBody(i,a.bodyType,l.position.x*o,l.position.y*o,r,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),So(e,s,i),t.add(i),n.set(i,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===we.Kinematic){const e=wo(l.rotation);s._physics_setBodyTransform(i,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 i=t._physics_getDynamicBodyTransforms(),o=i>>2;for(let i=0;i<s;i++){const s=o+4*i,r=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(r))continue;const u=e.world.get(r,se);if(!u)continue;let h=a,d=l,f=c;if(e.world.has(r,ce)){const t=e.world.get(r,ce);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ie)){const n=e.world.get(t.entity,ie),s=wo(n.rotation),i=a-n.position.x,o=l-n.position.y,r=Math.cos(-s),u=Math.sin(-s);h=(i*r-o*u)/(0!==n.scale.x?n.scale.x:1),d=(i*u+o*r)/(0!==n.scale.y?n.scale.y:1),f=c-s}}u.position.x=h,u.position.y=d;const p=vo(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(r,se,u)}}(e,s,i),function(e,t,n){t._physics_collectEvents();const s=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<i;o++){const i=e+6*o;s.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*n,contactY:t.HEAPF32[i+5]*n})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<r;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(_o,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(xo,Mo._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function So(e,t,n){const s=e.world;if(s.has(n,me)){const e=s.get(n,me);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,_e)){const e=s.get(n,_e);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,xe)){const e=s.get(n,xe);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 Mo{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(Mo.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 Po(e,t,n=!0){const s=e.getResourceManager(),i=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,i);const o=s.createTexture(t.width,t.height,i,t.pixels.length,1,n);return e._free(i),o}function Eo(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 To(e,t,n,s){const i=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),r=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,h=a+a,d=l+l,f=c+c,p=a*h,g=a*d,y=a*f,m=l*d,_=l*f,x=c*f,w=u*h,v=u*d,b=u*f;return new Float32Array([(1-(m+x))*i,(g+b)*i,(y-v)*i,0,(g-b)*o,(1-(p+x))*o,(_+w)*o,0,(y+v)*r,(_-w)*r,(1-(p+m))*r,0,e.position.x,e.position.y,e.position.z,1])}async function Co(e,t,n,s,i,o,r,a,l){const c=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=Pt(t.type);for(const o of i){if("texture"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&void 0===s[i])try{s[i]=Po(e,await n.loadPixels(i))}catch{s[i]=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 i=n[e];if(i&&i>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(t,n,c);let u={},h=null;if(i&&(h=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(i),u=await async function(e,t,n,s,i){const o={};for(const r of s.entities)for(const s of r.components){const r=Et(s.type);if(!r||!s.data)continue;const a=s.data[r.skeletonField],l=s.data[r.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),u=i.resolvePath(l);try{const s=await i.readText(l),r="binary"===Ot(c)?.contentType;let h,d;if(r){const e=await i.readBinary(a);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=await i.readText(a),n=(new TextEncoder).encode(e);d=n.length,h=t._malloc(d+1),t.HEAPU8.set(n,h),t.HEAPU8[h+d]=0}const f=n.loadSkeleton(h,d,s,s.length,r);if(t._free(h),f<0)continue;o[a]=f;const p=Eo(s),g=u.substring(0,u.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=g+"/"+p[t];try{const o=i.loadPixelsRaw?await i.loadPixelsRaw(s):await i.loadPixels(s),r=Po(e,o,!1),a=e.getResourceManager().getTextureGLId(r);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,i,h,n,s)),o){const t={gravity:r?.gravity??{...M},fixedTimestep:r?.fixedTimestep??P,subStepCount:r?.subStepCount??4};new bo("",t,()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=Pt(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{let t,i;const r=Ot(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await n.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){s[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=Po(e,c,!1),h=e.getResourceManager();s[o]=h.loadBitmapFont(t,u,c.width,c.height)}catch{s[o]=0}}return s}(t,n,s),f=await async function(e,t){const n={},s={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Pt(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){n[o]=0;continue}const i=e.vertexSource+e.fragmentSource;let r=s[i];r||(r=ht.createShader(e.vertexSource,e.fragmentSource),s[i]=r),n[o]=ht.createFromAsset(e,r)}catch{n[o]=0}}return n}(n,s);!function(e,t,n,s){const i={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=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]=i[e.type][n[e.field]]||0)}}(n,c,d,f);const p=It(e.world,n);if(l&&e.hasResource(rs))for(const t of p.values())e.world.insert(t,pe,{scene:l,persistent:!1});if(i&&h){const s=function(e,t,n,s){const i={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const r=Et(t.type);if(!r||!t.data)continue;const a=n[t.data[r.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=s.get(o.id);void 0!==c&&(i[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return i}(h,n,u,p);!function(e,t,n,s,i){let o=0;e.setSpineRenderer((r,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=S);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,de)?c.get(o,de):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&s.update(r,l*h);let d=0;if(c.has(o,ie)){const e=To(c.get(o,ie),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=s.getMeshBatchCount(r);for(let e=0;e<f;e++){const i=s.getMeshBatchVertexCount(r,e),o=s.getMeshBatchIndexCount(r,e);if(!i||!o)continue;const a=8*i*4,l=2*o,c=n._malloc(a),u=n._malloc(l),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(r,e,c,u,h,f);const p=n.HEAPU32[h>>2],g=n.HEAPU32[f>>2],y=new Float32Array(n.HEAPF32.buffer,c,8*i),m=new Uint16Array(n.HEAPU8.buffer,u,o),_=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(y,_>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(m),t.renderer_submitTriangles(_,i,x,o,p,g,d),t._free(_),t._free(x),n._free(c),n._free(u),n._free(h),n._free(f)}d&&t._free(d)}})}(e,t,i,h,s)}if(a){const t=e.getResource(Zt);t&&t.setAddressableManifest(a)}}function Ro(e,t,n){return{name:e,data:t,async setup(){await Co(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class Ao{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Et(e.type);if(i){const s=e.data[i.skeletonField],o=e.data[i.atlasField];s&&("binary"===Ot(s)?.contentType?n.add(s):t.add(s)),o&&t.add(o)}const o=Pt(e.type);for(const n of o){const i=e.data[n.field];"string"==typeof i&&i&&("font"===n.type?(s.add(i),t.add(i)):"material"===n.type&&t.add(i))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const o=[];for(const e of s){const t=Ot(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),i=await createImageBitmap(s),o=new OffscreenCanvas(i.width,i.height).getContext("2d");o.drawImage(i,0,0);const r=o.getImageData(0,0,i.width,i.height);return i.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Io="__preview__";class Fo{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:Io,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Io),this.loadPromise_=t.load(Io).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await r(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new Ao(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await Co(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,Io)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([re]);for(const s of n){if(e.get(s,re).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([ae]);for(const i of s){const s=e.get(i,ae);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const i=this.app_.getResource(rs).getScene(Io),o=i?i.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(o,se,r);const a={isActive:!0,projectionType:ee.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:te.ColorAndDepth};e.insert(o,re,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(Io),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 ko={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Jn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Jn.getTargetTexture(n),width:e.width,height:e.height}},release(e){Jn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Jn.releaseRenderTarget(e._handle),ko.create({width:t,height:n,depth:!0})),begin(e,t){Jn.begin(t,e._handle)},end(){Jn.end()},getDepthTexture:e=>Jn.getTargetDepthTexture(e._handle)};let Bo=!1;function zo(e){Bo=e}function Uo(){return Bo}function $o(){return!Bo}var Do;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Do||(Do={}));class Lo{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Do[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Do.Debug:console.debug(t,n);break;case Do.Info:console.log(t,n);break;case Do.Warn:console.warn(t,n);break;case Do.Error:console.error(t,n)}}}class Wo{constructor(){this.handlers_=[],this.minLevel_=Do.Info,this.addHandler(new Lo)}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(Do.Debug,e,t,n)}info(e,t,n){this.log(Do.Info,e,t,n)}warn(e,t,n){this.log(Do.Warn,e,t,n)}error(e,t,n){this.log(Do.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const i={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Oo=new Wo;function Ho(){return Oo}function jo(e){Oo.setMinLevel(e)}function Xo(e,t,n){Oo.debug(e,t,n)}function Yo(e,t,n){Oo.info(e,t,n)}function No(e,t,n){Oo.warn(e,t,n)}function Vo(e,t,n){Oo.error(e,t,n)}const Go=[Ks,ci,wi,$i,ji,Pi,Ni,Gi,Ki,Wi,Ii,Qi,to,oo,ao,fo,go];function qo(e,t){return function(e,t){const n=us.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),_n(e),lt(e),zn(e),Wn(e),Gn(e),Qn(e);const i=new ts;n.setPipeline(i);let o=d();const r=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,i,o){o||(o=ps(e,s,t,i));const r=n.getResource(tt);if(o.length>0){const e=o[0],n=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(n.x*t),r.vpY=Math.round((1-n.y-n.h)*i),r.vpW=Math.round(n.w*t),r.vpH=Math.round(n.h*i),r.screenW=t,r.screenH=i,r.worldLeft=e.cameraX-e.halfW,r.worldRight=e.cameraX+e.halfW,r.worldBottom=e.cameraY-e.halfH,r.worldTop=e.cameraY+e.halfH,r.valid=!0}else r.valid=!1}n.insertResource(tt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=r();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;Jn.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-o)/1e3;let h;if(Jn.resize(t,l),jn.isInitialized()&&jn.getPassCount()>0&&!jn.isBypassed()&&jn.resize(t,l),n.hasResource(rs)){const e=n.getResource(rs).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=ps(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:ds,width:t,height:l,elapsed:u});else{for(const e of f){const n=e.viewportRect,o=Math.round(n.x*t),r=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);i.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:u})}Jn.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(ze.First,l),n.addSystemToSchedule(ze.Last,c),n.addPlugin(tn),n.addPlugin(dn),n.addPlugin(Ne),n.addPlugin(cs),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Go,...t})}e=f;export{us as App,en as AssetPlugin,nn as AssetRefCounter,Qt as AssetServer,Zt as Assets,wt as AsyncCache,he as BitmapText,nt as BlendMode,we as BodyType,me as BoxCollider,fi as Button,di as ButtonState,re as Camera,ae as Canvas,xe as CapsuleCollider,ue as Children,_e as CircleCollider,te as ClearFlags,Fe as Commands,Be as CommandsInstance,g as DEFAULT_DESIGN_HEIGHT,p as DEFAULT_DESIGN_WIDTH,S as DEFAULT_FALLBACK_DT,P as DEFAULT_FIXED_TIMESTEP,x as DEFAULT_FONT_FAMILY,w as DEFAULT_FONT_SIZE,M as DEFAULT_GRAVITY,v as DEFAULT_LINE_HEIGHT,b as DEFAULT_MAX_DELTA_TIME,y as DEFAULT_PIXELS_PER_UNIT,E as DEFAULT_SPINE_SKIN,_ as DEFAULT_SPRITE_SIZE,m as DEFAULT_TEXT_CANVAS_SIZE,An as DataType,Yi as DragState,Xi as Draggable,bn as Draw,ro as Dropdown,ke as EntityCommands,Ss as FillDirection,ki as FillMethod,Bi as FillOrigin,Ri as FocusManager,Ci as FocusManagerState,Ti as Focusable,es as GLDebug,Dn as Geometry,R as INVALID_ENTITY,I as INVALID_FONT,F as INVALID_MATERIAL,A as INVALID_TEXTURE,zi as Image,Fi as ImageType,Xe as Input,Ye as InputPlugin,je as InputState,ui as Interactable,no as ListView,se as LocalTransform,Do as LogLevel,Wo as Logger,ht as Material,vt as MaterialLoader,Ce as Mut,fe as Name,ce as Parent,Mo as Physics,_o as PhysicsEvents,bo as PhysicsPlugin,jn as PostProcess,cn as PrefabServer,un as Prefabs,hn as PrefabsPlugin,Fo as PreviewPlugin,Hi as ProgressBar,Oi as ProgressBarDirection,ee as ProjectionType,Ae as Query,Ie as QueryInstance,ts as RenderPipeline,Yn as RenderStage,ko as RenderTexture,Jn as Renderer,Se as Res,Me as ResMut,ye as RigidBody,T as RuntimeConfig,Zi as SafeArea,ne as ScaleMode,rs as SceneManager,os as SceneManagerState,pe as SceneOwner,ze as Schedule,yi as ScreenSpace,Vi as ScrollView,xt as ShaderSources,Ji as Slider,qi as SliderDirection,de as SpineAnimation,oe as Sprite,He as SystemRunner,Vs as Text,Xs as TextAlign,Ei as TextInput,Ai as TextInputPlugin,Ns as TextOverflow,Js as TextPlugin,Gs as TextRenderer,Ys as TextVerticalAlign,Te as Time,Di as Toggle,tt as UICameraInfo,pi as UIEventQueue,gi as UIEvents,hi as UIInteraction,Mi as UIInteractionPlugin,xi as UILayoutPlugin,Qs as UIMask,li as UIMaskPlugin,Ps as UIRect,le as Velocity,Ao as WebAssetProvider,et as World,ie as WorldTransform,We as addStartupSystem,Le as addSystem,Oe as addSystemToSchedule,As as applyDirectionalFill,C as applyRuntimeConfig,tn as assetPlugin,Rn as clearDrawCallbacks,N as clearUserComponents,U as color,Ts as computeFillAnchors,Rs as computeFillSize,Cs as computeHandleAnchors,Ms as computeUIRectLayout,ai as createMaskProcessor,Ro as createRuntimeSceneConfig,qo as createWebApp,Xo as debug,j as defineComponent,be as defineResource,$e as defineSystem,X as defineTag,Vo as error,zt as findEntityByName,hs as flushPendingSystems,jt as getAddressableType,Xt as getAddressableTypeByEditorType,Nt as getAllAssetExtensions,Jt as getAssetMimeType,Ot as getAssetTypeEntry,Q as getComponent,Mt as getComponentAssetFields,ge as getComponentDefaults,Gt as getCustomExtensions,Ht as getEditorType,Ho as getLogger,t as getPlatform,s as getPlatformType,Y as getUserComponent,qt as getWeChatPackOptions,Yo as info,_n as initDrawAPI,Qn as initGLDebugAPI,zn as initGeometryAPI,lt as initMaterialAPI,Wn as initPostProcessAPI,Gn as initRendererAPI,Ne as inputPlugin,on as instantiatePrefab,Zs as intersectRects,ei as invertMatrix4,q as isBuiltinComponent,Kt as isCustomExtension,Uo as isEditor,Yt as isKnownAssetExtension,n as isPlatformInitialized,$o as isRuntime,st as isTextureRef,i as isWeChat,o as isWeb,kt as loadComponent,mo as loadPhysicsModule,Co as loadRuntimeScene,It as loadSceneData,Ft as loadSceneWithAssets,Vt as looksLikeAssetPath,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,oi as pointInOBB,ni as pointInWorldRect,dn as prefabsPlugin,$ as quat,K as registerComponent,St as registerComponentAssetFields,Ct as registerComponentEntityFields,Tn as registerDrawCallback,sn as registerEmbeddedAssets,_t as registerMaterialCallback,cs as sceneManagerPlugin,ti as screenToWorld,zo as setEditorMode,io as setListViewRenderer,jo as setLogLevel,Ke as setWasmErrorHandler,xn as shutdownDrawAPI,Zn as shutdownGLDebugAPI,Un as shutdownGeometryAPI,ct as shutdownMaterialAPI,On as shutdownPostProcessAPI,qn as shutdownRendererAPI,Ds as syncFillSpriteSize,Ii as textInputPlugin,Ks as textPlugin,yo as transitionTo,Pi as uiInteractionPlugin,wi as uiLayoutPlugin,ci as uiMaskPlugin,Go as uiPlugins,V as unregisterComponent,Cn as unregisterDrawCallback,Bt as updateCameraAspectRatio,k as vec2,B as vec3,z as vec4,No as warn,as 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 o(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function r(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}function f(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}const p=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),o=t=>e.onKeyUp(t.code),i=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},r=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},u=()=>{e.onPointerUp(0)},h=t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)};document.addEventListener("keydown",s),document.addEventListener("keyup",o),n.addEventListener("mousemove",i),n.addEventListener("mousedown",r),document.addEventListener("mouseup",a),n.addEventListener("touchstart",l),n.addEventListener("touchmove",c),n.addEventListener("touchend",u),n.addEventListener("wheel",h),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",o),n.removeEventListener("mousemove",i),n.removeEventListener("mousedown",r),document.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",u),n.removeEventListener("wheel",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},g=1920,y=1080,m=100,_=512,x={x:100,y:100},w="Arial",v=24,b=1.2,S=.5,M=1/60,P={x:0,y:-9.81},E=1/60,T="default",C={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function R(e){e.Text&&(e.Text._default.fontFamily=C.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=C.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=C.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=C.canvasMatchWidthOrHeight)}const A=0,I=4294967295,F=4294967295,k=0,B=(e=0,t=0)=>({x:e,y:t}),z=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),U=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),$=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),D=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function L(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(L);const t={};for(const n in e)t[n]=L(e[n]);return t}let W=0;function O(e,t){const n=++W;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...L(t),...e}:L(t)}}const H=new Map;function j(){return"undefined"==typeof window?H:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function X(e,t){const n=K.get(e)??j().get(e);if(n)return n;const s=O(e,t);return j().set(e,s),K.set(e,s),q(e,t,!1),s}function Y(e){const t=K.get(e)??j().get(e);if(t)return t;const n=O(e,{});return j().set(e,n),K.set(e,n),q(e,{},!0),n}function V(e){return j().get(e)}function N(){const e=j();for(const t of e.keys())K.delete(t);e.clear()}function G(e){j().delete(e),K.delete(e)}function q(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function J(e){return!0===e._builtin}const K=new Map;function Q(e,t){K.set(e,t)}function Z(e){return K.get(e)??V(e)}function ee(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return K.set(e,n),n}const te={Perspective:0,Orthographic:1},ne={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},se={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},oe=ee("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),ie=ee("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),re=ee("Sprite",{texture:I,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}),ae=ee("Camera",{projectionType:te.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:ne.ColorAndDepth}),le=ee("Canvas",{designResolution:{x:g,y:y},pixelsPerUnit:100,scaleMode:se.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),ce=ee("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),ue=ee("Parent",{entity:0}),he=ee("Children",{entities:[]}),de=ee("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:F,enabled:!0}),fe=ee("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}),pe={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},ge=X("SceneOwner",{scene:"",persistent:!1});function ye(e){const t=Z(e);return t?L(t._default):null}Q("Name",pe);const me=ee("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),_e=ee("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),xe=ee("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),we=ee("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ve={Static:0,Kinematic:1,Dynamic:2};let be=0;function Se(e,t){const n=++be;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function Me(e){return{_type:"res",_resource:e}}function Pe(e){return{_type:"res_mut",_resource:e}}class Ee{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 Te{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 Ee(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Ce=Se({delta:0,elapsed:0,frameCount:0},"Time");function Re(e){return{_type:"mut",_component:e}}function Ae(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Ie(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{Ae(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class Fe{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>Ae(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),o=n.length,i=e.length>0,r=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let u=null;this.world_.beginIteration();try{for(const h of s){if(null!==u&&i)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}if(r){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(h,t[n])){e=!0;break}if(e)continue}a[0]=h;for(let e=0;e<o;e++)a[e+1]=this.world_.get(h,n[e]);if(i){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=h}yield a}}finally{if(this.world_.endIteration(),null!==u&&i)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...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 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=J(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 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 Ue;!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"}(Ue||(Ue={}));let $e=0;function De(e,t,n){const s=++$e;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Le(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function We(e){Le().push({schedule:Ue.Update,system:e})}function Oe(e){Le().push({schedule:Ue.Startup,system:e})}function He(e,t){Le().push({schedule:e,system:t})}class je{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 Fe(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 Xe{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 Ye=Se(new Xe,"Input");class Ve{constructor(e){this.target_=e??null}build(e){const n=new Xe;e.insertResource(Ye,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(Ue.Last,De([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Ne=new Ve;function Ge(e,t,n){const s=[];for(const[e,o]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:o});continue}const n=qe(t[e]),i=qe(o);"null"!==n&&"undefined"!==n&&(n!==i&&null!=o&&s.push({field:e,expected:n,actual:i,value:o}))}return s}function qe(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Je(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 Ke=null;function Qe(e){Ke=e}function Ze(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Ke&&Ke(e,t)}function et(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}:et(e)}}return t}class tt{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,this.nextEntityId_=0}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw Ze(e,"spawn"),e}else e=++this.nextEntityId_;return this.entities_.add(e),this.worldVersion_++,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){Ze(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){Ze(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Ze(t,`removeParent(entity=${e})`)}}insert(e,t,n){return J(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return J(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return J(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(J(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return Ze(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.");J(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_,s=n[`add${e}`],o=n[`get${e}`],i=n[`has${e}`],r=n[`remove${e}`];if("function"!=typeof s||"function"!=typeof o||"function"!=typeof i||"function"!=typeof r)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:s.bind(n),get:o.bind(n),has:i.bind(n),remove:r.bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const e=Ge(t._name,t._default,s);if(e.length>0)throw new Error(Je(t._name,e))}const o={...t._default,...s};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,et(o))}catch(n){Ze(n,`insertBuiltin(${t._name}, entity=${e})`)}return this.worldVersion_++,o}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return this.getBuiltinMethods(t._cppName).get(e)}catch(n){return Ze(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 Ze(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){Ze(n,`removeBuiltin(${t._name}, entity=${e})`)}this.worldVersion_++}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const o=Ge(t._name,t._default,e);if(o.length>0)throw new Error(Je(t._name,o));s=e}const o=t.create(s);this.getStorage(t).set(e,o),this.worldVersion_++;let i=this.entityComponents_.get(e);return i||(i=[],this.entityComponents_.set(e,i)),-1===i.indexOf(t._id)&&i.push(t._id),o}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}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 K)if(J(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=j();for(const s of n)for(const[n,o]of e)if(o._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 o=this.queryCache_.get(s);if(o&&o.version===this.worldVersion_)return o.result;let i=null,r=1/0;for(const t of e)if(!J(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<r&&(r=n,i=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const l=i?i.keys():this.entities_;for(const t of l){let 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.slice()}),a}}const nt=Se({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var st;function ot(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"}(st||(st={}));let it=null,rt=null,at=1;const lt=new Map;function ct(e){it=e,rt=e.getResourceManager(),xt()}function ut(){0!==pt&&it&&(it._free(pt),pt=0),lt.clear(),at=1,ft=!1,yt.clear(),mt=null,rt=null,it=null}function ht(){if(!rt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return rt}const dt={createShader:(e,t)=>ht().createShader(e,t),releaseShader(e){e>0&&ht().releaseShader(e)},create(e){const t=at++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??st.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 lt.set(t,n),t},get:e=>lt.get(e),setUniform(e,t,n){const s=lt.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=lt.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=lt.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=lt.get(e);return t?.blendMode??st.Normal},setDepthTest(e,t){const n=lt.get(e);n&&(n.depthTest=t)},getShader(e){const t=lt.get(e);return t?.shader??0},release(e){lt.delete(e)},isValid:e=>lt.has(e),releaseAll(){lt.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??st.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=lt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=at++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return lt.set(n,s),n},toAssetData(e,t){const n=lt.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=lt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let ft=!1,pt=0;const gt=4096,yt=new Map;let mt=null;function _t(e){const t=(0===pt&&it&&(pt=it._malloc(gt)),pt);if(0===t||!it)return{ptr:0,count:0};let n=0,s=0;const o=it.HEAPU8,i=it.HEAPU32,r=it.HEAPF32;for(const[a,l]of e){if(n+128>gt)break;let e=yt.get(a);e||(mt||(mt=new TextEncoder),e=mt.encode(a),yt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);i[t+n>>2]=c,n+=4,o.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);i[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)r[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function xt(){if(!it||ft)return;it.materialDataProvider=(e,t,n,s,o)=>{const i=lt.get(e);if(!i)return it.HEAPU32[t>>2]=0,it.HEAPU32[n>>2]=0,it.HEAPU32[s>>2]=0,void(it.HEAPU32[o>>2]=0);it.HEAPU32[t>>2]=i.shader,it.HEAPU32[n>>2]=i.blendMode;const{ptr:r,count:a}=_t(i.uniforms);it.HEAPU32[s>>2]=r,it.HEAPU32[o>>2]=a},ft=!0}const wt={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 vt{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 o=this.pending_.get(e);if(o&&!o.aborted)return o.promise;const i={promise:null,aborted:!1};i.promise=(async()=>{const s=t(),o=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{i.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return i.aborted||this.cache_.set(e,o),this.pending_.delete(e),o})(),this.pending_.set(e,i);try{return await i.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class bt{constructor(e,t=""){this.cache_=new vt,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&&(dt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())dt.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 o=this.resolveShaderPath(e,s.shader),i=await this.shaderLoader_.load(o);return{handle:dt.createFromAsset(s,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}const St=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 Mt(e,t){St.set(e,t)}function Pt(e){const t=St.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 Et(e){return St.get(e)?.fields??[]}function Tt(e){return St.get(e)?.spine??null}const Ct=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Rt(e,t){Ct.set(e,t)}function At(e,t){const n=Ct.get(e.type);if(!n)return;const s=e.data;for(const e of n){const n=s[e];if("number"==typeof n&&0!==n){const o=t.get(n);s[e]=void 0!==o?o:0}}}function It(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();n.set(s.id,t),e.insert(t,pe,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;const t=n.get(s.id);for(const o of s.components)At(o,n),zt(e,t,o,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),o=n.get(s.parent);void 0!==t&&void 0!==o&&e.setParent(t,o)}return n}function Ft(e,t){return It(e,t)}async function kt(e,t,n){const s=n?.assetServer,o=n?.assetBaseUrl,i=new Map;s&&await async function(e,t,n,s){e=JSON.parse(JSON.stringify(e));const o=new Map;for(const e of Bt.keys())o.set(e,new Set);const i=[],r=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=St.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}`;r.has(t)||(r.add(t),i.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const a=new Map,l=[...Bt.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,n,s);a.set(e,r)}),c=i.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});await Promise.all([...l,...c]);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=St.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&(n[e.field]=a.get(e.type)?.get(t)??0)}}}(t,s,o,i);const r=It(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}const Bt=new Map([["texture",{async load(e,t,n,s){const o=new Map,i=[...e].map(async e=>{try{const i=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(i);o.set(e,r.handle),s.set(e,i)}catch(t){console.warn(`Failed to load texture: ${e}`,t),o.set(e,0)}});return await Promise.all(i),o}}],["material",{async load(e,t,n){const s=new Map,o=[...e].map(async e=>{try{const o=await t.loadMaterial(e,n);s.set(e,o.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(o),s}}],["font",{async load(e,t,n){const s=new Map,o=[...e].map(async e=>{try{const o=await t.loadBitmapFont(e,n);s.set(e,o)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(o),s}}]]);function zt(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 o=Z(n.type);if(o)e.insert(t,o,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function Ut(e,t){const n=e.getEntitiesWithComponents([ae]);for(const s of n){const n=e.get(s,ae);n&&(n.aspectRatio=t,e.insert(s,ae,n))}}function $t(e,t){const n=e.getEntitiesWithComponents([pe]);for(const s of n){const n=e.get(s,pe);if(n&&n.value===t)return s}return null}const Dt=[{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}],Lt={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"},Wt=new Map,Ot=new Set;for(const e of Dt)for(const t of e.extensions)Wt.set(t,e),Ot.add(t);function Ht(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function jt(e){return Wt.get(Ht(e))}function Xt(e){return jt(e)?.editorType??"unknown"}function Yt(e){return jt(e)?.addressableType??null}function Vt(e){for(const t of Dt)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function Nt(e){return Ot.has(e.toLowerCase())}function Gt(){return Ot}function qt(e){return"string"==typeof e&&(!!e.includes("/")&&Nt(Ht(e)))}function Jt(){const e=[];for(const t of Dt)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function Kt(){return Jt().map(e=>({type:"suffix",value:e}))}function Qt(e){return Lt[e.toLowerCase()]}function Zt(e){const t=jt(e);return t?.wechatPackInclude??!1}class en{constructor(e){this.textureCache_=new vt,this.shaderCache_=new vt,this.jsonCache_=new vt,this.textCache_=new vt,this.binaryCache_=new vt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new vt,this.prefabCache_=new vt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.module_=e,this.canvas_=h(C.textCanvasSize,C.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 bt(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}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),o=this.textureCache_.get(s);if(!o)continue;const i=(this.textureRefCounts_.get(s)??1)-1;i<=0?(t.releaseTexture(o.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,i)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),dt.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 o=this.resolveUrl(t,n),i=await this.fetchText(o);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i),l=[];for(const e of a){const t=r?`${r}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u="binary"===jt(e)?.contentType,h=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(h,i,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),o=l.find(e=>e.name===n);if(o){const n=t.getTextureGLId(o.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,o.info.width,o.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=jt(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 o=n?`${n}/${s}`:s;return this.loadFntFile(o)}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],o=e.substring(0,e.lastIndexOf("/")),i=o?`${o}/${s}`:s,r=await this.loadTextureRaw(i);return this.module_.getResourceManager().loadBitmapFont(t,r.handle,r.width,r.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 kt(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 o=s.metadata?.atlas;o&&n.push(this.loadSpine(s.path,o).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 o=s??n;return new Promise((n,s)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(i)},i.onerror=()=>s(new Error(`Failed to load image: ${e}`)),i.src=o})}createTextureFromImage(e,t){const{width:n,height:s}=e,o=this.getWebGL2Context();return o?this.createTextureWebGL2(o,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,o){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const r=this.module_.GL,a=r.getNewId(r.textures);r.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const o=this.ctx_.getImageData(0,0,t,n),i=new Uint8Array(o.data.buffer);this.unpremultiplyAlpha(i);const r=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const l=r.createTexture(t,n,a,i.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:o}=this.parseEsShader(t);if(!s||!o)throw new Error(`Invalid shader format: ${e}`);return dt.createShader(s,o)}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:o,fragment:i}=this.parseEsShader(s);if(!o||!i)throw new Error(`Invalid shader format: ${e}`);return dt.createShader(o,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.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 r(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.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 r(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let o="";for(const e of s){o=o?`${o}/${e}`:e;try{t.analyzePath(o).exists||t.mkdir(o)}catch{try{t.mkdir(o)}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 tn=Se(null,"Assets");class nn{build(e){const t=e.wasmModule;t?e.insertResource(tn,new en(t)):console.warn("AssetPlugin: No WASM module available")}}const sn=new nn;class on{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 rn(e,t){const n=e.getResource(tn);n&&n.registerEmbeddedAssets(t)}async function an(e,t,n){const{entities:s,rootId:o}=await cn(t,n?.overrides??[],n,void 0,new Set),i={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},r=await kt(e,i,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=r.get(o);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:r}}const ln=10;async function cn(e,t,n,s,o,i=0){if(i>ln)throw new Error(`Prefab nesting depth exceeded ${ln}. Check for deep or circular nesting in: ${e.name}`);const r=new Map;let a;if(void 0===s){a=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=s;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(o?.has(s.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${s.nestedPrefab.prefabPath}`);continue}o?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await cn(e,s.nestedPrefab.overrides,n,a,o,i+1);r.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?r.get(s.parent)??null:null),l.push(...t.entities);continue}const c=r.get(s.prefabEntityId),u=s.prefabEntityId===e.rootEntityId,h={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:u?null:null!==s.parent?r.get(s.parent)??null:null,children:s.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};un(h,t),l.push(h)}const c=r.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function un(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 hn{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,o=await this.assetServer_.loadPrefab(s,t?.baseUrl);return an(this.world_,o,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const dn=Se(null,"Prefabs");class fn{constructor(){this.name="PrefabsPlugin",this.dependencies=[tn]}build(e){const t=e.getResource(tn);e.insertResource(dn,new hn(e.world,t))}}const pn=new fn;let gn=null,yn=0,mn=0,_n=0;const xn=new Float32Array(256);function wn(e){gn=e,yn=gn._malloc(64),mn=gn._malloc(64),_n=gn._malloc(1024)}function vn(){gn&&(yn&&(gn._free(yn),yn=0),mn&&(gn._free(mn),mn=0),_n&&(gn._free(_n),_n=0)),gn=null}function bn(){if(!gn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return gn}const Sn={r:1,g:1,b:1,a:1},Mn={begin(e){const t=bn();try{t.HEAPF32.set(e,yn/4),t.draw_begin(yn)}catch(e){Ze(e,"Draw.begin")}},end(){try{bn().draw_end()}catch(e){Ze(e,"Draw.end")}},line(e,t,n,s=1){try{bn().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Ze(e,"Draw.line")}},rect(e,t,n,s=!0){try{bn().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Ze(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{bn().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Ze(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,o=32){try{bn().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,o)}catch(e){Ze(e,"Draw.circle")}},circleOutline(e,t,n,s=1,o=32){try{bn().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,o)}catch(e){Ze(e,"Draw.circleOutline")}},texture(e,t,n,s=Sn){try{bn().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){Ze(e,"Draw.texture")}},textureRotated(e,t,n,s,o=Sn){try{bn().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,o.r,o.g,o.b,o.a)}catch(e){Ze(e,"Draw.textureRotated")}},setLayer(e){bn().draw_setLayer(e)},setDepth(e){bn().draw_setDepth(e)},getDrawCallCount:()=>gn?gn.draw_getDrawCallCount():0,getPrimitiveCount:()=>gn?gn.draw_getPrimitiveCount():0,setBlendMode(e){bn().draw_setBlendMode(e)},setDepthTest(e){bn().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=bn();s.HEAPF32.set(n,mn/4),s.draw_mesh(e,t,mn)}catch(n){Ze(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=bn(),o=dt.get(t);if(!o)return;if(Mn.setBlendMode(o.blendMode),Mn.setDepthTest(o.depthTest),0===o.uniforms.size)return void Mn.drawMesh(e,o.shader,n);let i;if(s.HEAPF32.set(n,mn/4),!o.dirty_&&o.cachedBuffer_)i=o.cachedIdx_;else{i=0;let e=0;for(const[t,n]of o.uniforms){const s=Tn(t);if(!(s<0)){if(ot(n))xn[i++]=10,xn[i++]=s,xn[i++]=n.slot??e++,xn[i++]=n.textureId;else if("number"==typeof n)xn[i++]=1,xn[i++]=s,xn[i++]=n;else if(Array.isArray(n)){xn[i++]=n.length,xn[i++]=s;for(let e=0;e<n.length;e++)xn[i++]=n[e]}else"w"in n?(xn[i++]=4,xn[i++]=s,xn[i++]=n.x,xn[i++]=n.y,xn[i++]=n.z,xn[i++]=n.w):"z"in n?(xn[i++]=3,xn[i++]=s,xn[i++]=n.x,xn[i++]=n.y,xn[i++]=n.z):(xn[i++]=2,xn[i++]=s,xn[i++]=n.x,xn[i++]=n.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!o.cachedBuffer_||o.cachedBuffer_.length<i)&&(o.cachedBuffer_=new Float32Array(i)),o.cachedBuffer_.set(xn.subarray(0,i)),o.cachedIdx_=i,o.dirty_=!1}if(0===i)return void s.draw_mesh(e,o.shader,mn);s.HEAPF32.set(o.cachedBuffer_.subarray(0,i),_n/4),s.draw_meshWithUniforms(e,o.shader,mn,_n,i)}catch(n){Ze(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Pn={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17},En=new Set;function Tn(e){const t=Pn[e];return void 0!==t?t:(En.has(e)||(En.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Pn).join(", ")}`)),-1)}const Cn=new Map;function Rn(e,t,n){Cn.set(e,{fn:t,scene:n??""})}function An(e){Cn.delete(e)}function In(){Cn.clear()}var Fn;!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"}(Fn||(Fn={}));let kn=null,Bn=0,zn=0,Un=0;function $n(e){kn=e,Bn=kn._malloc(262144),zn=kn._malloc(65536),Un=kn._malloc(256)}function Dn(){kn&&(Bn&&kn._free(Bn),zn&&kn._free(zn),Un&&kn._free(Un),Bn=0,zn=0,Un=0),kn=null}function Ln(){if(!kn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return kn}const Wn={create(e){const t=Ln(),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,Bn/4);const o=e.layout.length,i=new Int32Array(o);for(let t=0;t<o;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Un,o).set(i),t.geometry_init(n,Bn,s,Un,o,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,zn,s).set(e.indices),t.geometry_setIndices16(n,zn,s)}else{new Uint32Array(t.HEAPU8.buffer,zn,s).set(e.indices),t.geometry_setIndices32(n,zn,s)}}return n},updateVertices(e,t,n=0){const s=Ln(),o=t.length;if(4*o>262144)throw new Error(`Vertex data too large: ${o} floats (max 65536)`);s.HEAPF32.set(t,Bn/4),s.geometry_updateVertices(e,Bn,o,n)},release(e){e>0&&Ln().geometry_release(e)},isValid:e=>!(!kn||e<=0)&&kn.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:Fn.Float2},{name:"a_texCoord",type:Fn.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 o=s/t*Math.PI*2,i=Math.cos(o)*e,r=Math.sin(o)*e,a=(Math.cos(o)+1)/2,l=(Math.sin(o)+1)/2;n.push(i,r,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:Fn.Float2},{name:"a_texCoord",type:Fn.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,o=-1/0;for(const i of e)t=Math.min(t,i.x),n=Math.min(n,i.y),s=Math.max(s,i.x),o=Math.max(o,i.y);const i=[];for(const r of e){const e=(r.x-t)/(s-t),a=(r.y-n)/(o-n);i.push(r.x,r.y,e,a)}const r=[];for(let t=1;t<e.length-1;t++)r.push(0,t,t+1);return Wn.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:Fn.Float2},{name:"a_texCoord",type:Fn.Float2}],indices:new Uint16Array(r)})}};let On=null;function Hn(e){On=e}function jn(){On&&Yn.isInitialized()&&Yn.shutdown(),On=null}function Xn(){if(!On)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return On}const Yn={init(e,t){try{return Xn().postprocess_init(e,t)}catch(n){return Ze(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Xn().postprocess_shutdown()}catch(e){Ze(e,"PostProcess.shutdown")}},resize(e,t){try{Xn().postprocess_resize(e,t)}catch(n){Ze(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Xn().postprocess_addPass(e,t)}catch(t){return Ze(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Xn().postprocess_removePass(e)}catch(t){Ze(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Xn().postprocess_setPassEnabled(e,t)}catch(t){Ze(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Xn().postprocess_isPassEnabled(e)}catch(t){return Ze(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{Xn().postprocess_setUniformFloat(e,t,n)}catch(n){Ze(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{Xn().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){Ze(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Xn().postprocess_begin()}catch(e){Ze(e,"PostProcess.begin")}},end(){try{Xn().postprocess_end()}catch(e){Ze(e,"PostProcess.end")}},getPassCount(){try{return Xn().postprocess_getPassCount()}catch(e){return Ze(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!On)return!1;try{return On.postprocess_isInitialized()}catch(e){return Ze(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Xn().postprocess_setBypass(e)}catch(e){Ze(e,"PostProcess.setBypass")}},isBypassed(){if(!On)return!0;try{return On.postprocess_isBypassed()}catch(e){return Ze(e,"PostProcess.isBypassed"),!0}},createBlur:()=>dt.createShader(Vn,"#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:()=>dt.createShader(Vn,"#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:()=>dt.createShader(Vn,"#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:()=>dt.createShader(Vn,"#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")},Vn="#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 Nn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Nn||(Nn={}));let Gn=null,qn=0;function Jn(e){Gn=e,qn=Gn._malloc(64)}function Kn(){Gn&&qn&&(Gn._free(qn),qn=0),Gn=null}const Qn={init(e,t){Gn?.renderer_init(e,t)},resize(e,t){Gn?.renderer_resize(e,t)},begin(e,t){if(Gn&&qn)try{Gn.HEAPF32.set(e,qn/4),Gn.renderer_begin(qn,t??0)}catch(e){Ze(e,"Renderer.begin")}},flush(){try{Gn?.renderer_flush()}catch(e){Ze(e,"Renderer.flush")}},end(){try{Gn?.renderer_end()}catch(e){Ze(e,"Renderer.end")}},submitSprites(e){if(Gn)try{Gn.renderer_submitSprites(e._cpp)}catch(e){Ze(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Gn)try{Gn.renderer_submitBitmapText(e._cpp)}catch(e){Ze(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Gn)try{Gn.renderer_submitSpine?.(e._cpp)}catch(e){Ze(e,"Renderer.submitSpine")}},setStage(e){Gn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Gn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Gn?.renderer_releaseTarget(e)},getTargetTexture:e=>Gn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Gn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Gn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Gn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,o){Gn?.renderer_setScissor(e,t,n,s,o)},clearBuffers(e){Gn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Gn?Gn.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Gn?{drawCalls:Gn.renderer_getDrawCalls(),triangles:Gn.renderer_getTriangles(),sprites:Gn.renderer_getSprites(),text:Gn.renderer_getText(),spine:Gn.renderer_getSpine?.()??0,meshes:Gn.renderer_getMeshes(),culled:Gn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Zn=null;function es(e){Zn=e}function ts(){Zn=null}const ns={enable(){Zn?.gl_enableErrorCheck(!0)},disable(){Zn?.gl_enableErrorCheck(!1)},check:e=>Zn?.gl_checkErrors(e)??0,diagnose(){Zn?.renderer_diagnose()}};class ss{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:o,elapsed:i}=e;s===this.lastWidth_&&o===this.lastHeight_||(Qn.resize(s,o),Yn.isInitialized()&&Yn.getPassCount()>0&&Yn.resize(s,o),this.lastWidth_=s,this.lastHeight_=o),Qn.setViewport(0,0,s,o),Qn.clearBuffers(3),Qn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,o),Qn.submitSprites(t),Qn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Qn.submitSpine(t),Qn.flush(),this.executeDrawCallbacks(n,i),Qn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:o,elapsed:i}=e;Qn.setViewport(s.x,s.y,s.w,s.h),Qn.setScissor(s.x,s.y,s.w,s.h,!0),Qn.clearBuffers(o),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,i):Qn.submitSpine(t),Qn.flush(),this.executeDrawCallbacks(n,i),Qn.end()}executeDrawCallbacks(e,t){const n=Cn;if(n.size>0){Mn.begin(e);const s=[];for(const[e,o]of n.entries())if(!o.scene||!this.activeScenes_||this.activeScenes_.has(o.scene))try{o.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}Mn.end();for(const e of s)An(e)}}}const os="__scene_transition_overlay__";class is{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class rs{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,ge,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),Rn(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=Yn.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){Yn.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,ge)){const n=this.app_.world.get(e,ge);n.persistent=t,this.app_.world.insert(e,ge,n)}}}class as{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??C.sceneTransitionDuration,o=t.color??{...C.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:o,targetScene:e,options:t,resolve:n},Rn(os,()=>{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;Mn.setLayer(9999),Mn.setDepth(9999),Mn.rect({x:0,y:0},{x:2e4,y:2e4},{r:o.r,g:o.g,b:o.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{try{n&&n!==e&&await this.unload(n,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,An(os),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,An(os),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 is(t);this.scenes_.set(e,n);const s=new rs(n,this.app_);this.contexts_.set(e,s);const o=(async()=>{let o=t.data;if(!o&&t.path){const e=this.app_.hasResource(tn)?this.app_.getResource(tn):null;if(e)o=await e.loadJson(t.path);else{const e=await fetch(t.path);o=await e.json()}}if(o){const t={};this.app_.hasResource(tn)&&(t.assetServer=this.app_.getResource(tn));const s=await kt(this.app_.world,o,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,ge,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=cs(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,o);try{return await o}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 is(t);this.scenes_.set(e,n);const s=new rs(n,this.app_);this.contexts_.set(e,s);const o=(async()=>{let o=t.data;if(!o&&t.path){const e=this.app_.hasResource(tn)?this.app_.getResource(tn):null;if(e)o=await e.loadJson(t.path);else{const e=await fetch(t.path);o=await e.json()}}if(o){const t={};this.app_.hasResource(tn)&&(t.assetServer=this.app_.getResource(tn));const s=await kt(this.app_.world,o,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,ge,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=cs(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,o);try{return await o}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 o=t?.keepPersistent??!0;for(const e of n.entities){if(o&&this.app_.world.valid(e)&&this.app_.world.has(e,ge)){if(this.app_.world.get(e,ge).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())An(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{Yn.removePass(e)}catch{}n.postProcessPasses.length=0,this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const i=this.loadOrder_.indexOf(e);-1!==i&&this.loadOrder_.splice(i,1),this.activeScene_===e&&(this.activeScene_=null)}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s={};let o=!1;if(n.has(e,re)){const t=n.get(e,re);s.sprite=t.color.a,t.color={...t.color,a:0},n.insert(e,re,t),o=!0}if(n.has(e,fe)){const t=n.get(e,fe);s.spine=t.color.a,t.color={...t.color,a:0},n.insert(e,fe,t),o=!0}if(n.has(e,de)){const t=n.get(e,de);s.bitmapText=t.color.a,t.color={...t.color,a:0},n.insert(e,de,t),o=!0}o&&t.savedAlphas.set(e,s)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s=t.savedAlphas.get(e);if(s){if(void 0!==s.sprite&&n.has(e,re)){const t=n.get(e,re);t.color={...t.color,a:s.sprite},n.insert(e,re,t)}if(void 0!==s.spine&&n.has(e,fe)){const t=n.get(e,fe);t.color={...t.color,a:s.spine},n.insert(e,fe,t)}if(void 0!==s.bitmapText&&n.has(e,de)){const t=n.get(e,de);t.color={...t.color,a:s.bitmapText},n.insert(e,de,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{Yn.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 ls=Se(null,"SceneManager");function cs(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(ls).getSceneStatus(t)&&n._fn(...s)}}}const us=De([Pe(ls),Me(Ce)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),hs={name:"SceneManager",build(e){const t=new as(e);e.insertResource(ls,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(ls),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Ue.Startup,n),e.addSystemToSchedule(Ue.Last,us)}};class ds{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(Ue.Last);else{this.runSchedule(Ue.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Ue.FixedPreUpdate),this.runSchedule(Ue.FixedUpdate),this.runSchedule(Ue.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(Ue.PreUpdate),this.runSchedule(Ue.Update),this.runSchedule(Ue.PostUpdate),this.runSchedule(Ue.Last),this.step_pending_&&(this.step_pending_=!1)}requestAnimationFrame(this.mainLoop)},this.world_=new tt,this.resources_=new Te;for(const e of Object.values(Ue))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new ds}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(Ue.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Ue.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 Qe(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(ls).register(e),this}setInitialScene(e){return this.getResource(ls).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new je(this.world_,this.resources_),this.resources_.insert(Ce,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Ue.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,In();for(const e of this.installed_plugins_)try{e.cleanup?.()}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.clear();const e=[ts,Kn,jn,Dn,ut,vn];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 o=t.get(s);if(void 0!==o){const t=e[o];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,o=new Set,i=r=>{if(s.has(r))return;if(o.has(r)){const t=e[r].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}o.add(r);const a=e[r];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&i(n)}o.delete(r),s.add(r),n.push(a)};for(let t=0;t<e.length;t++)i(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(Ce);t.delta=e,t.elapsed+=e,t.frameCount++}}function fs(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 ps=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function gs(e,t,n,s,o){const i=e*t/n,r=e;switch(s){case se.FixedWidth:return i;case se.FixedHeight:return r;case se.Expand:return Math.max(i,r);case se.Shrink:return Math.min(i,r);case se.Match:{const e=o;return Math.pow(i,1-e)*Math.pow(r,e)}default:return r}}function ys(e,t,n,s,o,i){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=i&&o?r.filter(e=>{const t=o.tryGet(e,ge);return!t||""===t.scene||i.has(t.scene)}):r;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const o=t.getCamera(e),i=t.getLocalTransform(e),r={x:o.viewportX,y:o.viewportY,w:o.viewportW,h:o.viewportH},a=r.w*n/(r.h*s);let u,h=0,d=0;if(o.projectionType===te.Orthographic){if(d=o.orthoSize,l){d=gs(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}h=d*a,u=_s(-h,h,-d,d,-o.farPlane,o.farPlane)}else u=ws(o.fov*Math.PI/180,a,o.nearPlane,o.farPlane);const f=bs(i.position.x,i.position.y,i.position.z);c.push({entity:e,viewProjection:new Float32Array(Ms(u,f)),viewportRect:r,clearFlags:o.clearFlags,priority:o.priority,halfW:h,halfH:d,cameraX:i.position.x,cameraY:i.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const ms=new Float32Array(16);function _s(e,t,n,s,o,i){const r=ms;r.fill(0);const a=t-e,l=s-n,c=i-o;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(s+n)/l,r[14]=-(i+o)/c,r[15]=1,r}const xs=new Float32Array(16);function ws(e,t,n,s){const o=xs;o.fill(0);const i=1/Math.tan(e/2),r=n-s;return o[0]=i/t,o[5]=i,o[10]=(s+n)/r,o[11]=-1,o[14]=2*s*n/r,o}const vs=new Float32Array(16);function bs(e,t,n){const s=vs;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 Ss=new Float32Array(16);function Ms(e,t){const n=Ss;for(let s=0;s<4;s++)for(let o=0;o<4;o++)n[4*o+s]=e[0+s]*t[4*o+0]+e[4+s]*t[4*o+1]+e[8+s]*t[4*o+2]+e[12+s]*t[4*o+3];return n}const Ps={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function Es(e,t,n,s,o,i,r={x:.5,y:.5}){const a=i.right-i.left,l=i.top-i.bottom,c=i.left+e.x*a,u=i.left+t.x*a,h=i.bottom+e.y*l,d=i.bottom+t.y*l;let f,p,g,y;e.x===t.x?(f=c+n.x-o.x*r.x,g=f+o.x):(f=c+n.x,g=u+s.x),e.y===t.y?(p=h+n.y-o.y*r.y,y=p+o.y):(p=h+n.y,y=d+s.y);const m=Math.max(0,g-f),_=Math.max(0,y-p);return{originX:f+r.x*m,originY:p+r.y*_,width:m,height:_,rect:{left:f,bottom:p,right:g,top:y}}}const Ts=X("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},_dirty:!0,_computedWidth:void 0,_computedHeight:void 0,_layoutManaged:void 0});function Cs(e,t){e.has(t,re)||e.insert(t,re,{texture:I,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0})}function Rs(e,t){switch(e){case Ps.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Ps.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Ps.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function As(e,t){switch(e){case Ps.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case Ps.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case Ps.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1-t}};default:return{anchorMin:{x:t,y:0},anchorMax:{x:t,y:1}}}}function Is(e,t,n,s){switch(e){case Ps.BottomToTop:case Ps.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function Fs(e,t,n,s){if(!e.has(t,Ts))return;const o=e.get(t,Ts),i=Rs(n,s);o.anchorMin=i.anchorMin,o.anchorMax=i.anchorMax,o.offsetMin=i.offsetMin,o.offsetMax=i.offsetMax,i.anchorMin.x===i.anchorMax.x&&(o.size={...o.size,x:0}),i.anchorMin.y===i.anchorMax.y&&(o.size={...o.size,y:0}),e.insert(t,Ts,o)}function ks(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Bs(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function zs(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),o=[];for(const t of s){if(!t){o.push("");continue}let s="";for(let i=0;i<t.length;i++){const r=t[i],a=s+r;if(e.measureText(a).width>n&&s){if(Bs(r.charCodeAt(0))&&s.length>0&&Bs(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!Bs(s.charCodeAt(t))){e=t;break}e>=0?(o.push(s.substring(0,e+1)),s=s.substring(e+1)+r):(o.push(s),s=r)}else o.push(s),s=r}else s=a}s&&o.push(s)}return o.length>0?o:[""]}function Us(e){let t=1;for(;t<e;)t*=2;return t}function $s(e,t){let n=0,s=t;for(;e.has(s,ue);){const t=e.get(s,ue).entity;if(!e.valid(t))break;n++,s=t}return n}function Ds(e){return e._computedWidth??e.size.x}function Ls(e){return e._computedHeight??e.size.y}function Ws(e,t,n,s,o,i){if(!e.has(t,re))return;const r=e.get(t,re);let a,l;switch(n){case Ps.BottomToTop:case Ps.TopToBottom:a=o,l=i*s;break;default:a=o*s,l=i}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,re,r))}function Os(e,t,n){let s=t;for(;e.has(s,ue);){const t=e.get(s,ue).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function Hs(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function js(e,t,n,s,o){if(!e.has(t,Ts))return;const i=e.get(t,Ts),r=Es(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n,i.pivot),a=r.rect.right-r.rect.left,l=r.rect.top-r.rect.bottom;if(i._computedWidth=a,i._computedHeight=l,e.has(t,re)){const n=e.get(t,re);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,re,n))}if(!i._layoutManaged&&e.has(t,oe)){const n=e.get(t,oe);n.position.x=r.originX-s,n.position.y=r.originY-o,e.insert(t,oe,n)}}function Xs(e){const t=Object.keys(e),n=t.map(t=>e[t]);return{take(e){const s={};for(let o=0;o<t.length;o++)s[t[o]]=n[o](e);return s},changed(e,s){for(let o=0;o<t.length;o++)if(e[t[o]]!==n[o](s))return!0;return!1},update(e,s){for(let o=0;o<t.length;o++)e[t[o]]=n[o](s)}}}const Ys={r:.3,g:.5,b:.8,a:1},Vs={Left:0,Center:1,Right:2},Ns={Top:0,Middle:1,Bottom:2},Gs={Visible:0,Clip:1,Ellipsis:2},qs=X("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Vs.Left,verticalAlign:Ns.Top,wordWrap:!0,overflow:Gs.Visible,lineHeight:1.2});class Js{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(C.textCanvasSize,C.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,Us(this.frameMaxW_)),e.height=Math.max(e.height,Us(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Us(this.frameMaxW_),e.height=Us(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const o=t&&t.size.x>0&&t.size.y>0,i=o?t.size.x:0,r=o?t.size.y:0,a=e.wordWrap&&o;let l=zs(n,e.content,a?i:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=o?Math.ceil(i):h+2*u,p=o?Math.ceil(r):d+2*u;if(o&&e.overflow===Gs.Ellipsis&&d>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,i)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,Us(f)),s.height=Math.max(s.height,Us(p)));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}, ${_})`,o&&e.overflow===Gs.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const x=l.length*c;let w;if(o)switch(e.verticalAlign){case Ns.Top:w=u;break;case Ns.Middle:w=u+(p-2*u-x)/2;break;case Ns.Bottom:w=p-x-u;break;default:w=u}else w=u;let v=w;for(const t of l){let s;switch(e.align){case Vs.Left:s=u;break;case Vs.Center:s=f/2;break;case Vs.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=c}o&&e.overflow===Gs.Clip&&n.restore();const b=n.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),M=this.module.getResourceManager(),P=this.module._malloc(S.length);this.module.HEAPU8.set(S,P);const E=M.createTexture(f,p,P,S.length,1,!0);return this.module._free(P),{textureHandle:E,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 o=this.renderText(t,n);return this.cache.set(e,o),o}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}measureWidth(e){let t=0;for(const n of e)t=Math.max(t,this.ctx.measureText(n).width);return t}mapAlign(e){switch(e){case Vs.Left:return"left";case Vs.Center:return"center";case Vs.Right:return"right"}}}const Ks=Xs({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?Ds(e.uiRect):0,containerHeight:e=>e.uiRect?Ls(e.uiRect):0});class Qs{build(e){Q("Text",qs);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Js(t),s=e.world,o=new Map;e.addSystemToSchedule(Ue.PreUpdate,De([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,qs));for(const e of o.keys())if(!s.valid(e)||!s.has(e,qs)){if(s.valid(e)&&s.has(e,re)){const t=s.get(e,re);t.texture=I,s.insert(e,re,t)}o.delete(e)}const e=s.getEntitiesWithComponents([qs]);for(const t of e){const e=s.get(t,qs),i=s.has(t,Ts)?s.get(t,Ts):null,r={text:e,uiRect:i},a=o.get(t);if(a&&!Ks.changed(a,r))continue;Cs(s,t);const l=n.renderForEntity(t,e,i),c=s.get(t,re);c.texture=l.textureHandle,c.size.x=l.width,c.size.y=l.height,c.uvOffset.x=0,c.uvOffset.y=0,c.uvScale.x=1,c.uvScale.y=1,s.insert(t,re,c),o.set(t,Ks.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Zs=new Qs,eo=X("UIMask",{enabled:!0,mode:"scissor"});function to(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),o=Math.min(e.x+e.w,t.x+t.w),i=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,o-n),h:Math.max(0,i-s)}}function no(e,t){const n=t??new Float32Array(16),s=e[0],o=e[1],i=e[2],r=e[3],a=e[4],l=e[5],c=e[6],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],g=e[12],y=e[13],m=e[14],_=e[15],x=s*l-o*a,w=s*c-i*a,v=s*u-r*a,b=o*c-i*l,S=o*u-r*l,M=i*u-r*c,P=h*y-d*g,E=h*m-f*g,T=h*_-p*g,C=d*m-f*y,R=d*_-p*y,A=f*_-p*m;let I=x*A-w*R+v*C+b*T-S*E+M*P;return 0===I||(I=1/I,n[0]=(l*A-c*R+u*C)*I,n[1]=(i*R-o*A-r*C)*I,n[2]=(y*M-m*S+_*b)*I,n[3]=(f*S-d*M-p*b)*I,n[4]=(c*T-a*A-u*E)*I,n[5]=(s*A-i*T+r*E)*I,n[6]=(m*v-g*M-_*w)*I,n[7]=(h*M-f*v+p*w)*I,n[8]=(a*R-l*T+u*P)*I,n[9]=(o*T-s*R-r*P)*I,n[10]=(g*S-y*v+_*x)*I,n[11]=(d*v-h*S-p*x)*I,n[12]=(l*E-a*C-c*P)*I,n[13]=(s*C-o*E+i*P)*I,n[14]=(y*w-g*b-m*x)*I,n[15]=(h*b-d*w+f*x)*I),n}function so(e,t,n,s,o,i,r){const a=(e-s)/i*2-1,l=(t-o)/r*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:u/h}}function oo(e,t,n,s,o,i,r,a){return e>=n-o*r&&e<=n+o*(1-r)&&t>=s-i*a&&t<=s+i*(1-a)}function io(e,t){return 2*Math.atan2(e,t)}function ro(e,t,n,s,o,i,r){const a=n[0]*e+n[4]*t+n[12],l=n[1]*e+n[5]*t+n[13],c=n[3]*e+n[7]*t+n[15];return[s+(.5*(a/c)+.5)*i,o+(.5*(l/c)+.5)*r]}function ao(e,t,n,s,o,i,r,a,l,c){const u=io(l,c),h=Math.sin(-u),d=Math.cos(-u),f=e-n,p=t-s,g=f*d-p*h+n,y=f*h+p*d+s;return g>=n-o*r&&g<=n+o*(1-r)&&y>=s-i*a&&y<=s+i*(1-a)}function lo(e,t,n,s,o,i,r){if(!e.has(t,Ts)||!e.has(t,ie))return null;const a=e.get(t,Ts),l=e.get(t,ie),c=Ds(a)*l.scale.x,u=Ls(a)*l.scale.y,h=l.position.x,d=l.position.y,f=a.pivot.x,p=a.pivot.y,g=-c*f,y=c*(1-f),m=-u*p,_=u*(1-p),x=io(l.rotation.z,l.rotation.w),w=Math.cos(x),v=Math.sin(x),b=[[h+g*w-m*v,d+g*v+m*w],[h+y*w-m*v,d+y*v+m*w],[h+y*w-_*v,d+y*v+_*w],[h+g*w-_*v,d+g*v+_*w]];let S=1/0,M=1/0,P=-1/0,E=-1/0;for(const[e,t]of b){const[a,l]=ro(e,t,n,s,o,i,r);S=Math.min(S,a),M=Math.min(M,l),P=Math.max(P,a),E=Math.max(E,l)}return{x:Math.round(S),y:Math.round(M),w:Math.round(P-S),h:Math.round(E-M)}}function co(e,t){return(n,s,o,i,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([eo]);if(0===l.length)return;const c=[],u=[],h=new Set,d=new Set;for(const e of l){const n=t.get(e,eo);n.enabled&&(h.add(e),"stencil"===n.mode?(u.push(e),d.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,o,i,r,a,l,c){const u=[];for(const e of s){let n=!0;Os(t,e,e=>{if(o.has(e)){if("scissor"===t.get(e,eo).mode)return n=!1,!0}return!1}),n&&u.push(e)}function h(s,u){const d=e.getChildEntities(n,s);for(const n of d){let s=u;if(o.has(n)){if("scissor"===t.get(n,eo).mode){const e=lo(t,n,i,r,a,l,c);e&&(s=to(u,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of u){const n=lo(t,e,i,r,a,l,c);n&&h(e,n)}}(e,t,n,c,h,s,o,i,r,a),u.length>0&&function(e,t,n,s,o){e.renderer_clearStencil();const i=[];for(const e of s){let n=!0;Os(t,e,e=>!!o.has(e)&&(n=!1,!0)),n&&i.push(e)}let r=1,a=!1;function l(){return r>255?(a||console.warn("Stencil mask overflow"),a=!0,null):r++}function c(t,s){if(a)return;e.renderer_setEntityStencilMask(t,s);const i=e.getChildEntities(n,t);for(const t of i)if(o.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),u(t,s)}function u(t,s){if(a)return;const i=e.getChildEntities(n,t);for(const t of i)if(o.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),u(t,s)}for(const e of i){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,n,u,d)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class uo{build(e){if(Q("UIMask",eo),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(co(e.wasmModule,e.world))}}const ho=new uo,fo=X("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),po=X("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),go={Normal:0,Hovered:1,Pressed:2,Disabled:3},yo=X("Button",{state:go.Normal,transition:null});class mo{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 _o=Se(new mo,"UIEvents"),xo=Y("ScreenSpace"),wo=Xs({anchorMinX:e=>e.anchorMin.x,anchorMinY:e=>e.anchorMin.y,anchorMaxX:e=>e.anchorMax.x,anchorMaxY:e=>e.anchorMax.y,offsetMinX:e=>e.offsetMin.x,offsetMinY:e=>e.offsetMin.y,offsetMaxX:e=>e.offsetMax.x,offsetMaxY:e=>e.offsetMax.y,sizeX:e=>e.size.x,sizeY:e=>e.size.y});function vo(e,t,n,s,o,i){if(!e.has(t,Ts))return;const r=e.get(t,Ts),a=Es(r.anchorMin,r.anchorMax,r.offsetMin,r.offsetMax,r.size,n,r.pivot),l=a.rect.right-a.rect.left,c=a.rect.top-a.rect.bottom;if(r._computedWidth=l,r._computedHeight=c,e.has(t,re)){const n=e.get(t,re);n.size.x===l&&n.size.y===c||(n.size.x=l,n.size.y=c,e.insert(t,re,n))}if(!r._layoutManaged){const n=e.get(t,oe);i?(n.position.x=a.originX,n.position.y=a.originY):(n.position.x=a.originX-s,n.position.y=a.originY-o),e.insert(t,oe,n)}if(!e.has(t,he))return;const u=e.get(t,he);if(u&&u.entities)for(const t of u.entities)e.valid(t)&&vo(e,t,a.rect,a.originX,a.originY,!1)}class bo{build(e){Q("UIRect",Ts);const t=e.world,n=new Map,s=new Map;let o=NaN,i=NaN,r=NaN,a=NaN;function l(e){let n=s.get(e);return void 0!==n||(n=function(e,t){let n=t;for(;;){if(e.has(n,xo))return n;if(!e.has(n,ue))return null;const t=e.get(n,ue);if(!e.valid(t.entity))return null;n=t.entity}}(t,e),s.set(e,n)),n}function c(e){if(s.delete(e),!t.has(e,he))return;const n=t.get(e,he);if(n&&n.entities)for(const e of n.entities)t.valid(e)&&c(e)}e.addSystemToSchedule(Ue.PreUpdate,De([Me(nt)],e=>{if(!e.valid)return;const u={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},h=.5*(u.left+u.right),d=.5*(u.bottom+u.top),f=o!==e.worldLeft||i!==e.worldBottom||r!==e.worldRight||a!==e.worldTop;o=e.worldLeft,i=e.worldBottom,r=e.worldRight,a=e.worldTop;const p=new Set;if(f){s.clear();const e=t.getEntitiesWithComponents([xo,Ts,oe]);for(const t of e)p.add(t)}for(const e of n.keys())t.valid(e)&&t.has(e,Ts)||(n.delete(e),s.delete(e));const g=t.getEntitiesWithComponents([Ts]);for(const e of g){const s=t.get(e,Ts),o=n.get(e);if(s._dirty||!o||wo.changed(o,s)){s._dirty=!1,c(e);const t=l(e);null!==t&&p.add(t)}}for(const e of p)vo(t,e,u,h,d,!0);for(const e of g){const s=t.get(e,Ts),o=n.get(e);o?wo.update(o,s):n.set(e,wo.take(s))}},{name:"UILayoutSystem"}))}}const So=new bo,Mo=function(){const e=new Float32Array(16),t=new Float32Array(16);let n=!0;return{update(e){for(let s=0;s<16;s++)if(t[s]!==e[s]){t.set(e),n=!0;break}},getInverse:t=>(n&&(no(t,e),n=!1),e)}}();function Po(e,t,n,s){let o=!1;return Os(e,t,t=>{if(!e.has(t,eo))return!1;if(!e.get(t,eo).enabled||!e.has(t,Ts)||!e.has(t,ie))return!1;const i=e.get(t,ie),r=e.get(t,Ts),a=Ds(r)*i.scale.x,l=Ls(r)*i.scale.y;return!ao(n,s,i.position.x,i.position.y,a,l,r.pivot.x,r.pivot.y,i.rotation.z,i.rotation.w)&&(o=!0,!0)}),o}function Eo(e,t,n,s){t.emit(n,s,n),Os(e,n,o=>{if(!e.has(o,fo))return!1;const i=e.get(o,fo);return i.enabled&&t.emit(o,s,n),i.blockRaycast})}class To{build(e){Q("Interactable",fo),Q("Button",yo);const t=e.world,n=new mo;e.insertResource(_o,n);let s=null,o=null;e.addSystemToSchedule(Ue.PreUpdate,De([Me(Ye),Me(nt)],(e,i)=>{n.drain();const r=t.getEntitiesWithComponents([po]);for(const e of r){const n=t.get(e,po);n.justPressed=!1,n.justReleased=!1}if(!i.valid)return;const a=f(),l=e.mouseX*a,c=i.screenH-e.mouseY*a;Mo.update(i.viewProjection);const u=so(l,c,Mo.getInverse(i.viewProjection),i.vpX,i.vpY,i.vpW,i.vpH);i.worldMouseX=u.x,i.worldMouseY=u.y;const h=t.getEntitiesWithComponents([fo,Ts,ie]);let d=null,p=-1/0;for(const e of h){Hs(t,e,po);const n=t.get(e,fo);if(!n.enabled)continue;if(!n.raycastTarget)continue;const s=t.get(e,ie),o=t.get(e,Ts),i=Ds(o)*s.scale.x,r=Ls(o)*s.scale.y;if(ao(u.x,u.y,s.position.x,s.position.y,i,r,o.pivot.x,o.pivot.y,s.rotation.z,s.rotation.w)){if(Po(t,e,u.x,u.y))continue;let n=0;t.has(e,re)&&(n=t.get(e,re).layer),n>p&&(p=n,d=e)}}if(null===s||t.valid(s)||(s=null),s!==d){if(null!==s&&t.valid(s)&&t.has(s,po)){t.get(s,po).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,po).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,po);e.pressed=!0,e.justPressed=!0,o=d,Eo(t,n,d,"press")}if(e.isMouseButtonReleased(0)&&null!==o){if(t.valid(o)&&t.has(o,po)){const e=t.get(o,po);e.pressed=!1,e.justReleased=!0,Eo(t,n,o,"release"),o===s&&Eo(t,n,o,"click")}o=null}},{name:"UIInteractionSystem"}));const i=new Set;e.addSystemToSchedule(Ue.Update,De([],()=>{const e=t.getEntitiesWithComponents([yo]);for(const n of e){if(Hs(t,n,fo,{enabled:!0}),!t.has(n,po))continue;const e=t.get(n,po),s=t.get(n,yo),o=t.get(n,fo),r=!i.has(n),a=s.state;if(o.enabled?e.pressed?s.state=go.Pressed:e.hovered?s.state=go.Hovered:s.state=go.Normal:s.state=go.Disabled,r&&i.add(n),(r||a!==s.state)&&s.transition&&t.has(n,re)){const i=t.get(n,re);i.color=ks(s.transition,o.enabled,e.pressed,e.hovered),t.insert(n,re,i)}}},{name:"ButtonSystem"}))}}const Co=new To,Ro=X("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0}),Ao=X("Focusable",{tabIndex:0,isFocused:!1});class Io{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Fo=Se(new Io,"FocusManager");class ko{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){Q("TextInput",Ro);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,o=h(C.textCanvasSize,64),i=o.getContext("2d",{willReadFrequently:!0});let r=!1,a=!0,l=0,c=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 d=u;function f(){const t=e.getResource(Fo);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,Ro)?s:null}const p=()=>{r||null===f()||x()},g=()=>{r=!0},y=()=>{r=!1,x()},m=t=>{const s=f();if(null===s)return;if("Escape"===t.key)return void w();const o=n.get(s,Ro);if("Enter"===t.key&&!o.multiline){t.preventDefault();return e.getResource(_o).emit(s,"submit"),void w()}let i=o.cursorPos;"ArrowLeft"===t.key?i=Math.max(0,o.cursorPos-1):"ArrowRight"===t.key?i=Math.min(o.value.length,o.cursorPos+1):"Home"===t.key?i=0:"End"===t.key&&(i=o.value.length),i!==o.cursorPos&&(o.cursorPos=i,d.selectionStart=i,d.selectionEnd=i,o.dirty=!0,v())},_=()=>{const t=f();if(null!==t){const s=n.get(t,Ro);s.focused=!1,s.dirty=!0;e.getResource(Fo).blur()}};function x(){const t=f();if(null===t)return;const s=n.get(t,Ro);if(s.readOnly)return;let o=d.value;if(s.maxLength>0&&o.length>s.maxLength&&(o=o.substring(0,s.maxLength),d.value=o),o!==s.value){s.value=o;e.getResource(_o).emit(t,"change")}s.cursorPos=d.selectionStart??o.length,s.dirty=!0,v()}function w(){const t=f();if(null!==t){const e=n.get(t,Ro);e.focused=!1,e.dirty=!0}e.getResource(Fo).blur(),d.blur()}function v(){a=!0,l=0}d.addEventListener("input",p),d.addEventListener("compositionstart",g),d.addEventListener("compositionend",y),d.addEventListener("keydown",m),d.addEventListener("blur",_),this.cleanupListeners_=()=>{d.removeEventListener("input",p),d.removeEventListener("compositionstart",g),d.removeEventListener("compositionend",y),d.removeEventListener("keydown",m),d.removeEventListener("blur",_),d.remove();const e=t.getResourceManager();for(const t of s.values())e.releaseTexture(t);s.clear()};let b=null;function S(e,r,l,c){(o.width<l||o.height<c)&&(o.width=Us(Math.max(o.width,l)),o.height=Us(Math.max(o.height,c))),i.clearRect(0,0,o.width,o.height);const u=r.backgroundColor;i.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,i.fillRect(0,0,l,c),i.save(),i.beginPath(),i.rect(r.padding,0,l-2*r.padding,c),i.clip(),i.font=`${r.fontSize}px ${r.fontFamily}`,i.textBaseline="top",i.textAlign="left";const h=0===r.value.length,d=h?r.placeholder:r.password?"●".repeat(r.value.length):r.value,f=h?r.placeholderColor:r.color;i.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*r.fontSize),g=r.padding;if(r.multiline){const e=zs(i,d,l-2*g);let t=g;for(const n of e)i.fillText(n,g,t),t+=p}else{const e=(c-r.fontSize)/2;i.fillText(d,g,e)}if(r.focused&&a){const e=r.password?"●".repeat(r.cursorPos):r.value.substring(0,r.cursorPos);let t,n,s;if(r.multiline){const e=zs(i,r.value,l-2*g);let o=0,a=0,c=0;for(let t=0;t<e.length;t++){const n=e[t].length;if(o+n>=r.cursorPos){a=t,c=r.cursorPos-o;break}o+=n,t<e.length-1&&o<r.value.length&&"\n"===r.value[o]&&o++,a=t+1,c=0}const u=a<e.length?e[a].substring(0,c):"";t=g+i.measureText(u).width,n=g+a*p,s=p}else t=g+i.measureText(e).width,n=(c-r.fontSize)/2,s=r.fontSize;i.fillStyle=`rgba(${Math.round(255*r.color.r)}, ${Math.round(255*r.color.g)}, ${Math.round(255*r.color.b)}, ${r.color.a})`,i.fillRect(t,n,2,s)}i.restore();const y=i.getImageData(0,0,l,c),m=new Uint8Array(y.data.buffer),_=t.getResourceManager(),x=t._malloc(m.length);t.HEAPU8.set(m,x);const w=s.get(e);void 0!==w&&_.releaseTexture(w);const v=_.createTexture(l,c,x,m.length,1,!0);s.set(e,v),t._free(x);const b=n.get(e,re);b.texture=v,b.size.x=l,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,re,b)}e.addSystemToSchedule(Ue.Update,De([Me(Fo)],e=>{const t=n.getEntitiesWithComponents([Ro]);for(const e of t)Hs(n,e,Ao,{tabIndex:0,isFocused:!1}),Hs(n,e,fo,{enabled:!0,blockRaycast:!0});const s=f();if(s!==b){if(null!==b&&n.valid(b)&&n.has(b,Ro)){const e=n.get(b,Ro);e.focused=!1,e.dirty=!0,d.blur()}null!==s&&function(e){const t=n.get(e,Ro);t.readOnly||(t.focused=!0,t.dirty=!0,d.value=t.value,d.selectionStart=t.cursorPos,d.selectionEnd=t.cursorPos,d.focus(),v())}(s),b=s}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(Ue.PreUpdate,De([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let o=0===c?0:(e-c)/1e3;c=e,o=Math.min(o,.1);const i=f();if(null!==i&&(l+=o,l>=.5)){l-=.5,a=!a;n.get(i,Ro).dirty=!0}const r=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Ro)||(r.releaseTexture(t),s.delete(e));const u=n.getEntitiesWithComponents([Ro,Ts]);for(const e of u){const t=n.get(e,Ro);if(!t.dirty)continue;const s=n.get(e,Ts),o=Math.ceil(s.size.x),i=Math.ceil(s.size.y);o<=0||i<=0||(Cs(n,e),S(e,t,o,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Bo=new ko,zo={Simple:0,Sliced:1,Tiled:2,Filled:3},Uo={Horizontal:0,Vertical:1},$o={Left:0,Right:1,Bottom:2,Top:3},Do=X("Image",{texture:I,color:{r:1,g:1,b:1,a:1},imageType:zo.Simple,fillMethod:Uo.Horizontal,fillOrigin:$o.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Lo=Xs({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,layer:e=>e.image.layer,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?Ds(e.uiRect):0,rectHeight:e=>e.uiRect?Ls(e.uiRect):0,enabled:e=>e.image.enabled});const Wo=new class{build(e){Q("Image",Do);const t=e.world,n=new Map;e.addSystemToSchedule(Ue.PreUpdate,De([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,Do)||n.delete(e);const e=t.getEntitiesWithComponents([Do]);for(const s of e){const e=t.get(s,Do),o=t.has(s,Ts)?t.get(s,Ts):null,i={image:e,uiRect:o},r=n.get(s);if(r&&!Lo.changed(r,i))continue;Cs(t,s);const a=t.get(s,re);if(e.enabled){if(a.texture=e.texture,a.color.r=e.color.r,a.color.g=e.color.g,a.color.b=e.color.b,a.color.a=e.color.a,a.layer=e.layer,a.material=e.material,o&&(a.size.x=Ds(o),a.size.y=Ls(o)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===zo.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===Uo.Horizontal?e.fillOrigin===$o.Left?(a.uvScale.x=t,a.size.x=n*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=n*t):e.fillOrigin===$o.Bottom?(a.uvScale.y=t,a.size.y=s*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=s*t)}else e.imageType===zo.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale.x=a.size.x/e.tileSize.x,a.uvScale.y=a.size.y/e.tileSize.y);t.insert(s,re,a),n.set(s,Lo.take(i))}else a.color.a=0,t.insert(s,re,a),n.set(s,Lo.take(i))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},Oo=X("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Ho=X("ToggleGroup",{allowSwitchOff:!1});const jo=new class{build(e){Q("Toggle",Oo),Q("ToggleGroup",Ho);const t=e.world,n=new Set;e.addSystemToSchedule(Ue.Update,De([Me(_o)],e=>{const s=t.getEntitiesWithComponents([Oo]),o=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,Oo);s.isOn&&0!==s.group&&t.valid(s.group)&&(o.has(s.group)?s.isOn=!1:o.set(s.group,e))}const i=new Map;for(const e of s){const n=t.get(e,Oo);if(0!==n.group&&t.valid(n.group)){let t=i.get(n.group);t||(t=[],i.set(n.group,t)),t.push(e)}}for(const n of s){if(Hs(t,n,fo,{enabled:!0}),!t.has(n,po))continue;const s=t.get(n,po),o=t.get(n,Oo),r=t.get(n,fo);if(s.justPressed&&r.enabled){const s=o.group,r=0!==s&&t.valid(s)&&t.has(s,Ho);if(o.isOn&&r){if(!t.get(s,Ho).allowSwitchOff)continue}if(o.isOn=!o.isOn,o.isOn&&r){const o=i.get(s);if(o)for(const s of o){if(s===n)continue;const o=t.get(s,Oo);o.isOn&&(o.isOn=!1,e.emit(s,"change"))}}e.emit(n,"change")}if(o.graphicEntity&&t.valid(o.graphicEntity)&&t.has(o.graphicEntity,re)){const e=t.get(o.graphicEntity,re);e.enabled=o.isOn,t.insert(o.graphicEntity,re,e)}if(o.transition&&t.has(n,re)){const e=t.get(n,re);e.color=ks(o.transition,r.enabled,s.pressed,s.hovered),t.insert(n,re,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},Xo=Ps,Yo=X("ProgressBar",{value:0,fillEntity:0,direction:Ps.LeftToRight});const Vo=new class{build(e){Q("ProgressBar",Yo);const t=e.world;e.addSystemToSchedule(Ue.PreUpdate,De([],()=>{const e=t.getEntitiesWithComponents([Yo,Ts]);for(const n of e){const e=t.get(n,Yo);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=Math.max(0,Math.min(1,e.value));Fs(t,e.fillEntity,e.direction,s)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}},No=X("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Go=X("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}});const qo=new class{build(e){Q("Draggable",No),Q("DragState",Go);const t=e.world,n=e.getResource(_o);let s=null,o={x:0,y:0},i=null;e.addSystemToSchedule(Ue.PreUpdate,De([Me(Ye),Me(nt)],(e,r)=>{if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([No,po]);let n=null,i=-1/0,r=-1;for(const s of e){if(!t.get(s,No).enabled)continue;if(t.get(s,po).hovered){let e=0;t.has(s,re)&&(e=t.get(s,re).layer);const o=$s(t,s);(e>i||e===i&&o>=r)&&(i=e,r=o,n=s)}}if(null!==n){s=n,o={x:a.x,y:a.y},t.has(n,Go)||t.insert(n,Go);const e=t.get(n,Go),i=t.get(n,ie);e.startWorldPos={x:i.position.x,y:i.position.y},e.currentWorldPos={x:i.position.x,y:i.position.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,Go)){t.get(s,Go).isDragging=!1}s=null}if(null!==s&&null===i){if(!t.valid(s))return void(s=null);const e=a.x-o.x,l=a.y-o.y,c=Math.sqrt(e*e+l*l),u=t.get(s,No);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){i=s,s=null;t.get(i,Go).isDragging=!0,n.emit(i,"drag_start")}}if(null!==i){if(!t.valid(i)||!t.has(i,Go))return void(i=null);const s=t.get(i,Go),o=t.get(i,No),r=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+r,u=s.startWorldPos.y+l;const h=function(e,t,n,s){let o=e.lockX?t.startWorldPos.x:n,i=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(o=Math.max(o,e.constraintMin.x),i=Math.max(i,e.constraintMin.y)),null!==e.constraintMax&&(o=Math.min(o,e.constraintMax.x),i=Math.min(i,e.constraintMax.y)),{x:o,y:i}}(o,s,c,u);c=h.x,u=h.y;const d=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-d,y:u-f},s.currentWorldPos={x:c,y:u},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:u-s.startWorldPos.y},t.has(i,oe)){const e=function(e,t,n,s){if(!e.has(t,ue))return{x:n,y:s};const o=e.get(t,ue).entity;if(!e.valid(o)||!e.has(o,ie))return{x:n,y:s};const i=e.get(o,ie),r=0!==i.scale.x?i.scale.x:1,a=0!==i.scale.y?i.scale.y:1,l=io(i.rotation.z,i.rotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(n*u-s*c)/r,y:(n*c+s*u)/a}}(t,i,s.deltaWorld.x,s.deltaWorld.y),n=t.get(i,oe);n.position.x+=e.x,n.position.y+=e.y,t.insert(i,oe,n)}n.emit(i,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(i,"drag_end"),i=null)}},{name:"DragSystem"}))}},Jo=X("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135});const Ko=new class{build(e){Q("ScrollView",Jo);const t=e.world,n=new Map;let s=0;e.addSystemToSchedule(Ue.PreUpdate,De([Me(Ye),Me(nt)],(e,o)=>{const i=performance.now()/1e3,r=s>0?Math.min(i-s,.05):0;if(s=i,!o.valid)return;for(const[e]of n)t.valid(e)||n.delete(e);const a={x:o.worldMouseX,y:o.worldMouseY},l=t.getEntitiesWithComponents([Jo,Ts]);for(const s of l){Hs(t,s,fo,{enabled:!0,blockRaycast:!0}),Hs(t,s,eo,{enabled:!0,mode:"scissor"});const o=t.get(s,Jo),i=t.get(s,Ts);let l=n.get(s);l||(l={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0},n.set(s,l));const c=t.has(s,po)?t.get(s,po):null;if(c?.justPressed&&(l.isDragging=!0,l.lastWorldX=a.x,l.lastWorldY=a.y,l.velocityX=0,l.velocityY=0),l.isDragging&&e.isMouseButtonDown(0)){const e=a.x-l.lastWorldX,t=a.y-l.lastWorldY;if(o.horizontalEnabled){o.scrollX-=e;const t=r>0?-e/r:0;l.velocityX=.8*l.velocityX+.2*t}if(o.verticalEnabled){o.scrollY-=t;const e=r>0?-t/r:0;l.velocityY=.8*l.velocityY+.2*e}l.lastWorldX=a.x,l.lastWorldY=a.y}if(l.isDragging&&e.isMouseButtonReleased(0)&&(l.isDragging=!1),c?.hovered){const t=e.getScrollDelta();o.verticalEnabled&&0!==t.y&&(o.scrollY+=.1*t.y,l.velocityY=0),o.horizontalEnabled&&0!==t.x&&(o.scrollX+=.1*t.x,l.velocityX=0)}if(!l.isDragging&&o.inertia&&r>0){const e=Math.pow(o.decelerationRate,60*r);o.horizontalEnabled&&Math.abs(l.velocityX)>.1?(o.scrollX+=l.velocityX*r,l.velocityX*=e):l.velocityX=0,o.verticalEnabled&&Math.abs(l.velocityY)>.1?(o.scrollY+=l.velocityY*r,l.velocityY*=e):l.velocityY=0}const u=Ds(i),h=Ls(i),d=Math.max(0,o.contentWidth-u),f=Math.max(0,o.contentHeight-h),p=o.scrollX,g=o.scrollY;if(o.scrollX=Math.max(0,Math.min(o.scrollX,d)),o.scrollY=Math.max(0,Math.min(o.scrollY,f)),o.scrollX!==p&&(l.velocityX=0),o.scrollY!==g&&(l.velocityY=0),0!==o.contentEntity&&t.valid(o.contentEntity)&&t.has(o.contentEntity,oe)){const e=t.get(o.contentEntity,oe);e.position.x=-o.scrollX,e.position.y=o.scrollY,t.insert(o.contentEntity,oe,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UIInteractionSystem"]})}},Qo=Ps,Zo=X("Slider",{value:0,minValue:0,maxValue:1,direction:Ps.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});const ei=new class{build(e){Q("Slider",Zo);const t=e.world;let n=null;e.addSystemToSchedule(Ue.PreUpdate,De([Me(Ye),Me(nt),Me(_o)],(e,s,o)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const i=s.worldMouseX,r=s.worldMouseY,a=t.getEntitiesWithComponents([Zo,Ts,ie]);for(const s of a){Hs(t,s,fo,{enabled:!0,blockRaycast:!0});const a=t.get(s,Zo),l=t.get(s,Ts),c=t.get(s,ie),u=t.has(s,po)?t.get(s,po):null,h=a.handleEntity;if(0!==h&&t.valid(h)&&(Hs(t,h,fo,{enabled:!0,blockRaycast:!1}),t.has(h,fo))){const e=t.get(h,fo);e.blockRaycast&&(e.blockRaycast=!1,t.insert(h,fo,e))}let d=u?.justPressed??!1;if(!d&&0!==h&&t.valid(h)&&t.has(h,po)){d=t.get(h,po).justPressed}if(d&&(n=s),n===s&&e.isMouseButtonDown(0)){const e=Ds(l),n=Ls(l),u=e*c.scale.x,h=n*c.scale.y,d=io(c.rotation.z,c.rotation.w),f=Math.sin(-d),p=Math.cos(-d),g=i-c.position.x,y=r-c.position.y,m=g*p-y*f,_=g*f+y*p,x=-l.pivot.x*u,w=-l.pivot.y*h;let v;switch(a.direction){case Ps.LeftToRight:v=u>0?(m-x)/u:0;break;case Ps.RightToLeft:v=u>0?1-(m-x)/u:0;break;case Ps.BottomToTop:v=h>0?(_-w)/h:0;break;case Ps.TopToBottom:v=h>0?1-(_-w)/h:0}v=Math.max(0,Math.min(1,v));let b=a.minValue+v*(a.maxValue-a.minValue);a.wholeNumbers&&(b=Math.round(b));const S=a.value;a.value=Math.max(a.minValue,Math.min(a.maxValue,b)),t.insert(s,Zo,a),a.value!==S&&o.emit(s,"change")}n===s&&e.isMouseButtonReleased(0)&&(n=null);const f=a.maxValue-a.minValue,p=f>0?(a.value-a.minValue)/f:0,g=Ds(l),y=Ls(l),m=l.pivot,_={left:-m.x*g,bottom:-m.y*y,right:(1-m.x)*g,top:(1-m.y)*y};if(0!==a.fillEntity&&t.valid(a.fillEntity)&&(Fs(t,a.fillEntity,a.direction,p),js(t,a.fillEntity,_,0,0)),0!==a.handleEntity&&t.valid(a.handleEntity)){if(t.has(a.handleEntity,Ts)){const e=t.get(a.handleEntity,Ts);switch(e.offsetMin={x:0,y:0},e.offsetMax={x:0,y:0},a.direction){case Ps.LeftToRight:e.anchorMin={x:p,y:0},e.anchorMax={x:p,y:1};break;case Ps.RightToLeft:e.anchorMin={x:1-p,y:0},e.anchorMax={x:1-p,y:1};break;case Ps.BottomToTop:e.anchorMin={x:0,y:p},e.anchorMax={x:1,y:p};break;case Ps.TopToBottom:e.anchorMin={x:0,y:1-p},e.anchorMax={x:1,y:1-p}}t.insert(a.handleEntity,Ts,e)}js(t,a.handleEntity,_,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}};const ti=new class{build(e){Q("Focusable",Ao);const t=e.world,n=new Io;e.insertResource(Fo,n),e.addSystemToSchedule(Ue.Update,De([Me(Ye),Me(_o)],(e,s)=>{null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const o=t.getEntitiesWithComponents([Ao]);for(const e of o){if(!t.has(e,po))continue;t.get(e,po).justPressed&&i(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of o){if(!t.valid(n))continue;if(t.has(n,fo)){if(!t.get(n,fo).enabled)continue}const s=t.get(n,Ao);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const r=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?s.length-1:0:a?(r-1+s.length)%s.length:(r+1)%s.length,i(s[l])}function i(e){const o=n.focusedEntity;if(o===e)return;if(null!==o&&t.valid(o)&&t.has(o,Ao)){t.get(o,Ao).isFocused=!1,s.emit(o,"blur",o)}n.focus(e);t.get(e,Ao).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},ni=X("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function si(){return o()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:n,screenWidth:s,screenHeight:o}=t;return{top:n.top,bottom:o-n.bottom,left:n.left,right:s-n.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}const oi=new class{build(e){Q("SafeArea",ni);const t=e.world;let n=si(),s=!0,i=0,r=0;if(o()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=si(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=si(),s=!0});e.addSystemToSchedule(Ue.PreUpdate,De([Me(nt)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===i&&a===r||(i=e.screenH,r=a,s=!0),!s)return;s=!1;const l=f(),c=o()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([ni,Ts]);for(const e of u){const s=t.get(e,ni),o=t.get(e,Ts),i=s.applyTop?n.top*c:0,r=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let u=!1;o.offsetMin.x===a&&o.offsetMin.y===r||(o.offsetMin={x:a,y:r},u=!0),o.offsetMax.x===-l&&o.offsetMax.y===-i||(o.offsetMax={x:-l,y:-i},u=!0),u&&t.insert(e,Ts,o)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},ii=X("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let ri=null;function ai(e,t){if(!ri)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=ri.get(e);n?n.renderer=t:ri.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const li=new class{build(e){Q("ListView",ii);const t=e.world,n=new Map;ri=n,e.addSystemToSchedule(Ue.PreUpdate,De([Me(Ye)],e=>{for(const[e,s]of n)if(!t.valid(e)){for(const e of s.itemEntities.values())t.valid(e)&&t.despawn(e);n.delete(e)}const s=t.getEntitiesWithComponents([ii,Ts]);for(const o of s){Hs(t,o,fo,{enabled:!0,blockRaycast:!0}),Hs(t,o,eo,{enabled:!0,mode:"scissor"});let s=n.get(o);s||(s={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(o,s));const i=t.get(o,ii),r=t.get(o,Ts),a=r._computedHeight??r.size.y,l=r._computedWidth??r.size.x,c=t.has(o,po)?t.get(o,po):null;if(c?.hovered){const t=e.getScrollDelta();0!==t.y&&(i.scrollY+=.1*t.y)}const u=Math.max(0,i.itemCount*i.itemHeight-a);i.scrollY=Math.max(0,Math.min(i.scrollY,u));const h=Math.max(0,Math.floor(i.scrollY/i.itemHeight)-i.overscan),d=Math.min(i.itemCount,Math.ceil((i.scrollY+a)/i.itemHeight)+i.overscan);for(const[e,n]of s.itemEntities)(e<h||e>=d)&&(t.valid(n)&&t.despawn(n),s.itemEntities.delete(e));for(let e=h;e<d;e++){let n=s.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,pe,{value:`ListItem_${e}`}),t.insert(n,Ts,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:l,y:i.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,o),s.itemEntities.set(e,n),s.renderer&&s.renderer(e,n)),t.has(n,oe)){const s=t.get(n,oe);s.position.y=-(e*i.itemHeight-i.scrollY),t.insert(n,oe,s)}}s.visibleStart=h,s.visibleEnd=d}},{name:"ListViewSystem"}))}},ci=X("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const ui=new class{build(e){Q("Dropdown",ci);const t=e.world,n=new Map;function s(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const o=n.listEntity;if(0===o||!t.valid(o))return;l(o,!0),t.has(o,eo)||t.insert(o,eo,{enabled:!0,mode:"scissor"}),a(s);const i=t.has(o,Ts)?t.get(o,Ts):null,r=i?i.size.x:160;for(let e=0;e<n.options.length;e++){const i=t.spawn();t.insert(i,pe,{value:`Option_${e}`}),t.insert(i,Ts,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:30},pivot:{x:.5,y:1}}),t.insert(i,oe,{position:{x:0,y:-30*e,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(i,qs,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:1,g:1,b:1,a:1},align:Vs.Left,verticalAlign:Ns.Middle,wordWrap:!1,overflow:Gs.Clip,lineHeight:1.2}),t.insert(i,re,{texture:0,color:{r:1,g:1,b:1,a:0},size:{x:r,y:30},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(i,fo,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(i,o),s.optionEntities.push(i)}i&&(i.size.y=30*n.options.length,t.insert(o,Ts,i)),c(s)}function o(e,t,n){t.isOpen=!1,a(n),l(t.listEntity,!1)}function i(e,t,n,s,i){t.selectedIndex=s,o(0,t,n),i.emit(e,"change")}function r(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,qs))return;const s=t.get(n,qs),o=e.selectedIndex>=0&&e.selectedIndex<e.options.length?e.options[e.selectedIndex]:"";s.content!==o&&(s.content=o,t.insert(n,qs,s))}function a(e){for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[]}function l(e,n){if(0!==e&&t.valid(e)){if(t.has(e,fo)){const s=t.get(e,fo);s.enabled=n,t.insert(e,fo,s)}if(t.has(e,re)){const s=t.get(e,re);s.enabled=n,t.insert(e,re,s)}}}function c(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s)||!t.has(s,re))continue;const o=t.get(s,re);n===e.highlightIndex?o.color={...Ys}:o.color={r:1,g:1,b:1,a:0},t.insert(s,re,o)}}function u(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,po))continue;if(t.get(n,po).hovered)return!0}return!1}e.addSystemToSchedule(Ue.Update,De([Me(Ye),Me(_o)],(e,a)=>{for(const[e]of n)t.valid(e)||n.delete(e);const l=t.getEntitiesWithComponents([ci]);for(const h of l){Hs(t,h,fo,{enabled:!0,blockRaycast:!0});const l=t.get(h,ci),d=t.has(h,po)?t.get(h,po):null;let f=n.get(h);if(f||(f={optionEntities:[],highlightIndex:-1},n.set(h,f)),d?.justPressed&&(l.isOpen?o(h,l,f):s(h,l,f)),l.isOpen){for(let e=0;e<f.optionEntities.length;e++){const n=f.optionEntities[e];if(!t.valid(n)||!t.has(n,po))continue;if(t.get(n,po).justPressed){i(h,l,f,e,a);break}}e.isKeyPressed("ArrowDown")?(f.highlightIndex>=l.options.length-1?f.highlightIndex=0:f.highlightIndex++,c(f)):e.isKeyPressed("ArrowUp")?(f.highlightIndex<=0?f.highlightIndex=l.options.length-1:f.highlightIndex--,c(f)):e.isKeyPressed("Enter")&&f.highlightIndex>=0?i(h,l,f,f.highlightIndex,a):e.isKeyPressed("Escape")&&o(h,l,f),e.isMouseButtonPressed(0)&&(d?.hovered||u(f)||o(h,l,f))}r(l)}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},hi=0,di=0,fi=2,pi=X("LayoutGroup",{direction:hi,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:di,reverseOrder:!1});const gi=new class{build(e){Q("LayoutGroup",pi);const t=e.world;e.addSystemToSchedule(Ue.PreUpdate,De([],()=>{const e=t.getEntitiesWithComponents([pi,Ts,he]);for(const n of e){const e=t.get(n,pi),s=t.get(n,Ts),o=t.get(n,he);if(!o.entities||0===o.entities.length)continue;const i=[];for(const e of o.entities)t.valid(e)&&t.has(e,Ts)&&t.has(e,oe)&&i.push({entity:e,rect:t.get(e,Ts)});if(0===i.length)continue;e.reverseOrder&&i.reverse();const r=s._computedWidth??s.size.x,a=s._computedHeight??s.size.y,l=s.pivot.x,c=s.pivot.y,u=e.padding,h=e.direction===hi;let d=0;for(let n=0;n<i.length;n++){const s=i[n],o=s.rect._computedWidth??s.rect.size.x,f=s.rect._computedHeight??s.rect.size.y,p=s.rect.pivot.x,g=s.rect.pivot.y;let y,m;h?(y=-l*r+u.left+d+p*o,m=e.childAlignment===di?(1-c)*a-u.top-(1-g)*f:e.childAlignment===fi?-c*a+u.bottom+g*f:(.5-c)*a+.5*(u.bottom-u.top)+(g-.5)*f,d+=o,n<i.length-1&&(d+=e.spacing)):(y=e.childAlignment===di?-l*r+u.left+p*o:e.childAlignment===fi?(1-l)*r-u.right-(1-p)*o:(.5-l)*r+.5*(u.left-u.right)+(p-.5)*o,m=(1-c)*a-u.top-d-(1-g)*f,d+=f,n<i.length-1&&(d+=e.spacing)),s.rect._layoutManaged=!0;const _=t.get(s.entity,oe);_.position.x=y,_.position.y=m,t.insert(s.entity,oe,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};function yi(e,t,n){if(e.has(t,re)&&e.has(t,Ts)){const s=e.get(t,re);s.layer!==n&&(s.layer=n,e.insert(t,re,s)),n++}if(!e.has(t,he))return n;const s=e.get(t,he);if(!s||!s.entities)return n;for(const t of s.entities)e.valid(t)&&(n=yi(e,t,n));return n}const mi=new class{build(e){const t=e.world;e.addSystemToSchedule(Ue.PostUpdate,De([],()=>{let e=0;const n=t.getEntitiesWithComponents([xo,Ts]);for(const s of n)e=yi(t,s,e)},{name:"UIRenderOrderSystem"}))}};async function _i(e,t,n){const s=e.getResource(ls);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function xi(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 wi=Se({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),vi=Se(null,"PhysicsAPI");function bi(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Si(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Mi{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(wi,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=xi(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const o=function(e){const t=e.world.getEntitiesWithComponents([le]);for(const n of t){const t=e.world.get(n,le);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/o,r=e.world;e.addSystemToSchedule(Ue.PostUpdate,De([Me(Ce)],a=>{const l=r.getEntitiesWithComponents([me,oe,ie]),c=new Set;for(const o of l){c.add(o);const a=r.get(o,me),l=r.get(o,ie);if(t.has(o)){const e=n.get(o);!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(o,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const r=bi(l.rotation);s._physics_createBody(o,a.bodyType,l.position.x*i,l.position.y*i,r,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Pi(e,s,o),t.add(o),n.set(o,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===ve.Kinematic){const e=bi(l.rotation);s._physics_setBodyTransform(o,l.position.x*i,l.position.y*i,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 o=t._physics_getDynamicBodyTransforms(),i=o>>2;for(let o=0;o<s;o++){const s=i+4*o,r=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(r))continue;const u=e.world.get(r,oe);if(!u)continue;let h=a,d=l,f=c;if(e.world.has(r,ue)){const t=e.world.get(r,ue);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ie)){const n=e.world.get(t.entity,ie),s=bi(n.rotation),o=a-n.position.x,i=l-n.position.y,r=Math.cos(-s),u=Math.sin(-s);h=(o*r-i*u)/(0!==n.scale.x?n.scale.x:1),d=(o*u+i*r)/(0!==n.scale.y?n.scale.y:1),f=c-s}}u.position.x=h,u.position.y=d;const p=Si(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(r,oe,u)}}(e,s,o),function(e,t,n){t._physics_collectEvents();const s=[],o=t._physics_getCollisionEnterCount();if(o>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<o;i++){const o=e+6*i;s.push({entityA:t.HEAPU32[o],entityB:t.HEAPU32[o+1],normalX:t.HEAPF32[o+2],normalY:t.HEAPF32[o+3],contactX:t.HEAPF32[o+4]*n,contactY:t.HEAPF32[o+5]*n})}}const i=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<r;n++){const s=e+2*n;i.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(wi,{collisionEnters:s,collisionExits:i,sensorEnters:a,sensorExits:c})}(e,s,o)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(vi,Ei._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function Pi(e,t,n){const s=e.world;if(s.has(n,_e)){const e=s.get(n,_e);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,xe)){const e=s.get(n,xe);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,we)){const e=s.get(n,we);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 Ei{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(Ei.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 Ti(e,t,n=!0){const s=e.getResourceManager(),o=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,o);const i=s.createTexture(t.width,t.height,o,t.pixels.length,1,n);return e._free(o),i}function Ci(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 Ri(e,t,n,s){const o=e.scale.x*t*(n?-1:1),i=e.scale.y*t*(s?-1:1),r=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,h=a+a,d=l+l,f=c+c,p=a*h,g=a*d,y=a*f,m=l*d,_=l*f,x=c*f,w=u*h,v=u*d,b=u*f;return new Float32Array([(1-(m+x))*o,(g+b)*o,(y-v)*o,0,(g-b)*i,(1-(p+x))*i,(_+w)*i,0,(y+v)*r,(_-w)*r,(1-(p+m))*r,0,e.position.x,e.position.y,e.position.z,1])}async function Ai(e,t,n,s,o,i,r,a,l){const c=await async function(e,t,n){const s={};for(const o of t.entities)for(const t of o.components){const o=Et(t.type);for(const i of o){if("texture"!==i.type)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{s[o]=Ti(e,await n.loadPixels(o))}catch{s[o]=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 o=n[e];if(o&&o>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(o,e.left,e.right,e.top,e.bottom)}}}}(t,n,c);let u={},h=null;if(o&&(h=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(o),u=await async function(e,t,n,s,o){const i={};for(const r of s.entities)for(const s of r.components){const r=Tt(s.type);if(!r||!s.data)continue;const a=s.data[r.skeletonField],l=s.data[r.atlasField];if(!a||!l)continue;const c=o.resolvePath(a),u=o.resolvePath(l);try{const s=await o.readText(l),r="binary"===jt(c)?.contentType;let h,d;if(r){const e=await o.readBinary(a);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=await o.readText(a),n=(new TextEncoder).encode(e);d=n.length,h=t._malloc(d+1),t.HEAPU8.set(n,h),t.HEAPU8[h+d]=0}const f=n.loadSkeleton(h,d,s,s.length,r);if(t._free(h),f<0)continue;i[a]=f;const p=Ci(s),g=u.substring(0,u.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=g+"/"+p[t];try{const i=o.loadPixelsRaw?await o.loadPixelsRaw(s):await o.loadPixels(s),r=Ti(e,i,!1),a=e.getResourceManager().getTextureGLId(r);n.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,o,h,n,s)),i){const t={gravity:r?.gravity??{...P},fixedTimestep:r?.fixedTimestep??E,subStepCount:r?.subStepCount??4};new Mi("",t,()=>Promise.resolve(i)).build(e)}const d=await async function(e,t,n){const s={};for(const o of t.entities)for(const t of o.components){const o=Et(t.type).find(e=>"font"===e.type);if(!o)continue;const i=t.data[o.field];if("string"==typeof i&&i&&void 0===s[i])try{let t,o;const r=jt(i);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await n.readText(i)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){s[i]=0;continue}const a=i.substring(0,i.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(i),o=i.substring(0,i.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[i]=0;continue}const l=o?`${o}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=Ti(e,c,!1),h=e.getResourceManager();s[i]=h.loadBitmapFont(t,u,c.width,c.height)}catch{s[i]=0}}return s}(t,n,s),f=await async function(e,t){const n={},s={};for(const o of e.entities)for(const e of o.components){if(!e.data)continue;const o=Et(e.type).find(e=>"material"===e.type);if(!o)continue;const i=e.data[o.field];if("string"==typeof i&&i&&void 0===n[i])try{const e=JSON.parse(await t.readText(i));if(!e.vertexSource||!e.fragmentSource){n[i]=0;continue}const o=e.vertexSource+e.fragmentSource;let r=s[o];r||(r=dt.createShader(e.vertexSource,e.fragmentSource),s[o]=r),n[i]=dt.createFromAsset(e,r)}catch{n[i]=0}}return n}(n,s);!function(e,t,n,s){const o={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=Et(e.type);if(0===t.length)continue;const n=e.data;for(const e of t)"string"==typeof n[e.field]&&(n[e.field]=o[e.type][n[e.field]]||0)}}(n,c,d,f);const p=Ft(e.world,n);if(l&&e.hasResource(ls))for(const t of p.values())e.world.insert(t,ge,{scene:l,persistent:!1});if(o&&h){const s=function(e,t,n,s){const o={};for(const i of t.entities)if(!1!==i.visible)for(const t of i.components){const r=Tt(t.type);if(!r||!t.data)continue;const a=n[t.data[r.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=s.get(i.id);void 0!==c&&(o[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return o}(h,n,u,p);!function(e,t,n,s,o){let i=0;e.setSpineRenderer((r,a)=>{let l=a-i;i=a,(l<=0||l>.5)&&(l=M);const c=e.world;for(const e in o){const i=Number(e),r=o[e],a=c.has(i,fe)?c.get(i,fe):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&s.update(r,l*h);let d=0;if(c.has(i,ie)){const e=Ri(c.get(i,ie),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=s.getMeshBatchCount(r);for(let e=0;e<f;e++){const o=s.getMeshBatchVertexCount(r,e),i=s.getMeshBatchIndexCount(r,e);if(!o||!i)continue;const a=8*o*4,l=2*i,c=n._malloc(a),u=n._malloc(l),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(r,e,c,u,h,f);const p=n.HEAPU32[h>>2],g=n.HEAPU32[f>>2],y=new Float32Array(n.HEAPF32.buffer,c,8*o),m=new Uint16Array(n.HEAPU8.buffer,u,i),_=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(y,_>>2),new Uint16Array(t.HEAPU8.buffer,x,i).set(m),t.renderer_submitTriangles(_,o,x,i,p,g,d),t._free(_),t._free(x),n._free(c),n._free(u),n._free(h),n._free(f)}d&&t._free(d)}})}(e,t,o,h,s)}if(a){const t=e.getResource(tn);t&&t.setAddressableManifest(a)}}function Ii(e,t,n){return{name:e,data:t,async setup(){await Ai(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class Fi{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 o of e.entities)for(const e of o.components){if(!e.data)continue;const o=Tt(e.type);if(o){const s=e.data[o.skeletonField],i=e.data[o.atlasField];s&&("binary"===jt(s)?.contentType?n.add(s):t.add(s)),i&&t.add(i)}const i=Et(e.type);for(const n of i){const o=e.data[n.field];"string"==typeof o&&o&&("font"===n.type?(s.add(o),t.add(o)):"material"===n.type&&t.add(o))}}const o=[];for(const e of t)o.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)o.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(o);const i=[];for(const e of s){const t=jt(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||i.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}i.length>0&&await Promise.all(i)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),o=await createImageBitmap(s),i=new OffscreenCanvas(o.width,o.height).getContext("2d");i.drawImage(o,0,0);const r=i.getImageData(0,0,o.width,o.height);return o.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const ki="__preview__";class Bi{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(ls);t.register({name:ki,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(ki),this.loadPromise_=t.load(ki).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await r(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new Fi(this.baseUrl_);await n.prefetch(t);let s=null;const o=this.app_.spineInitPromise;if(o){s=(await o).controller.raw}await Ai(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,ki)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([ae]);for(const s of n){if(e.get(s,ae).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([le]);for(const o of s){const s=e.get(o,le);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const o=this.app_.getResource(ls).getScene(ki),i=o?o.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(i,oe,r);const a={isActive:!0,projectionType:te.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:ne.ColorAndDepth};e.insert(i,ae,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(ls);await e.switchTo(ki),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 zi={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),zi.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 Ui=!1;function $i(e){Ui=e}function Di(){return Ui}function Li(){return!Ui}var Wi;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Wi||(Wi={}));class Oi{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Wi[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Wi.Debug:console.debug(t,n);break;case Wi.Info:console.log(t,n);break;case Wi.Warn:console.warn(t,n);break;case Wi.Error:console.error(t,n)}}}class Hi{constructor(){this.handlers_=[],this.minLevel_=Wi.Info,this.addHandler(new Oi)}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(Wi.Debug,e,t,n)}info(e,t,n){this.log(Wi.Info,e,t,n)}warn(e,t,n){this.log(Wi.Warn,e,t,n)}error(e,t,n){this.log(Wi.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const o={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(o)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const ji=new Hi;function Xi(){return ji}function Yi(e){ji.setMinLevel(e)}function Vi(e,t,n){ji.debug(e,t,n)}function Ni(e,t,n){ji.info(e,t,n)}function Gi(e,t,n){ji.warn(e,t,n)}function qi(e,t,n){ji.error(e,t,n)}const Ji=[Zs,ho,So,Wo,Vo,Co,qo,Ko,ei,jo,Bo,ti,oi,li,ui,gi,mi];function Ki(e,t){return function(e,t){const n=ds.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),wn(e),ct(e),$n(e),Hn(e),Jn(e),es(e);const o=new ss;n.setPipeline(o);let i=d();const r=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,o,i){i||(i=ys(e,s,t,o));const r=n.getResource(nt);if(i.length>0){const e=i[0],n=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(n.x*t),r.vpY=Math.round((1-n.y-n.h)*o),r.vpW=Math.round(n.w*t),r.vpH=Math.round(n.h*o),r.screenW=t,r.screenH=o,r.worldLeft=e.cameraX-e.halfW,r.worldRight=e.cameraX+e.halfW,r.worldBottom=e.cameraY-e.halfH,r.worldTop=e.cameraY+e.halfH,r.valid=!0}else r.valid=!1}n.insertResource(nt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=r();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;Qn.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-i)/1e3;let h;if(Qn.resize(t,l),Yn.isInitialized()&&Yn.getPassCount()>0&&!Yn.isBypassed()&&Yn.resize(t,l),n.hasResource(ls)){const e=n.getResource(ls).getActiveScenes();e.length>0&&(h=new Set(e))}o.setActiveScenes(h??null);const f=ys(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)o.render({registry:{_cpp:s},viewProjection:ps,width:t,height:l,elapsed:u});else{for(const e of f){const n=e.viewportRect,i=Math.round(n.x*t),r=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);o.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:u})}Qn.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(Ue.First,l),n.addSystemToSchedule(Ue.Last,c),n.addPlugin(sn),n.addPlugin(pn),n.addPlugin(Ne),n.addPlugin(hs),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Ji,...t})}e=p;export{ds as App,nn as AssetPlugin,on as AssetRefCounter,en as AssetServer,tn as Assets,vt as AsyncCache,de as BitmapText,st as BlendMode,ve as BodyType,_e as BoxCollider,yo as Button,go as ButtonState,ae as Camera,le as Canvas,we as CapsuleCollider,he as Children,xe as CircleCollider,ne as ClearFlags,ke as Commands,ze as CommandsInstance,y as DEFAULT_DESIGN_HEIGHT,g as DEFAULT_DESIGN_WIDTH,M as DEFAULT_FALLBACK_DT,E as DEFAULT_FIXED_TIMESTEP,w as DEFAULT_FONT_FAMILY,v as DEFAULT_FONT_SIZE,P as DEFAULT_GRAVITY,b as DEFAULT_LINE_HEIGHT,S as DEFAULT_MAX_DELTA_TIME,m as DEFAULT_PIXELS_PER_UNIT,T as DEFAULT_SPINE_SKIN,x as DEFAULT_SPRITE_SIZE,_ as DEFAULT_TEXT_CANVAS_SIZE,Fn as DataType,Go as DragState,No as Draggable,Mn as Draw,ci as Dropdown,Be as EntityCommands,Ps as FillDirection,Uo as FillMethod,$o as FillOrigin,Fo as FocusManager,Io as FocusManagerState,Ao as Focusable,ns as GLDebug,Wn as Geometry,A as INVALID_ENTITY,F as INVALID_FONT,k as INVALID_MATERIAL,I as INVALID_TEXTURE,Do as Image,zo as ImageType,Ye as Input,Ve as InputPlugin,Xe as InputState,fo as Interactable,ii as ListView,oe as LocalTransform,Wi as LogLevel,Hi as Logger,dt as Material,bt as MaterialLoader,Re as Mut,pe as Name,ue as Parent,Ei as Physics,wi as PhysicsEvents,Mi as PhysicsPlugin,Yn as PostProcess,hn as PrefabServer,dn as Prefabs,fn as PrefabsPlugin,Bi as PreviewPlugin,Yo as ProgressBar,Xo as ProgressBarDirection,te as ProjectionType,Ie as Query,Fe as QueryInstance,ss as RenderPipeline,Nn as RenderStage,zi as RenderTexture,Qn as Renderer,Me as Res,Pe as ResMut,me as RigidBody,C as RuntimeConfig,ni as SafeArea,se as ScaleMode,ls as SceneManager,as as SceneManagerState,ge as SceneOwner,Ue as Schedule,xo as ScreenSpace,Jo as ScrollView,wt as ShaderSources,Zo as Slider,Qo as SliderDirection,fe as SpineAnimation,re as Sprite,je as SystemRunner,qs as Text,Vs as TextAlign,Ro as TextInput,ko as TextInputPlugin,Gs as TextOverflow,Qs as TextPlugin,Js as TextRenderer,Ns as TextVerticalAlign,Ce as Time,Oo as Toggle,nt as UICameraInfo,mo as UIEventQueue,_o as UIEvents,po as UIInteraction,To as UIInteractionPlugin,bo as UILayoutPlugin,eo as UIMask,uo as UIMaskPlugin,Ts as UIRect,ce as Velocity,Fi as WebAssetProvider,tt as World,ie as WorldTransform,Oe as addStartupSystem,We as addSystem,He as addSystemToSchedule,Fs as applyDirectionalFill,R as applyRuntimeConfig,sn as assetPlugin,In as clearDrawCallbacks,N as clearUserComponents,$ as color,Rs as computeFillAnchors,Is as computeFillSize,As as computeHandleAnchors,Es as computeUIRectLayout,co as createMaskProcessor,Ii as createRuntimeSceneConfig,Ki as createWebApp,Vi as debug,X as defineComponent,Se as defineResource,De as defineSystem,Y as defineTag,qi as error,$t as findEntityByName,fs as flushPendingSystems,Yt as getAddressableType,Vt as getAddressableTypeByEditorType,Gt as getAllAssetExtensions,Qt as getAssetMimeType,jt as getAssetTypeEntry,Z as getComponent,Pt as getComponentAssetFields,ye as getComponentDefaults,Jt as getCustomExtensions,Xt as getEditorType,Xi as getLogger,t as getPlatform,s as getPlatformType,V as getUserComponent,Kt as getWeChatPackOptions,Ni as info,wn as initDrawAPI,es as initGLDebugAPI,$n as initGeometryAPI,ct as initMaterialAPI,Hn as initPostProcessAPI,Jn as initRendererAPI,Ne as inputPlugin,an as instantiatePrefab,to as intersectRects,no as invertMatrix4,J as isBuiltinComponent,Zt as isCustomExtension,Di as isEditor,Nt as isKnownAssetExtension,n as isPlatformInitialized,Li as isRuntime,ot as isTextureRef,o as isWeChat,i as isWeb,zt as loadComponent,xi as loadPhysicsModule,Ai as loadRuntimeScene,Ft as loadSceneData,kt as loadSceneWithAssets,qt as looksLikeAssetPath,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,ao as pointInOBB,oo as pointInWorldRect,pn as prefabsPlugin,D as quat,Q as registerComponent,Mt as registerComponentAssetFields,Rt as registerComponentEntityFields,Rn as registerDrawCallback,rn as registerEmbeddedAssets,xt as registerMaterialCallback,hs as sceneManagerPlugin,so as screenToWorld,$i as setEditorMode,ai as setListViewRenderer,Yi as setLogLevel,Qe as setWasmErrorHandler,vn as shutdownDrawAPI,ts as shutdownGLDebugAPI,Dn as shutdownGeometryAPI,ut as shutdownMaterialAPI,jn as shutdownPostProcessAPI,Kn as shutdownRendererAPI,Ws as syncFillSpriteSize,Bo as textInputPlugin,Zs as textPlugin,_i as transitionTo,Co as uiInteractionPlugin,So as uiLayoutPlugin,ho as uiMaskPlugin,Ji as uiPlugins,G as unregisterComponent,An as unregisterDrawCallback,Ut as updateCameraAspectRatio,B as vec2,z as vec3,U as vec4,Gi as warn,cs as wrapSceneSystem};//# sourceMappingURL=index.js.mapdiff --git a/desktop/public/sdk/esm/physics/index.d.ts b/desktop/public/sdk/esm/physics/index.d.tsindex 35b7df4dc..8a71bda6c 100644--- a/desktop/public/sdk/esm/physics/index.d.ts+++ b/desktop/public/sdk/esm/physics/index.d.ts@@ -693,6 +693,7 @@ interface Plugin {name?: string;dependencies?: ResourceDef<any>[];build(app: App): void;+ cleanup?(): void;}declare class App {private readonly world_;diff --git a/desktop/public/sdk/esm/spine/index.d.ts b/desktop/public/sdk/esm/spine/index.d.tsindex cf81daf4a..b7c1eb858 100644--- a/desktop/public/sdk/esm/spine/index.d.ts+++ b/desktop/public/sdk/esm/spine/index.d.ts@@ -765,6 +765,7 @@ interface Plugin {name?: string;dependencies?: ResourceDef<any>[];build(app: App): void;+ cleanup?(): void;}declare class App {private readonly world_;