Skip to content

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

chore: sync SDK build outputs

esengineb05f7c18d029
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.js
index 5843da473..865d27231 100644
--- a/desktop/public/sdk/cjs/esengine.wechat.js
+++ b/desktop/public/sdk/cjs/esengine.wechat.js
@@ -1,2 +1,2 @@
-"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function r(e,r){return t().fetch(e,r)}async function s(e){return t().readFile(e)}async function n(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,r){return t().createCanvas(e,r)}function a(){return t().now()}function l(e,t){return new Promise((r,s)=>{const n=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===n?"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];r({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,r="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(r).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function c(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const r=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(r,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 "${r}": ${t}`)}}let u=null;function d(){return u||(u=wx.getFileSystemManager()),u}function h(e){return new Promise((t,r)=>{d().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function p(e,t="utf-8"){return new Promise((r,s)=>{d().readFile({filePath:e,encoding:t,success:e=>{r(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function f(e){return new Promise(t=>{d().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}let m=null,g=null;function x(e){return new Promise((t,r)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>r(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function y(e){const{width:t,height:r}=e,{ctx:s}=function(e,t){return m||(m=wx.createCanvas(),m.width=e,m.height=t,g=m.getContext("2d")),(m.width<e||m.height<t)&&(m.width=Math.max(m.width,e),m.height=Math.max(m.height,t)),{canvas:m,ctx:g}}(t,r);s.clearRect(0,0,t,r),s.drawImage(e,0,0);const n=s.getImageData(0,0,t,r);return{width:t,height:r,pixels:new Uint8Array(n.data.buffer)}}let _=!1;const w=new class{constructor(){this.name="wechat"}async fetch(e,t){return l(e,t)}async readFile(e){return h(e)}async readTextFile(e){return p(e)}async fileExists(e){return f(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return c(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const r=wx.createCanvas();return r.width=e,r.height=t,r}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{const r=t.touches[0];r&&e.onPointerDown(0,r.clientX,r.clientY)}),wx.onTouchMove(t=>{const r=t.touches[0];r&&e.onPointerMove(r.clientX,r.clientY)}),wx.onTouchEnd(()=>{e.onPointerUp(0)})}},b=4294967295,v=4294967295;function S(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const P=S("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),C=S("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),T=S("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),A=S("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),E={Static:0,Kinematic:1,Dynamic:2};let M=0;function R(e,t){const r=++M;return{_id:Symbol(`Component_${r}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function I(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function B(e,t){const r=I(),s=r.get(e);if(s)return s;const n=R(e,t);return r.set(e,n),k(e,t,!1),n}function F(e){const t=I(),r=t.get(e);if(r)return r;const s=R(e,{});return t.set(e,s),k(e,{},!0),s}function U(e){return I().get(e)}function k(e,t,r){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,r)}function W(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function D(e){return!0===e._builtin}const $=W("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),z=W("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),L=W("Sprite",{texture:b,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}),H=W("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),O=W("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),N=W("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),j=W("Parent",{entity:0}),X=W("Children",{entities:[]}),V=W("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:v}),G=W("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}),Y={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},q={LocalTransform:$,WorldTransform:z,Sprite:L,Camera:H,Canvas:O,Velocity:N,Parent:j,Children:X,BitmapText:V,SpineAnimation:G,RigidBody:P,BoxCollider:C,CircleCollider:T,CapsuleCollider:A};let J=0;function K(e,t){const r=++J;return{_id:Symbol(`Resource_${r}_${t??""}`),_name:t??`Resource_${r}`,_default:e}}function Q(e){return{_type:"res",_resource:e}}class Z{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}}class ee{constructor(){this.resources_=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)}getResMut(e){return new Z(this.get(e),t=>this.set(e,t))}}const te=K({delta:0,elapsed:0,frameCount:0},"Time");function re(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}class se{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)}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,r=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),n=r.length,o=e.length>0,i=t.length>0,a=new Array(n+1);let l=null,c=[];try{for(const u of s){if(null!==l&&o){for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}c.length=0}if(i){let e=!1;for(let r=0;r<t.length;r++)if(this.world_.has(u,t[r])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<n;e++)a[e+1]=this.world_.get(u,r[e]);if(o){for(let t=0;t<e.length;t++){const s=e[t];c.push({component:r[s],data:a[s+1]})}l=u}yield a}}finally{if(null!==l&&o)for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}}}forEach(e){for(const[t,...r]of this)e(t,...r)}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 ne{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 r;return r=D(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:r}):this.commands_.queueInsert(this.entityRef_.entity,e,r),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 oe{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ne(this,null);return this.spawned_.push(e),e}entity(e){return new ne(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,r){this.pending_.push({type:"insert",entity:e,component:t,data:r})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const r=this.world_.spawn();t.entity=r;for(const t of e)this.world_.insert(r,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const r of e.components)this.world_.insert(t,r.component,r.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var ie;exports.Schedule=void 0,(ie=exports.Schedule||(exports.Schedule={}))[ie.Startup=0]="Startup",ie[ie.First=1]="First",ie[ie.PreUpdate=2]="PreUpdate",ie[ie.Update=3]="Update",ie[ie.PostUpdate=4]="PostUpdate",ie[ie.Last=5]="Last",ie[ie.FixedPreUpdate=10]="FixedPreUpdate",ie[ie.FixedUpdate=11]="FixedUpdate",ie[ie.FixedPostUpdate=12]="FixedPostUpdate";let ae=0;function le(e,t,r){const s=++ae;return{_id:Symbol(`System_${s}_${r?.name??""}`),_params:e,_fn:t,_name:r?.name??`System_${s}`}}function ce(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class ue{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 r=0;r<e._params.length;r++)t[r]=this.resolveParam(e._params[r]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof oe&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new se(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new oe(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 he=K(new de,"Input");class pe{constructor(e){this.target_=e??null}build(e){const r=new de;e.insertResource(he,r),t().bindInputEvents({onKeyDown(e){r.keysDown.has(e)||r.keysPressed.add(e),r.keysDown.add(e)},onKeyUp(e){r.keysDown.delete(e),r.keysReleased.add(e)},onPointerMove(e,t){r.mouseX=e,r.mouseY=t},onPointerDown(e,t,s){r.mouseX=t,r.mouseY=s,r.mouseButtons.add(e),r.mouseButtonsPressed.add(e)},onPointerUp(e){r.mouseButtons.delete(e),r.mouseButtonsReleased.add(e)},onWheel(e,t){r.scrollDeltaX+=e,r.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.Last,le([],()=>{r.keysPressed.clear(),r.keysReleased.clear(),r.mouseButtonsPressed.clear(),r.mouseButtonsReleased.clear(),r.scrollDeltaX=0,r.scrollDeltaY=0},{name:"InputClearSystem"}))}}const fe=new pe;function me(e){const t={};for(const r of Object.keys(e)){const s=e[r];if(null==s||"object"!=typeof s||Array.isArray(s))t[r]=s;else{const e=s;t[r]="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}:me(e)}}return t}class ge{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,r){return D(t)?this.insertBuiltin(e,t,r):this.insertScript(e,t,r)}get(e,t){return D(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return D(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){D(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,r){const s={};if(null!=r&&"object"==typeof r)for(const[e,t]of Object.entries(r))void 0!==t&&(s[e]=t);const n={...t._default,...s};if(this.cppRegistry_){const r=`add${t._cppName}`,s=this.cppRegistry_[r];s?.call(this.cppRegistry_,e,me(n))}return n}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const r=`get${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const r=`has${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const r=`remove${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e)}insertScript(e,t,r){const s=t.create(r);return this.getStorage(t).set(e,s),s}getScript(e,t){const r=this.tsStorage_.get(t._id);if(!r)throw new Error(`Component not found: ${t._name}`);return r.get(e)}hasScript(e,t){const r=this.tsStorage_.get(t._id);return r?.has(e)??!1}removeScript(e,t){const r=this.tsStorage_.get(t._id);r?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();let t=null,r=1/0;for(const s of e)if(!D(s)){const e=this.tsStorage_.get(s._id),n=e?e.size:0;n<r&&(r=n,t=e??null)}const s=[],n=t?t.keys():this.entities_;for(const t of n){let r=!0;for(const s of e)if(!this.has(t,s)){r=!1;break}r&&s.push(t)}return s}}var xe,ye,_e;exports.TextAlign=void 0,(xe=exports.TextAlign||(exports.TextAlign={}))[xe.Left=0]="Left",xe[xe.Center=1]="Center",xe[xe.Right=2]="Right",exports.TextVerticalAlign=void 0,(ye=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[ye.Top=0]="Top",ye[ye.Middle=1]="Middle",ye[ye.Bottom=2]="Bottom",exports.TextOverflow=void 0,(_e=exports.TextOverflow||(exports.TextOverflow={}))[_e.Visible=0]="Visible",_e[_e.Clip=1]="Clip",_e[_e.Ellipsis=2]="Ellipsis";const we=B("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2});class be{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const r=this.ctx,s=this.canvas;r.font=`${e.fontSize}px ${e.fontFamily}`;const n=t&&t.size.x>0&&t.size.y>0,o=n?t.size.x:0,i=n?t.size.y:0,a=e.wordWrap&&n;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=n?Math.ceil(o):d+2*u,f=n?Math.ceil(i):h+2*u;if(n&&e.overflow===exports.TextOverflow.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<p||s.height<f){const e=Math.max(s.width,this.nextPowerOf2(p)),t=Math.max(s.height,this.nextPowerOf2(f));s.width=e,s.height=t}const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),x=Math.round(255*e.color.b),y=e.color.a;r.clearRect(0,0,s.width,s.height),r.font=`${e.fontSize}px ${e.fontFamily}`,r.textAlign=this.mapAlign(e.align),r.textBaseline="top",r.fillStyle=`rgba(${m}, ${g}, ${x}, ${y})`,n&&e.overflow===exports.TextOverflow.Clip&&(r.save(),r.beginPath(),r.rect(0,0,p,f),r.clip());const _=l.length*c;let w;if(n)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-_)/2;break;case exports.TextVerticalAlign.Bottom:w=f-_-u;break;default:w=u}else w=u;let b=w;for(const t of l){let s;switch(e.align){case exports.TextAlign.Left:s=u;break;case exports.TextAlign.Center:s=p/2;break;case exports.TextAlign.Right:s=p-u;break;default:s=u}r.fillText(t,s,b),b+=c}n&&e.overflow===exports.TextOverflow.Clip&&r.restore();const v=r.getImageData(0,0,p,f),S=new Uint8Array(v.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const T=P.createTexture(p,f,C,S.length,1,!0);return this.module._free(C),{textureHandle:T,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let r=e;for(;r.length>0&&this.ctx.measureText(r+"...").width>t;)r=r.slice(0,-1);return r+"..."}renderForEntity(e,t,r){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const n=this.renderText(t,r);return this.cache.set(e,n),n}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[r,s]of this.cache)e(r)||(t.releaseTexture(s.textureHandle),this.cache.delete(r))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const r=e.split("\n"),s=[];for(const e of r){if(!e){s.push("");continue}let r="";for(const n of e){const e=r+n;this.ctx.measureText(e).width>t&&r?(s.push(r),r=n):r=e}r&&s.push(r)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const r of e){const e=this.ctx.measureText(r),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const ve=B("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}});function Se(e){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight}}function Pe(e,t){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight}class Ce{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const r=new be(t),s=e.world,n=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,le([],()=>{r.cleanupOrphaned(e=>s.valid(e)&&s.has(e,we));for(const e of n.keys())s.valid(e)&&s.has(e,we)||n.delete(e);const e=s.getEntitiesWithComponents([we]);for(const t of e){const e=s.get(t,we),o=n.get(t);if(o&&!Pe(o,e))continue;s.has(t,L)||s.insert(t,L,{texture:b,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const i=s.has(t,ve)?s.get(t,ve):null,a=r.renderForEntity(t,e,i),l=s.get(t,L);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,L,l),n.set(t,Se(e))}}))}}const Te=new Ce,Ae=B("UIMask",{enabled:!0});function Ee(e,t){const r=Math.max(e.x,t.x),s=Math.max(e.y,t.y),n=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:r,y:s,w:Math.max(0,n-r),h:Math.max(0,o-s)}}function Me(e,t,r,s,n,o,i,a,l,c,u){const d=e-r*n,h=e+r*(1-n),p=t-s*o,f=t+s*(1-o);function m(e,t){const r=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],n=i[3]*e+i[7]*t+i[15];return[a+(.5*(r/n)+.5)*c,l+(.5*(s/n)+.5)*u]}const[g,x]=m(d,p),[y,_]=m(h,f),w=Math.min(g,y),b=Math.max(g,y),v=Math.min(x,_),S=Math.max(x,_);return{x:Math.round(w),y:Math.round(v),w:Math.round(b-w),h:Math.round(S-v)}}function Re(e,t){const r=t??new Float32Array(16),s=e[0],n=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],m=e[12],g=e[13],x=e[14],y=e[15],_=s*l-n*a,w=s*c-o*a,b=s*u-i*a,v=n*c-o*l,S=n*u-i*l,P=o*u-i*c,C=d*g-h*m,T=d*x-p*m,A=d*y-f*m,E=h*x-p*g,M=h*y-f*g,R=p*y-f*x;let I=_*R-w*M+b*E+v*A-S*T+P*C;return 0===I||(I=1/I,r[0]=(l*R-c*M+u*E)*I,r[1]=(o*M-n*R-i*E)*I,r[2]=(g*P-x*S+y*v)*I,r[3]=(p*S-h*P-f*v)*I,r[4]=(c*A-a*R-u*T)*I,r[5]=(s*R-o*A+i*T)*I,r[6]=(x*b-m*P-y*w)*I,r[7]=(d*P-p*b+f*w)*I,r[8]=(a*M-l*A+u*C)*I,r[9]=(n*A-s*M-i*C)*I,r[10]=(m*S-g*b+y*_)*I,r[11]=(h*b-d*S-f*_)*I,r[12]=(l*T-a*E-c*C)*I,r[13]=(s*E-n*T+o*C)*I,r[14]=(g*w-m*v-x*_)*I,r[15]=(d*v-h*w+p*_)*I),r}function Ie(e,t,r,s,n,o,i){const a=(e-s)/o*2-1,l=(t-n)/i*2-1,c=r[0]*a+r[4]*l+r[12],u=r[1]*a+r[5]*l+r[13],d=r[3]*a+r[7]*l+r[15];return{x:c/d,y:u/d}}function Be(e,t,r,s,n,o,i,a){return e>=r-n*i&&e<=r+n*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function Fe(e,t,r,s,n,o,i){if(!e.has(t,ve)||!e.has(t,z))return null;const a=e.get(t,ve),l=e.get(t,z),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return Me(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,r,s,n,o,i)}function Ue(e,t){return(r,s,n,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Ae]);if(0!==l.length)try{!function(e,t,r,s,n,o,i,a,l){const c=new Set;for(const e of s){t.get(e,Ae).enabled&&c.add(e)}const u=[];for(const e of s){if(!c.has(e))continue;let r=!0,s=e;for(;t.has(s,j);){const e=t.get(s,j);if(c.has(e.entity)){r=!1;break}s=e.entity}r&&u.push(e)}function d(s,u){const h=e.getChildEntities(r,s);for(const r of h){let s=u;if(c.has(r)){const e=Fe(t,r,n,o,i,a,l);e&&(s=Ee(u,e))}e.renderer_setEntityClipRect(r,s.x,s.y,s.w,s.h),d(r,s)}}for(const e of u){const r=Fe(t,e,n,o,i,a,l);r&&d(e,r)}}(e,t,r,l,s,n,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class ke{build(e){if(!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Ue(e.wasmModule,e.world))}}const We=new ke,De=B("Interactable",{enabled:!0}),$e=B("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var ze;exports.ButtonState=void 0,(ze=exports.ButtonState||(exports.ButtonState={}))[ze.Normal=0]="Normal",ze[ze.Hovered=1]="Hovered",ze[ze.Pressed=2]="Pressed",ze[ze.Disabled=3]="Disabled";const Le=B("Button",{state:exports.ButtonState.Normal,transition:null});class He{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(r=>r.entity===e&&r.type===t)}}const Oe=K(new He,"UIEvents"),Ne=K({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo"),je=new Float32Array(16);class Xe{build(e){const t=e.world,r=new He;e.insertResource(Oe,r);let s=null,n=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,le([Q(he),Q(Ne)],(e,o)=>{r.drain();const i=t.getEntitiesWithComponents([$e]);for(const e of i){const r=t.get(e,$e);r.justPressed=!1,r.justReleased=!1}if(!o.valid)return;const a="undefined"!=typeof window&&window.devicePixelRatio||1,l=e.mouseX*a,c=o.screenH-e.mouseY*a;Re(o.viewProjection,je);const u=Ie(l,c,je,o.vpX,o.vpY,o.vpW,o.vpH),d=t.getEntitiesWithComponents([De,ve,z]);let h=null,p=-1/0;for(const e of d){t.has(e,$e)||t.insert(e,$e);if(!t.get(e,De).enabled)continue;const r=t.get(e,z),s=t.get(e,ve),n=s.size.x*r.scale.x,o=s.size.y*r.scale.y;if(Be(u.x,u.y,r.position.x,r.position.y,n,o,s.pivot.x,s.pivot.y)){let r=0;t.has(e,L)&&(r=t.get(e,L).layer),r>=p&&(p=r,h=e)}}if(s!==h){if(null!==s&&t.valid(s)&&t.has(s,$e)){t.get(s,$e).hovered=!1,r.emit(s,"hover_exit")}if(null!==h){t.get(h,$e).hovered=!0,r.emit(h,"hover_enter")}s=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,$e);e.pressed=!0,e.justPressed=!0,n=h,r.emit(h,"press")}if(e.isMouseButtonReleased(0)&&null!==n){if(t.valid(n)&&t.has(n,$e)){const e=t.get(n,$e);e.pressed=!1,e.justReleased=!0,r.emit(n,"release"),n===s&&r.emit(n,"click")}n=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(exports.Schedule.Update,le([],()=>{const e=t.getEntitiesWithComponents([Le]);for(const r of e){if(t.has(r,De)||t.insert(r,De,{enabled:!0}),!t.has(r,$e))continue;const e=t.get(r,$e),s=t.get(r,Le),n=t.get(r,De),o=s.state;if(n.enabled?e.pressed?s.state=exports.ButtonState.Pressed:e.hovered?s.state=exports.ButtonState.Hovered:s.state=exports.ButtonState.Normal:s.state=exports.ButtonState.Disabled,o!==s.state&&s.transition&&t.has(r,L)){const e=t.get(r,L),n=s.transition;switch(s.state){case exports.ButtonState.Normal:e.color={...n.normalColor};break;case exports.ButtonState.Hovered:e.color={...n.hoveredColor};break;case exports.ButtonState.Pressed:e.color={...n.pressedColor};break;case exports.ButtonState.Disabled:e.color={...n.disabledColor}}t.insert(r,L,e)}}},{name:"ButtonSystem"}))}}const Ve=new Xe,Ge=F("ScreenSpace");function Ye(e,t,r,s,n,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,p,f,m;if(l===c&&u===d){const e=l+r.x,t=u+r.y,s=.5*n.x,o=.5*n.y;h=e-s,p=t-o,f=e+s,m=t+o}else h=l+r.x,p=u+r.y,f=c+s.x,m=d+s.y;return{centerX:.5*(h+f),centerY:.5*(p+m),width:f-h,height:m-p,rect:{left:h,bottom:p,right:f,top:m}}}function qe(e,t,r,s,n,o){if(!e.has(t,ve))return;const i=e.get(t,ve),a=Ye(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,r);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,$);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-n),e.insert(t,$,l),!e.has(t,X))return;const c=e.get(t,X);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&qe(e,t,a.rect,a.centerX,a.centerY,!1)}class Je{build(e){const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,le([Q(Ne)],e=>{if(!e.valid)return;const r={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(r.left+r.right),n=.5*(r.bottom+r.top),o=t.getEntitiesWithComponents([Ge,ve,$]);for(const e of o)qe(t,e,r,s,n,!0)},{name:"UILayoutSystem"}))}}const Ke=new Je,Qe=B("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class Ze{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const r=e.world,s=new Map,n=i(512,64),o=n.getContext("2d",{willReadFrequently:!0});let a=null,l=!1,c=!0,u=0,d=0;const h=function(){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}();function p(){if(null===a||!r.valid(a))return;const t=r.get(a,Qe);if(t.readOnly)return;let s=h.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),h.value=s),s!==t.value){t.value=s;e.getResource(Oe).emit(a,"change")}t.cursorPos=h.selectionStart??s.length,t.dirty=!0,g()}function f(e){if(a===e)return;m();const t=r.get(e,Qe);t.readOnly||(a=e,t.focused=!0,t.dirty=!0,h.value=t.value,h.selectionStart=t.cursorPos,h.selectionEnd=t.cursorPos,h.focus(),g())}function m(){if(null!==a&&r.valid(a)&&r.has(a,Qe)){const e=r.get(a,Qe);e.focused=!1,e.dirty=!0}a=null,h.blur()}function g(){c=!0,u=0}function x(e,i,a,l){(n.width<a||n.height<l)&&(n.width=tt(Math.max(n.width,a)),n.height=tt(Math.max(n.height,l))),o.clearRect(0,0,n.width,n.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,l),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,l),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,p=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*p.r)}, ${Math.round(255*p.g)}, ${Math.round(255*p.b)}, ${p.a})`;const f=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=et(o,h,a-2*m);let t=m;for(const r of e)o.fillText(r,m,t),t+=f}else{const e=(l-i.fontSize)/2;o.fillText(h,m,e)}if(i.focused&&c){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,r,s;if(i.multiline){const e=et(o,i.value.substring(0,i.cursorPos),a-2*m),n=e.length>0?e[e.length-1]:"";t=m+o.measureText(n).width,r=m+(e.length-1)*f,s=f}else t=m+o.measureText(e).width,r=(l-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,r,2,s)}o.restore();const g=o.getImageData(0,0,a,l),x=new Uint8Array(g.data.buffer),y=t.getResourceManager(),_=t._malloc(x.length);t.HEAPU8.set(x,_);const w=s.get(e);void 0!==w&&y.releaseTexture(w);const b=y.createTexture(a,l,_,x.length,1,!0);s.set(e,b),t._free(_);const v=r.get(e,L);v.texture=b,v.size.x=a,v.size.y=l,v.uvOffset.x=0,v.uvOffset.y=0,v.uvScale.x=1,v.uvScale.y=1,v.color={r:1,g:1,b:1,a:1},r.insert(e,L,v)}h.addEventListener("input",()=>{l||null===a||p()}),h.addEventListener("compositionstart",()=>{l=!0}),h.addEventListener("compositionend",()=>{l=!1,p()}),h.addEventListener("keydown",t=>{if(null===a)return;if("Escape"===t.key)return void m();const s=r.get(a,Qe);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(Oe).emit(a,"submit"),void m()}let n=s.cursorPos;"ArrowLeft"===t.key?n=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?n=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?n=0:"End"===t.key&&(n=s.value.length),n!==s.cursorPos&&(s.cursorPos=n,h.selectionStart=n,h.selectionEnd=n,s.dirty=!0,g())}),h.addEventListener("blur",()=>{if(null!==a&&r.valid(a)&&r.has(a,Qe)){const e=r.get(a,Qe);e.focused=!1,e.dirty=!0}a=null}),e.addSystemToSchedule(exports.Schedule.PreUpdate,le([Q(Oe)],e=>{const t=r.getEntitiesWithComponents([Qe,De]);for(const e of t){if(!r.has(e,$e))continue;if(r.get(e,$e).justPressed)return void f(e)}if(null!==a){const e=r.getEntitiesWithComponents([De]);for(const t of e){if(r.has(t,Qe))continue;if(!r.has(t,$e))continue;if(r.get(t,$e).justPressed)return void m()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(exports.Schedule.PreUpdate,le([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),n=0===d?0:(e-d)/1e3;if(d=e,null!==a&&(u+=n,u>=.5&&(u-=.5,c=!c,null!==a&&r.valid(a)&&r.has(a,Qe)))){r.get(a,Qe).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)r.valid(e)&&r.has(e,Qe)||(o.releaseTexture(t),s.delete(e));const i=r.getEntitiesWithComponents([Qe,ve]);for(const e of i){const t=r.get(e,Qe);if(!t.dirty)continue;const s=r.get(e,ve),n=Math.ceil(s.size.x),o=Math.ceil(s.size.y);n<=0||o<=0||(r.has(e,L)||r.insert(e,L,{texture:b,color:{r:1,g:1,b:1,a:1},size:{x:n,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),x(e,t,n,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function et(e,t,r){if(!t)return[""];if(r<=0)return t.split("\n");const s=t.split("\n"),n=[];for(const t of s){if(!t){n.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>r&&s?(n.push(s),s=o):s=t}s&&n.push(s)}return n.length>0?n:[""]}function tt(e){let t=1;for(;t<e;)t*=2;return t}const rt=new Ze;var st;function nt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(st=exports.BlendMode||(exports.BlendMode={}))[st.Normal=0]="Normal",st[st.Additive=1]="Additive",st[st.Multiply=2]="Multiply",st[st.Screen=3]="Screen",st[st.PremultipliedAlpha=4]="PremultipliedAlpha";let ot=null,it=null,at=1;const lt=new Map;function ct(e){ot=e,it=e.getResourceManager(),_t()}function ut(){0!==ft&&ot&&(ot._free(ft),ft=0),lt.clear(),at=1,pt=!1,it=null,ot=null}function dt(){if(!it)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return it}const ht={createShader:(e,t)=>dt().createShader(e,t),releaseShader(e){e>0&&dt().releaseShader(e)},create(e){const t=at++,r={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))r.uniforms.set(t,s);return lt.set(t,r),t},get:e=>lt.get(e),setUniform(e,t,r){const s=lt.get(e);s&&s.uniforms.set(t,r)},getUniform(e,t){const r=lt.get(e);return r?.uniforms.get(t)},setBlendMode(e,t){const r=lt.get(e);r&&(r.blendMode=t)},getBlendMode(e){const t=lt.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const r=lt.get(e);r&&(r.depthTest=t)},getShader(e){const t=lt.get(e);return t?.shader??0},release(e){lt.delete(e)},isValid:e=>lt.has(e),createFromAsset(e,t){const r={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)r[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?r[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(r[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:r,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=lt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const r=at++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return lt.set(r,s),r},toAssetData(e,t){const r=lt.get(e);if(!r)return null;const s={};for(const[e,t]of r.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:r.blendMode,depthTest:r.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 pt=!1,ft=0;const mt=4096,gt=new Map;let xt=null;function yt(e){const t=(0===ft&&ot&&(ft=ot._malloc(mt)),ft);if(0===t||!ot)return{ptr:0,count:0};let r=0,s=0;const n=ot.HEAPU8,o=ot.HEAPU32,i=ot.HEAPF32;for(const[a,l]of e){if(r+128>mt)break;let e=gt.get(a);e||(xt||(xt=new TextEncoder),e=xt.encode(a),gt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+r>>2]=c,r+=4,n.set(e,t+r),r+=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+r>>2]=d,r+=4;for(let e=0;e<4;e++)i[t+r>>2]=h[e],r+=4;s++}return{ptr:t,count:s}}function _t(){if(!ot||pt)return;ot.materialDataProvider=(e,t,r,s,n)=>{const o=lt.get(e);if(!o)return ot.HEAPU32[t>>2]=0,ot.HEAPU32[r>>2]=0,ot.HEAPU32[s>>2]=0,void(ot.HEAPU32[n>>2]=0);ot.HEAPU32[t>>2]=o.shader,ot.HEAPU32[r>>2]=o.blendMode;const{ptr:i,count:a}=yt(o.uniforms);ot.HEAPU32[s>>2]=i,ot.HEAPU32[n>>2]=a},pt=!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 bt{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const r=this.pending_.get(e);if(r)return r;const s=this.loadInternal(e);this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}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 o(t))throw new Error(`Material file not found: ${t}`);const r=await n(t);if(!r)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(r);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),a=await this.shaderLoader_.load(i);return{handle:ht.createFromAsset(s,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 r=e.substring(0,e.lastIndexOf("/"));return r?`${r}/${t}`:t}}function vt(e,t){const r=new Map;for(const s of t.entities){const t=e.spawn();if(r.set(s.id,t),e.insert(t,Y,{value:s.name}),!1!==s.visible)for(const r of s.components)Pt(e,t,r)}for(const s of t.entities)if(null!==s.parent){const t=r.get(s.id),n=r.get(s.parent);void 0!==t&&void 0!==n&&e.setParent(t,n)}return r}async function St(e,t,r){const s=new Map,n=r?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();if(s.set(i.id,t),e.insert(t,Y,{value:i.name}),!1!==i.visible)for(const s of i.components){if("Sprite"===s.type&&n){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:r?.assetBaseUrl?`${r.assetBaseUrl}/${t}`:`/${t}`;try{const r=await n.loadTexture(s);e.texture=r.handle,o.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("BitmapText"===s.type&&n){const e=s.data;if("string"==typeof e.font&&e.font)try{const t=await n.loadBitmapFont(e.font,r?.assetBaseUrl);e.font=t}catch(t){console.warn(`Failed to load bitmap font: ${e.font}`,t),e.font=0}}if("SpineAnimation"===s.type&&n){const e=s.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await n.loadSpine(t,o,r?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Pt(e,t,s)}}for(const r of t.entities)if(null!==r.parent){const t=s.get(r.id),n=s.get(r.parent);void 0!==t&&void 0!==n&&e.setParent(t,n)}if(n&&t.textureMetadata)for(const[e,r]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&r.sliceBorder&&n.setTextureMetadataByPath(t,r.sliceBorder)}return s}function Pt(e,t,r){const s=r.data;switch(r.type){case"LocalTransform":e.insert(t,$,s);break;case"Sprite":e.insert(t,L,s);break;case"Camera":e.insert(t,H,s);break;case"Canvas":e.insert(t,O,s);break;case"Text":e.insert(t,we,s);break;case"BitmapText":e.insert(t,V,s);break;case"SpineAnimation":e.insert(t,G,s);break;case"UIRect":{const r=s;r.anchor&&!r.anchorMin&&(r.anchorMin={...r.anchor},r.anchorMax={...r.anchor},delete r.anchor),e.insert(t,ve,r);break}case"UIMask":e.insert(t,Ae,s);break;case"Interactable":e.insert(t,De,s);break;case"Button":e.insert(t,Le,s);break;case"RigidBody":e.insert(t,P,s);break;case"BoxCollider":e.insert(t,C,s);break;case"CircleCollider":e.insert(t,T,s);break;case"CapsuleCollider":e.insert(t,A,s);break;default:{const n=U(r.type);n?e.insert(t,n,s):console.warn(`Unknown component type: ${r.type}`);break}}}class Ct{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const r=this.cache_.get(e);if(void 0!==r)return r;const s=this.pending_.get(e);if(s)return s;const n=t();this.pending_.set(e,n);try{const t=await n;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}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()}values(){return this.cache_.values()}}class Tt{constructor(e){this.textureCache_=new Ct,this.shaderCache_=new Ct,this.jsonCache_=new Ct,this.textCache_=new Ct,this.binaryCache_=new Ct,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Ct,this.prefabCache_=new Ct,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.module_=e,this.canvas_=i(512,512),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,r]of Object.entries(e))this.embedded_.set(t,r);this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const r of[!0,!1]){const s=this.textureCacheKey(e,r),n=this.textureCache_.get(s);n&&(t.releaseTexture(n.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);this.textureCache_.clear(),this.fontCache_.clear(),this.prefabCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.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 r=this.textureCache_.get(this.textureCacheKey(e,!0));return!!r&&(this.setTextureMetadata(r.handle,t),!0)}async loadSpine(e,t,r){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const n=this.resolveUrl(t,r),o=await this.fetchText(n);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);for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,r);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,r),c=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);return this.writeToVirtualFS(e,c)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const r=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(r,async()=>e.endsWith(".bmfont")?this.loadBmfontAsset(r):this.loadFntFile(r))}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),r=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 n=r?`${r}/${s}`:s;return this.loadFntFile(n)}async loadFntFile(e){const t=await this.fetchText(e),r=t.match(/file="([^"]+)"/);if(!r)throw new Error(`No page texture found in .fnt file: ${e}`);const s=r[1],n=e.substring(0,e.lastIndexOf("/")),o=n?`${n}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const r=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(r,()=>this.fetchJson(r))}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 r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(r):this.jsonCache_.getOrLoad(r,()=>this.fetchJson(r))}async loadText(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(r):this.textCache_.getOrLoad(r,()=>this.fetchText(r))}async loadBinary(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(r):this.binaryCache_.getOrLoad(r,()=>this.fetchBinary(r))}async loadScene(e,t){return St(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const r of Object.values(e.groups))r.assets&&t.push(...Object.values(r.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,r]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(r.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let r=this.labelIndex_.get(e);r||(r=[],this.labelIndex_.set(e,r)),r.push(t)}}this.groupAssets_.set(t,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},r=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":r.push(this.loadTexture(s.path).then(r=>{t.textures.set(e,r)}));break;case"material":r.push(this.loadMaterial(s.path).then(r=>{t.materials.set(e,r)}));break;case"spine":{const n=s.metadata?.atlas;n&&r.push(this.loadSpine(s.path,n).then(r=>{t.spine.set(e,r)}));break}case"bitmap-font":r.push(this.loadBitmapFont(s.path).then(r=>{t.fonts.set(e,r)}));break;case"prefab":r.push(this.loadPrefab(s.path).then(r=>{t.prefabs.set(e,r)}));break;case"audio":case"binary":default:r.push(this.loadBinary(s.path).then(r=>{t.binary.set(e,r)}));break;case"json":r.push(this.loadJson(s.path).then(r=>{t.json.set(e,r)}));break;case"text":r.push(this.loadText(s.path).then(r=>{t.text.set(e,r)}))}}return await Promise.all(r),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const r=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(r,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const r=await this.loadImage(e);return this.createTextureFromImage(r,t)}async loadImage(e){const r=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(r);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const n=s??r;return new Promise((r,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 r(e)}catch{}r(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=n})}createTextureFromImage(e,t){const{width:r,height:s}=e,n=this.getWebGL2Context();return n?this.createTextureWebGL2(n,e,r,s,t):this.createTextureFallback(e,r,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,r,s,n){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,n?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,r,s),width:r,height:s}}createTextureFallback(e,t,r,s){(this.canvas_.width<t||this.canvas_.height<r)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(r))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const n=this.ctx_.getImageData(0,0,t,r),o=new Uint8Array(n.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,r,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:r}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const r=e[t+3];if(r>0&&r<255){const s=255/r;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,r=this.embedded_.get(t);if(r){const t=this.decodeDataUrlText(r),{vertex:s,fragment:n}=this.parseEsShader(t);if(!s||!n)throw new Error(`Invalid shader format: ${e}`);return ht.createShader(s,n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await o(t))throw new Error(`Shader file not found: ${e}`);const s=await n(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:a}=this.parseEsShader(s);if(!i||!a)throw new Error(`Invalid shader format: ${e}`);return ht.createShader(i,a)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),r=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:r?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r.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 r=this.embedded_.get(t);if(r)return JSON.parse(this.decodeDataUrlText(r));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const r=this.embedded_.get(t);if(r)return this.decodeDataUrlText(r);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return n(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const r=this.embedded_.get(t);if(r)return this.decodeDataUrlBinary(r);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return s(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 r=this.module_.FS;if(!r)return!1;try{return this.ensureVirtualDir(e),r.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 r=e.substring(0,e.lastIndexOf("/"));if(!r)return;const s=r.split("/").filter(e=>e);let n="";for(const e of s){n=n?`${n}/${e}`:e;try{t.analyzePath(n).exists||t.mkdir(n)}catch{try{t.mkdir(n)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const r=t??this.baseUrl;return r?`${r}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const At=K(null,"Assets");class Et{build(e){const t=e.wasmModule;t?e.insertResource(At,new Tt(t)):console.warn("AssetPlugin: No WASM module available")}}const Mt=new Et;async function Rt(e,t,r){const{entities:s,rootId:n}=await It(t,r?.overrides??[],r),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 St(e,o,{assetServer:r?.assetServer,assetBaseUrl:r?.assetBaseUrl}),a=i.get(n);return void 0!==r?.parent&&e.setParent(a,r.parent),{root:a,entities:i}}async function It(e,t,r,s){const n=new Map;let o;if(void 0===s){o=0;for(const t of e.entities)t.nestedPrefab||(n.set(t.prefabEntityId,t.prefabEntityId),o=Math.max(o,t.prefabEntityId+1))}else{o=s;for(const t of e.entities)t.nestedPrefab||n.set(t.prefabEntityId,o++)}const i=[];for(const s of e.entities){if(s.nestedPrefab){if(!r?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);const e=await r.assetServer.loadPrefab(s.nestedPrefab.prefabPath,r.assetBaseUrl),t=await It(e,s.nestedPrefab.overrides,r,o);n.set(s.prefabEntityId,t.rootId),o=t.nextId;const a=t.entities.find(e=>e.id===t.rootId);a&&(a.parent=null!==s.parent?n.get(s.parent)??null:null),i.push(...t.entities);continue}const a=n.get(s.prefabEntityId),l=s.prefabEntityId===e.rootEntityId,c={id:a,prefabEntityId:s.prefabEntityId,name:s.name,parent:l?null:null!==s.parent?n.get(s.parent)??null:null,children:s.children.map(e=>n.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};Bt(c,t),i.push(c)}const a=n.get(e.rootEntityId);if(void 0===a)throw new Error("Failed to resolve prefab root entity");return{entities:i,rootId:a,nextId:o}}function Bt(e,t){for(const r of t)if(r.prefabEntityId===e.prefabEntityId)switch(r.type){case"property":if(r.componentType&&void 0!==r.propertyName){const t=e.components.find(e=>e.type===r.componentType);t&&(t.data[r.propertyName]=r.value)}break;case"name":"string"==typeof r.value&&(e.name=r.value);break;case"visibility":"boolean"==typeof r.value&&(e.visible=r.value);break;case"component_added":if(r.componentData){e.components.some(e=>e.type===r.componentData.type)||e.components.push({type:r.componentData.type,data:JSON.parse(JSON.stringify(r.componentData.data))})}break;case"component_removed":r.componentType&&(e.components=e.components.filter(e=>e.type!==r.componentType))}}class Ft{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const r=await this.assetServer_.loadPrefab(e,t?.baseUrl);return Rt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Ut=K(null,"Prefabs");class kt{build(e){const t=e.getResource(At);t?e.insertResource(Ut,new Ft(e.world,t)):console.warn("PrefabsPlugin: Assets resource not available")}}const Wt=new kt;let Dt=null,$t=0,zt=0,Lt=0;const Ht=new Float32Array(256);function Ot(e){Dt=e,$t=Dt._malloc(64),zt=Dt._malloc(64),Lt=Dt._malloc(1024)}function Nt(){Dt&&($t&&(Dt._free($t),$t=0),zt&&(Dt._free(zt),zt=0),Lt&&(Dt._free(Lt),Lt=0)),Dt=null}function jt(){if(!Dt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Dt}const Xt={r:1,g:1,b:1,a:1},Vt={begin(e){const t=jt();t.HEAPF32.set(e,$t/4),t.draw_begin($t)},end(){jt().draw_end()},line(e,t,r,s=1){jt().draw_line(e.x,e.y,t.x,t.y,r.r,r.g,r.b,r.a,s)},rect(e,t,r,s=!0){jt().draw_rect(e.x,e.y,t.x,t.y,r.r,r.g,r.b,r.a,s)},rectOutline(e,t,r,s=1){jt().draw_rectOutline(e.x,e.y,t.x,t.y,r.r,r.g,r.b,r.a,s)},circle(e,t,r,s=!0,n=32){jt().draw_circle(e.x,e.y,t,r.r,r.g,r.b,r.a,s,n)},circleOutline(e,t,r,s=1,n=32){jt().draw_circleOutline(e.x,e.y,t,r.r,r.g,r.b,r.a,s,n)},texture(e,t,r,s=Xt){jt().draw_texture(e.x,e.y,t.x,t.y,r,s.r,s.g,s.b,s.a)},textureRotated(e,t,r,s,n=Xt){jt().draw_textureRotated(e.x,e.y,t.x,t.y,r,s,n.r,n.g,n.b,n.a)},setLayer(e){jt().draw_setLayer(e)},setDepth(e){jt().draw_setDepth(e)},getDrawCallCount:()=>Dt?Dt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Dt?Dt.draw_getPrimitiveCount():0,setBlendMode(e){jt().draw_setBlendMode(e)},setDepthTest(e){jt().draw_setDepthTest(e)},drawMesh(e,t,r){const s=jt();s.HEAPF32.set(r,zt/4),s.draw_mesh(e,t,zt)},drawMeshWithMaterial(e,t,r){const s=jt(),n=ht.get(t);if(!n)return;if(Vt.setBlendMode(n.blendMode),Vt.setDepthTest(n.depthTest),0===n.uniforms.size)return void Vt.drawMesh(e,n.shader,r);s.HEAPF32.set(r,zt/4);let o=0,i=0;for(const[e,t]of n.uniforms){const r=Yt(e);if(!(r<0)){if(nt(t))Ht[o++]=10,Ht[o++]=r,Ht[o++]=t.slot??i++,Ht[o++]=t.textureId;else if("number"==typeof t)Ht[o++]=1,Ht[o++]=r,Ht[o++]=t;else if(Array.isArray(t)){Ht[o++]=t.length,Ht[o++]=r;for(let e=0;e<t.length;e++)Ht[o++]=t[e]}else"w"in t?(Ht[o++]=4,Ht[o++]=r,Ht[o++]=t.x,Ht[o++]=t.y,Ht[o++]=t.z,Ht[o++]=t.w):"z"in t?(Ht[o++]=3,Ht[o++]=r,Ht[o++]=t.x,Ht[o++]=t.y,Ht[o++]=t.z):(Ht[o++]=2,Ht[o++]=r,Ht[o++]=t.x,Ht[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(Ht.subarray(0,o),Lt/4),s.draw_meshWithUniforms(e,n.shader,zt,Lt,o)):s.draw_mesh(e,n.shader,zt)}},Gt={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function Yt(e){return Gt[e]??-1}var qt;exports.DataType=void 0,(qt=exports.DataType||(exports.DataType={}))[qt.Float=1]="Float",qt[qt.Float2=2]="Float2",qt[qt.Float3=3]="Float3",qt[qt.Float4=4]="Float4",qt[qt.Int=5]="Int",qt[qt.Int2=6]="Int2",qt[qt.Int3=7]="Int3",qt[qt.Int4=8]="Int4";let Jt=null,Kt=0,Qt=0,Zt=0;function er(e){Jt=e,Kt=Jt._malloc(262144),Qt=Jt._malloc(65536),Zt=Jt._malloc(256)}function tr(){Jt&&(Kt&&Jt._free(Kt),Qt&&Jt._free(Qt),Zt&&Jt._free(Zt),Kt=0,Qt=0,Zt=0),Jt=null}function rr(){if(!Jt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Jt}const sr={create(e){const t=rr(),r=t.geometry_create();if(0===r)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,Kt/4);const n=e.layout.length,o=new Int32Array(n);for(let t=0;t<n;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Zt,n).set(o),t.geometry_init(r,Kt,s,Zt,n,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,Qt,s).set(e.indices),t.geometry_setIndices16(r,Qt,s)}else{new Uint32Array(t.HEAPU8.buffer,Qt,s).set(e.indices),t.geometry_setIndices32(r,Qt,s)}}return r},updateVertices(e,t,r=0){const s=rr(),n=t.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);s.HEAPF32.set(t,Kt/4),s.geometry_updateVertices(e,Kt,n,r)},release(e){e>0&&rr().geometry_release(e)},isValid:e=>!(!Jt||e<=0)&&Jt.geometry_isValid(e),createQuad(e=1,t=1){const r=e/2,s=t/2;return sr.create({vertices:new Float32Array([-r,-s,0,0,r,-s,1,0,r,s,1,1,-r,s,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 r=[],s=[];r.push(0,0,.5,.5);for(let s=0;s<=t;s++){const n=s/t*Math.PI*2,o=Math.cos(n)*e,i=Math.sin(n)*e,a=(Math.cos(n)+1)/2,l=(Math.sin(n)+1)/2;r.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return sr.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.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,r=1/0,s=-1/0,n=-1/0;for(const o of e)t=Math.min(t,o.x),r=Math.min(r,o.y),s=Math.max(s,o.x),n=Math.max(n,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-r)/(n-r);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 sr.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 nr=null;function or(e){nr=e}function ir(){nr&&lr.isInitialized()&&lr.shutdown(),nr=null}function ar(){if(!nr)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return nr}const lr={init:(e,t)=>ar().postprocess_init(e,t),shutdown(){ar().postprocess_shutdown()},resize(e,t){ar().postprocess_resize(e,t)},addPass:(e,t)=>ar().postprocess_addPass(e,t),removePass(e){ar().postprocess_removePass(e)},setEnabled(e,t){ar().postprocess_setPassEnabled(e,t)},isEnabled:e=>ar().postprocess_isPassEnabled(e),setUniform(e,t,r){ar().postprocess_setUniformFloat(e,t,r)},setUniformVec4(e,t,r){ar().postprocess_setUniformVec4(e,t,r.x,r.y,r.z,r.w)},begin(){ar().postprocess_begin()},end(){ar().postprocess_end()},getPassCount:()=>ar().postprocess_getPassCount(),isInitialized:()=>!!nr&&nr.postprocess_isInitialized(),setBypass(e){ar().postprocess_setBypass(e)},isBypassed:()=>!nr||nr.postprocess_isBypassed(),createBlur:()=>ht.createShader(cr,"#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(cr,"#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(cr,"#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(cr,"#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")},cr="#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 ur;exports.RenderStage=void 0,(ur=exports.RenderStage||(exports.RenderStage={}))[ur.Background=0]="Background",ur[ur.Opaque=1]="Opaque",ur[ur.Transparent=2]="Transparent",ur[ur.Overlay=3]="Overlay";let dr=null,hr=0;function pr(e){dr=e,hr=dr._malloc(64)}function fr(){dr&&hr&&(dr._free(hr),hr=0),dr=null}const mr={init(e,t){dr?.renderer_init(e,t)},resize(e,t){dr?.renderer_resize(e,t)},begin(e,t){dr&&hr&&(dr.HEAPF32.set(e,hr/4),dr.renderer_begin(hr,t??0))},flush(){dr?.renderer_flush()},end(){dr?.renderer_end()},submitSprites(e){dr&&dr.renderer_submitSprites(e._cpp)},submitBitmapText(e){dr&&dr.renderer_submitBitmapText(e._cpp)},submitSpine(e){dr&&dr.renderer_submitSpine?.(e._cpp)},setStage(e){dr?.renderer_setStage(e)},createRenderTarget:(e,t,r=1)=>dr?.renderer_createTarget(e,t,r)??0,releaseRenderTarget(e){dr?.renderer_releaseTarget(e)},getTargetTexture:e=>dr?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>dr?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,r,s){dr?.renderer_setClearColor?.(e,t,r,s)},setViewport(e,t,r,s){dr?.renderer_setViewport(e,t,r,s)},setScissor(e,t,r,s,n){dr?.renderer_setScissor(e,t,r,s,n)},clearBuffers(e){dr?.renderer_clearBuffers(e)},measureBitmapText:(e,t,r,s)=>dr?dr.getResourceManager().measureBitmapText(e,t,r,s):{width:0,height:0},getStats:()=>dr?{drawCalls:dr.renderer_getDrawCalls(),triangles:dr.renderer_getTriangles(),sprites:dr.renderer_getSprites(),text:dr.renderer_getText(),spine:dr.renderer_getSpine?.()??0,meshes:dr.renderer_getMeshes(),culled:dr.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let gr=null;function xr(e){gr=e}function yr(){gr=null}const _r={enable(){gr?.gl_enableErrorCheck(!0)},disable(){gr?.gl_enableErrorCheck(!1)},check:e=>gr?.gl_checkErrors(e)??0,diagnose(){gr?.renderer_diagnose()}},wr=new Map;function br(e){wr.delete(e)}class vr{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:r,width:s,height:n,elapsed:o}=e;s===this.lastWidth_&&n===this.lastHeight_||(mr.resize(s,n),lr.isInitialized()&&lr.getPassCount()>0&&lr.resize(s,n),this.lastWidth_=s,this.lastHeight_=n),mr.setViewport(0,0,s,n),mr.clearBuffers(3),mr.begin(r),this.maskProcessor_&&this.maskProcessor_(t._cpp,r,0,0,s,n),mr.submitSprites(t),mr.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):mr.submitSpine(t),mr.flush(),this.executeDrawCallbacks(r,o),mr.end()}renderCamera(e){const{registry:t,viewProjection:r,viewportPixels:s,clearFlags:n,elapsed:o}=e;mr.setViewport(s.x,s.y,s.w,s.h),mr.setScissor(s.x,s.y,s.w,s.h,!0),mr.clearBuffers(n),mr.setScissor(0,0,0,0,!1),mr.begin(r),this.maskProcessor_&&this.maskProcessor_(t._cpp,r,s.x,s.y,s.w,s.h),mr.submitSprites(t),mr.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):mr.submitSpine(t),mr.flush(),this.executeDrawCallbacks(r,o),mr.end()}executeDrawCallbacks(e,t){const r=wr;if(r.size>0){Vt.begin(e);const s=[];for(const[e,n]of r.entries())try{n(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}Vt.end();for(const e of s)br(e)}}}class Sr{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=a(),t=e-this.lastTime_;this.lastTime_=e;const r=t/1e3;for(this.updateTime(r),this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=r;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate);this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),requestAnimationFrame(this.mainLoop)},this.world_=new ge,this.resources_=new ee;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Sr}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new ue(this.world_,this.resources_),this.resources_.insert(te,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1,yr(),fr(),ir(),tr(),ut(),Nt()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(te);t.delta=e,t.elapsed+=e,t.frameCount++}}const Pr=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Cr(e,t,r,s,n){const o=e*t/r,i=e;switch(s){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=n;return Math.pow(o,1-e)*Math.pow(i,e)}}}function Tr(e,t,r,s){if(0===r||0===s)return[];const n=e.registry_getCameraEntities(t);if(0===n.length)return[];const o=function(e,t){const r=e.registry_getCanvasEntity(t);return r<0?null:t.getCanvas(r)}(e,t),i=[];for(const e of n){const n=t.getCamera(e),a=t.getLocalTransform(e),l={x:n.viewportX,y:n.viewportY,w:n.viewportW,h:n.viewportH},c=l.w*r/(l.h*s);let u,d=0,h=0;if(1===n.projectionType){if(h=n.orthoSize,o){h=Cr(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=Er(-d,d,-h,h,-n.farPlane,n.farPlane)}else u=Rr(n.fov*Math.PI/180,c,n.nearPlane,n.farPlane);const p=Br(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:Fr(u,p),viewportRect:l,clearFlags:n.clearFlags,priority:n.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const Ar=new Float32Array(16);function Er(e,t,r,s,n,o){const i=Ar;i.fill(0);const a=t-e,l=s-r,c=o-n;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+r)/l,i[14]=-(o+n)/c,i[15]=1,i}const Mr=new Float32Array(16);function Rr(e,t,r,s){const n=Mr;n.fill(0);const o=1/Math.tan(e/2),i=r-s;return n[0]=o/t,n[5]=o,n[10]=(s+r)/i,n[11]=-1,n[14]=2*s*r/i,n}const Ir=new Float32Array(16);function Br(e,t,r){const s=Ir;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]=-r,s[15]=1,s}function Fr(e,t){const r=new Float32Array(16);for(let s=0;s<4;s++)for(let n=0;n<4;n++)r[4*n+s]=e[0+s]*t[4*n+0]+e[4+s]*t[4*n+1]+e[8+s]*t[4*n+2]+e[12+s]*t[4*n+3];return r}async function Ur(e,t){if(t)return t();return(0,(await import(e)).default)()}const kr=K({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Wr=K(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 $r(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class zr{constructor(e,t={},r){this.wasmUrl_=e,this.factory_=r,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,r=new Map,s=Ur(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const n=function(e){const t=e.world.getEntitiesWithComponents([O]);for(const r of t){const t=e.world.get(r,O);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/n,i=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,le([Q(te)],a=>{const l=i.getEntitiesWithComponents([P,$,z]),c=new Set;for(const n of l){c.add(n);const a=i.get(n,P),l=i.get(n,z);if(t.has(n)){const e=r.get(n);!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(n,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);s._physics_createBody(n,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),Lr(e,s,n),t.add(n),r.set(n,{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=Dr(l.rotation);s._physics_setBodyTransform(n,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),r.delete(e));s._physics_step(a.delta),function(e,t,r){const s=t._physics_getDynamicBodyCount();if(0===s)return;const n=t._physics_getDynamicBodyTransforms(),o=n>>2;for(let n=0;n<s;n++){const s=o+4*n,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*r,l=t.HEAPF32[s+2]*r,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,$);if(!u)continue;let d=a,h=l,p=c;if(e.world.has(i,j)){const t=e.world.get(i,j);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,z)){const r=e.world.get(t.entity,z),s=Dr(r.rotation),n=a-r.position.x,o=l-r.position.y,i=Math.cos(-s),u=Math.sin(-s);d=(n*i-o*u)/(0!==r.scale.x?r.scale.x:1),h=(n*u+o*i)/(0!==r.scale.y?r.scale.y:1),p=c-s}}u.position.x=d,u.position.y=h;const f=$r(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,$,u)}}(e,s,n),function(e,t,r){t._physics_collectEvents();const s=[],n=t._physics_getCollisionEnterCount();if(n>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<n;o++){const n=e+6*o;s.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1],normalX:t.HEAPF32[n+2],normalY:t.HEAPF32[n+3],contactX:t.HEAPF32[n+4]*r,contactY:t.HEAPF32[n+5]*r})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let r=0;r<i;r++){const s=e+2*r;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 r=0;r<l;r++){const s=e+2*r;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 r=0;r<u;r++){const s=e+2*r;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(kr,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,n)},{name:"PhysicsSystem"})),e.__physicsModule=s,e.insertResource(Wr,Hr._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=s}}function Lr(e,t,r){const s=e.world;if(s.has(r,C)){const e=s.get(r,C);return void t._physics_addBoxShape(r,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(r,T)){const e=s.get(r,T);return void t._physics_addCircleShape(r,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(r,A)){const e=s.get(r,A);t._physics_addCapsuleShape(r,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Hr{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(Hr.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function Or(e,t,r=!0){const s=e.getResourceManager(),n=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,n);const o=s.createTexture(t.width,t.height,n,t.pixels.length,1,r);return e._free(n),o}function Nr(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function jr(e,t,r,s){const n=e.scale.x*t*(r?-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,p=c+c,f=a*d,m=a*h,g=a*p,x=l*h,y=l*p,_=c*p,w=u*d,b=u*h,v=u*p;return new Float32Array([(1-(x+_))*n,(m+v)*n,(g-b)*n,0,(m-v)*o,(1-(f+_))*o,(y+w)*o,0,(g+b)*i,(y-w)*i,(1-(f+x))*i,0,e.position.x,e.position.y,e.position.z,1])}async function Xr(e,t,r,s,n,o,i,a){const l=await async function(e,t,r){const s={};for(const n of t.entities)for(const t of n.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const n=t.data.texture;if(void 0!==s[n])continue;try{s[n]=Or(e,await r.loadPixels(n))}catch{s[n]=0}}return s}(t,r,s);!function(e,t,r){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const n=r[e];if(n&&n>0){const r=t.textureMetadata[e];if(r?.sliceBorder){const e=r.sliceBorder;s.setTextureMetadata(n,e.left,e.right,e.top,e.bottom)}}}}(t,r,l);let c={},u=null;if(n&&(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"])}}(n),c=await async function(e,t,r,s,n){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=n.resolvePath(i),c=n.resolvePath(a);try{const s=n.readText(a),u=l.endsWith(".skel");let d,h;if(u){const e=n.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=n.readText(i),r=(new TextEncoder).encode(e);h=r.length,d=t._malloc(h+1),t.HEAPU8.set(r,d),t.HEAPU8[d+h]=0}const p=r.loadSkeleton(d,h,s,s.length,u);if(t._free(d),p<0)continue;o[i]=p;const f=Nr(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const s=m+"/"+f[t];try{const o=n.loadPixelsRaw?await n.loadPixelsRaw(s):await n.loadPixels(s),i=Or(e,o,!1),a=e.getResourceManager().getTextureGLId(i);r.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,n,u,r,s)),o){new zr("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,r){const s={};for(const n of t.entities)for(const t of n.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const n=t.data.font;if(void 0===s[n])try{let t,o;if(n.endsWith(".bmfont")){const e=JSON.parse(r.readText(n)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[n]=0;continue}const a=n.substring(0,n.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=r.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=r.readText(n),o=n.substring(0,n.lastIndexOf("/"));const i=t.match(/file="([^"]+)"/);if(!i){s[n]=0;continue}const a=o?`${o}/${i[1]}`:i[1],l=r.loadPixelsRaw?await r.loadPixelsRaw(a):await r.loadPixels(a),c=Or(e,l,!1),u=e.getResourceManager();s[n]=u.loadBitmapFont(t,c,l.width,l.height)}catch{s[n]=0}}return s}(t,r,s),h=function(e,t){const r={},s={};for(const n of e.entities)for(const e of n.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const n=e.data.material;if(void 0===r[n])try{const e=JSON.parse(t.readText(n));if(!e.vertexSource||!e.fragmentSource){r[n]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=ht.createShader(e.vertexSource,e.fragmentSource),s[o]=i),r[n]=ht.createFromAsset(e,i)}catch{r[n]=0}}return r}(r,s),p=vt(e.world,r);if(function(e,t,r,s){for(const n of t.entities){const t=s.get(n.id);if(void 0!==t)for(const s of n.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const n=e.get(t,L);n&&(n.texture=r[s.data.texture]||0,e.insert(t,L,n))}}}(e.world,r,l,p),function(e,t,r,s){for(const n of t.entities){const t=s.get(n.id);if(void 0!==t)for(const s of n.components){if("BitmapText"!==s.type||!s.data.font||"string"!=typeof s.data.font)continue;const n=r[s.data.font]||0;if(!n)continue;const o=e.get(t,V);o&&(o.font=n,e.insert(t,V,o))}}}(e.world,r,d,p),function(e,t,r,s){for(const n of t.entities){const t=s.get(n.id);if(void 0!==t)for(const s of n.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const n=r[s.data.material]||0;if(n)if("Sprite"===s.type){const r=e.get(t,L);r&&(r.material=n,e.insert(t,L,r))}else if("SpineAnimation"===s.type){const r=e.get(t,G);r&&(r.material=n,e.insert(t,G,r))}}}}(e.world,r,h,p),n&&u){const s=function(e,t,r,s){const n={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=r[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(n[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return n}(u,r,c,p);!function(e,t,r,s,n){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in n){const o=Number(e),i=n[e],a=c.has(o,G)?c.get(o,G):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(i,l*d);let h=0;if(c.has(o,z)){const e=jr(c.get(o,z),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=s.getMeshBatchCount(i);for(let e=0;e<p;e++){const n=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!n||!o)continue;const a=8*n*4,l=2*o,c=r._malloc(a),u=r._malloc(l),d=r._malloc(4),p=r._malloc(4);s.getMeshBatchData(i,e,c,u,d,p);const f=r.HEAPU32[d>>2],m=r.HEAPU32[p>>2],g=new Float32Array(r.HEAPF32.buffer,c,8*n),x=new Uint16Array(r.HEAPU8.buffer,u,o),y=t._malloc(a),_=t._malloc(l);t.HEAPF32.set(g,y>>2),new Uint16Array(t.HEAPU8.buffer,_,o).set(x),t.renderer_submitTriangles(y,n,_,o,f,m,h),t._free(y),t._free(_),r._free(c),r._free(u),r._free(d),r._free(p)}h&&t._free(h)}})}(e,t,n,u,s)}if(a){const t=e.getResource(At);t&&t.setAddressableManifest(a)}}class Vr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,r=new Set,s=new Set;for(const n of e.entities)for(const e of n.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,n=e.data.atlasPath;s&&(s.endsWith(".skel")?r.add(s):t.add(s)),n&&t.add(n)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const n=[];for(const e of t)n.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of r)n.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(n);const o=[];for(const e of s){if(!e.endsWith(".bmfont"))continue;const t=this.textCache_.get(e);if(t)try{const r=JSON.parse(t),s="label-atlas"===r.type?r.generatedFnt:r.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),r=t?`${t}/${s}`:s;this.textCache_.has(r)||o.push(fetch(this.resolveUrl(r)).then(e=>e.text()).then(e=>{this.textCache_.set(r,e)}).catch(()=>{}))}}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),r=await fetch(t),s=await r.blob(),n=await createImageBitmap(s),o=new OffscreenCanvas(n.width,n.height).getContext("2d");o.drawImage(n,0,0);const i=o.getImageData(0,0,n.width,n.height);return n.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Gr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),r=mr.createRenderTarget(e.width,e.height,t);return{_handle:r,textureId:mr.getTargetTexture(r),width:e.width,height:e.height}},release(e){mr.releaseRenderTarget(e._handle)},resize:(e,t,r)=>(mr.releaseRenderTarget(e._handle),Gr.create({width:t,height:r,depth:!0})),begin(e,t){mr.begin(t,e._handle)},end(){mr.end()},getDepthTexture:e=>mr.getTargetDepthTexture(e._handle)};let Yr=!1;_||(_=!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 r="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},n=await l(r,s);return{ok:n.ok,status:n.status,statusText:n.statusText,headers:new Headers(n.headers),json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.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:r}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return c(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),r=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);n<128?r[s++]=n:n<2048?(r[s++]=192|n>>6,r[s++]=128|63&n):n>=55296&&n<=56319?(n=e.charCodeAt(++t)-56320+(n-55296<<10)+65536,r[s++]=240|n>>18,r[s++]=128|n>>12&63,r[s++]=128|n>>6&63,r[s++]=128|63&n):(r[s++]=224|n>>12,r[s++]=128|n>>6&63,r[s++]=128|63&n)}return r.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let r="";for(let e=0;e<t.length;){const s=t[e];if(s<128)r+=String.fromCharCode(s),e++;else if(192==(224&s))r+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))r+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const n=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;r+=String.fromCharCode(55296+(n>>10),56320+(1023&n)),e+=4}}return r}})}(),console.log("[ESEngine] WeChat platform initialized")),e=w,exports.App=Sr,exports.AssetPlugin=Et,exports.AssetServer=Tt,exports.Assets=At,exports.AsyncCache=Ct,exports.BitmapText=V,exports.BodyType=E,exports.BoxCollider=C,exports.Button=Le,exports.Camera=H,exports.Canvas=O,exports.CapsuleCollider=A,exports.Children=X,exports.CircleCollider=T,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=oe,exports.Draw=Vt,exports.EntityCommands=ne,exports.GLDebug=_r,exports.Geometry=sr,exports.INVALID_ENTITY=0,exports.INVALID_FONT=v,exports.INVALID_TEXTURE=b,exports.Input=he,exports.InputPlugin=pe,exports.InputState=de,exports.Interactable=De,exports.LocalTransform=$,exports.Material=ht,exports.MaterialLoader=bt,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=Y,exports.Parent=j,exports.Physics=Hr,exports.PhysicsEvents=kr,exports.PhysicsPlugin=zr,exports.PostProcess=lr,exports.PrefabServer=Ft,exports.Prefabs=Ut,exports.PrefabsPlugin=kt,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(!this.app_)return;let e="fetch scene";try{const t=await r(this.sceneUrl_);if(!t.ok)throw new Error(`Failed to fetch scene: ${t.status}`);e="parse scene JSON";const s=await t.json();e="prefetch assets";const n=new Vr(this.baseUrl_);await n.prefetch(s);let o=null;const i=this.app_.__spineInitPromise;if(i){e="init spine";o=(await i).controller.raw}e="loadRuntimeScene",await Xr(this.app_,this.app_.wasmModule,s,n,o),e="ensureCamera",this.ensureCamera()}catch(t){const r=t instanceof Error?t.message:String(t),s=t instanceof Error?t.stack:"";throw console.error(`[PreviewPlugin] Failed at step "${e}": ${r}\n${s}`),new Error(`[PreviewPlugin:${e}] ${r}`)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const r=e.getEntitiesWithComponents([H]);for(const s of r){if(e.get(s,H).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,r=1920/1080;const s=e.getEntitiesWithComponents([O]);for(const n of s){const s=e.get(n,O);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,r=s.designResolution.x/s.designResolution.y;break}}const n=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(n,$,o);const i={isActive:!0,projectionType:1,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:r,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3};e.insert(n,H,i)}}},exports.Query=function(...e){return function(e,t=[],r=[]){const s=[];return e.forEach((e,t)=>{re(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:r}}(e)},exports.QueryInstance=se,exports.RenderPipeline=vr,exports.RenderTexture=Gr,exports.Renderer=mr,exports.Res=Q,exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.RigidBody=P,exports.ScreenSpace=Ge,exports.ShaderSources=wt,exports.SpineAnimation=G,exports.Sprite=L,exports.SystemRunner=ue,exports.Text=we,exports.TextInput=Qe,exports.TextInputPlugin=Ze,exports.TextPlugin=Ce,exports.TextRenderer=be,exports.Time=te,exports.UICameraInfo=Ne,exports.UIEventQueue=He,exports.UIEvents=Oe,exports.UIInteraction=$e,exports.UIInteractionPlugin=Xe,exports.UILayoutPlugin=Je,exports.UIMask=Ae,exports.UIMaskPlugin=ke,exports.UIRect=ve,exports.Velocity=N,exports.WebAssetProvider=Vr,exports.World=ge,exports.WorldTransform=z,exports.addStartupSystem=function(e){ce().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){ce().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){ce().push({schedule:e,system:t})},exports.assetPlugin=Mt,exports.clearDrawCallbacks=function(){wr.clear()},exports.clearUserComponents=function(){I().clear()},exports.color=(e=1,t=1,r=1,s=1)=>({r:e,g:t,b:r,a:s}),exports.computeUIRectLayout=Ye,exports.createMaskProcessor=Ue,exports.createWebApp=function(e,t){const r=Sr.new(),s=new e.Registry;r.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ot(e),ct(e),er(e),or(e),pr(e),xr(e);const n=new vr;r.pipeline_=n;let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function l(t,n){const o=Tr(e,s,t,n),i=r.getResource(Ne);if(o.length>0){const e=o[0],r=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(r.x*t),i.vpY=Math.round((1-r.y-r.h)*n),i.vpW=Math.round(r.w*t),i.vpH=Math.round(r.h*n),i.screenW=t,i.screenH=n,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}r.insertResource(Ne,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();l(e,t)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:r}=i();if(0===t||0===r)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;mr.setClearColor(e.x,e.y,e.z,e.w)}const u=(a()-o)/1e3;mr.resize(t,r),lr.isInitialized()&&lr.getPassCount()>0&&!lr.isBypassed()&&lr.resize(t,r);const d=Tr(e,s,t,r);if(l(t,r),0===d.length)n.render({registry:{_cpp:s},viewProjection:Pr,width:t,height:r,elapsed:u});else{for(const e of d){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*r),l=Math.round(o.w*t),c=Math.round(o.h*r);n.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:c},clearFlags:e.clearFlags,elapsed:u})}mr.setViewport(0,0,t,r)}}};return r.addSystemToSchedule(exports.Schedule.First,c),r.addSystemToSchedule(exports.Schedule.Last,u),r.addPlugin(Mt),r.addPlugin(Wt),r.addPlugin(fe),r.addPlugin(Te),r.addPlugin(We),r.addPlugin(Ke),r.addPlugin(Ve),r.addPlugin(rt),r},exports.defineComponent=B,exports.defineResource=K,exports.defineSystem=le,exports.defineTag=F,exports.findEntityByName=function(e,t){const r=e.getEntitiesWithComponents([Y]);for(const s of r){const r=e.get(s,Y);if(r&&r.value===t)return s}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const r of t)e.addSystemToSchedule(r.schedule,r.system);t.length=0}},exports.getComponentDefaults=function(e){const t=q[e];if(t)return{...t._default};const r=U(e);return r?{...r._default}:null},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=U,exports.initDrawAPI=Ot,exports.initGLDebugAPI=xr,exports.initGeometryAPI=er,exports.initMaterialAPI=ct,exports.initPostProcessAPI=or,exports.initRendererAPI=pr,exports.inputPlugin=fe,exports.instantiatePrefab=Rt,exports.intersectRects=Ee,exports.invertMatrix4=Re,exports.isBuiltinComponent=D,exports.isEditor=function(){return Yr},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!Yr},exports.isTextureRef=nt,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=Pt,exports.loadPhysicsModule=Ur,exports.loadRuntimeScene=Xr,exports.loadSceneData=vt,exports.loadSceneWithAssets=St,exports.platformFetch=r,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,r){return t().instantiateWasm(e,r)},exports.platformReadFile=s,exports.platformReadTextFile=n,exports.pointInWorldRect=Be,exports.prefabsPlugin=Wt,exports.quat=(e=1,t=0,r=0,s=0)=>({w:e,x:t,y:r,z:s}),exports.registerDrawCallback=function(e,t){wr.set(e,t)},exports.registerEmbeddedAssets=function(e,t){const r=e.getResource(At);r&&r.registerEmbeddedAssets(t)},exports.registerMaterialCallback=_t,exports.screenToWorld=Ie,exports.setEditorMode=function(e){Yr=e},exports.shutdownDrawAPI=Nt,exports.shutdownGLDebugAPI=yr,exports.shutdownGeometryAPI=tr,exports.shutdownMaterialAPI=ut,exports.shutdownPostProcessAPI=ir,exports.shutdownRendererAPI=fr,exports.textInputPlugin=rt,exports.textPlugin=Te,exports.uiInteractionPlugin=Ve,exports.uiLayoutPlugin=Ke,exports.uiMaskPlugin=We,exports.unregisterDrawCallback=br,exports.updateCameraAspectRatio=function(e,t){const r=e.getEntitiesWithComponents([H]);for(const s of r){const r=e.get(s,H);r&&(r.aspectRatio=t,e.insert(s,H,r))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,r=0)=>({x:e,y:t,z:r}),exports.vec4=(e=0,t=0,r=0,s=1)=>({x:e,y:t,z:r,w:s}),exports.worldRectToScreen=Me,exports.wxFileExists=f,exports.wxFileExistsSync=function(e){const t=d();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=y,exports.wxLoadImage=x,exports.wxLoadImagePixels=async function(e){return y(await x(e))},exports.wxReadFile=h,exports.wxReadTextFile=p,exports.wxWriteFile=function(e,t){return new Promise((r,s)=>{d().writeFile({filePath:e,data:t,success:()=>r(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};
+"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function r(e,r){return t().fetch(e,r)}async function s(e){return t().readFile(e)}async function n(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,r){return t().createCanvas(e,r)}function a(){return t().now()}function l(e,t){return new Promise((r,s)=>{const n=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===n?"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];r({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,r="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(r).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function c(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const r=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(r,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 "${r}": ${t}`)}}let u=null;function d(){return u||(u=wx.getFileSystemManager()),u}function h(e){return new Promise((t,r)=>{d().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function p(e,t="utf-8"){return new Promise((r,s)=>{d().readFile({filePath:e,encoding:t,success:e=>{r(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function f(e){return new Promise(t=>{d().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}let m=null,g=null;function x(e){return new Promise((t,r)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>r(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function y(e){const{width:t,height:r}=e,{ctx:s}=function(e,t){return m||(m=wx.createCanvas(),m.width=e,m.height=t,g=m.getContext("2d")),(m.width<e||m.height<t)&&(m.width=Math.max(m.width,e),m.height=Math.max(m.height,t)),{canvas:m,ctx:g}}(t,r);s.clearRect(0,0,t,r),s.drawImage(e,0,0);const n=s.getImageData(0,0,t,r);return{width:t,height:r,pixels:new Uint8Array(n.data.buffer)}}let _=!1;const w=new class{constructor(){this.name="wechat"}async fetch(e,t){return l(e,t)}async readFile(e){return h(e)}async readTextFile(e){return p(e)}async fileExists(e){return f(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return c(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const r=wx.createCanvas();return r.width=e,r.height=t,r}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{const r=t.touches[0];r&&e.onPointerDown(0,r.clientX,r.clientY)}),wx.onTouchMove(t=>{const r=t.touches[0];r&&e.onPointerMove(r.clientX,r.clientY)}),wx.onTouchEnd(()=>{e.onPointerUp(0)})}},b=4294967295,v=4294967295;function S(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const P=S("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),C=S("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),T=S("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),A=S("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),E={Static:0,Kinematic:1,Dynamic:2};let M=0;function R(e,t){const r=++M;return{_id:Symbol(`Component_${r}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function I(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function B(e,t){const r=I(),s=r.get(e);if(s)return s;const n=R(e,t);return r.set(e,n),k(e,t,!1),n}function F(e){const t=I(),r=t.get(e);if(r)return r;const s=R(e,{});return t.set(e,s),k(e,{},!0),s}function U(e){return I().get(e)}function k(e,t,r){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,r)}function W(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function D(e){return!0===e._builtin}const $=W("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),z=W("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),L=W("Sprite",{texture:b,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}),H=W("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),O=W("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),N=W("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),j=W("Parent",{entity:0}),X=W("Children",{entities:[]}),V=W("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:v}),G=W("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}),Y={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},q={LocalTransform:$,WorldTransform:z,Sprite:L,Camera:H,Canvas:O,Velocity:N,Parent:j,Children:X,BitmapText:V,SpineAnimation:G,RigidBody:P,BoxCollider:C,CircleCollider:T,CapsuleCollider:A};let J=0;function K(e,t){const r=++J;return{_id:Symbol(`Resource_${r}_${t??""}`),_name:t??`Resource_${r}`,_default:e}}function Q(e){return{_type:"res",_resource:e}}class Z{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}}class ee{constructor(){this.resources_=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)}getResMut(e){return new Z(this.get(e),t=>this.set(e,t))}}const te=K({delta:0,elapsed:0,frameCount:0},"Time");function re(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}class se{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)}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,r=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),n=r.length,o=e.length>0,i=t.length>0,a=new Array(n+1);let l=null,c=[];try{for(const u of s){if(null!==l&&o){for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}c.length=0}if(i){let e=!1;for(let r=0;r<t.length;r++)if(this.world_.has(u,t[r])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<n;e++)a[e+1]=this.world_.get(u,r[e]);if(o){for(let t=0;t<e.length;t++){const s=e[t];c.push({component:r[s],data:a[s+1]})}l=u}yield a}}finally{if(null!==l&&o)for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}}}forEach(e){for(const[t,...r]of this)e(t,...r)}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 ne{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 r;return r=D(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:r}):this.commands_.queueInsert(this.entityRef_.entity,e,r),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 oe{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ne(this,null);return this.spawned_.push(e),e}entity(e){return new ne(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,r){this.pending_.push({type:"insert",entity:e,component:t,data:r})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const r=this.world_.spawn();t.entity=r;for(const t of e)this.world_.insert(r,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const r of e.components)this.world_.insert(t,r.component,r.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var ie;exports.Schedule=void 0,(ie=exports.Schedule||(exports.Schedule={}))[ie.Startup=0]="Startup",ie[ie.First=1]="First",ie[ie.PreUpdate=2]="PreUpdate",ie[ie.Update=3]="Update",ie[ie.PostUpdate=4]="PostUpdate",ie[ie.Last=5]="Last",ie[ie.FixedPreUpdate=10]="FixedPreUpdate",ie[ie.FixedUpdate=11]="FixedUpdate",ie[ie.FixedPostUpdate=12]="FixedPostUpdate";let ae=0;function le(e,t,r){const s=++ae;return{_id:Symbol(`System_${s}_${r?.name??""}`),_params:e,_fn:t,_name:r?.name??`System_${s}`}}function ce(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class ue{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 r=0;r<e._params.length;r++)t[r]=this.resolveParam(e._params[r]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof oe&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new se(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new oe(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 he=K(new de,"Input");class pe{constructor(e){this.target_=e??null}build(e){const r=new de;e.insertResource(he,r),t().bindInputEvents({onKeyDown(e){r.keysDown.has(e)||r.keysPressed.add(e),r.keysDown.add(e)},onKeyUp(e){r.keysDown.delete(e),r.keysReleased.add(e)},onPointerMove(e,t){r.mouseX=e,r.mouseY=t},onPointerDown(e,t,s){r.mouseX=t,r.mouseY=s,r.mouseButtons.add(e),r.mouseButtonsPressed.add(e)},onPointerUp(e){r.mouseButtons.delete(e),r.mouseButtonsReleased.add(e)},onWheel(e,t){r.scrollDeltaX+=e,r.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.Last,le([],()=>{r.keysPressed.clear(),r.keysReleased.clear(),r.mouseButtonsPressed.clear(),r.mouseButtonsReleased.clear(),r.scrollDeltaX=0,r.scrollDeltaY=0},{name:"InputClearSystem"}))}}const fe=new pe;function me(e){const t={};for(const r of Object.keys(e)){const s=e[r];if(null==s||"object"!=typeof s||Array.isArray(s))t[r]=s;else{const e=s;t[r]="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}:me(e)}}return t}class ge{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,r){return D(t)?this.insertBuiltin(e,t,r):this.insertScript(e,t,r)}get(e,t){return D(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return D(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){D(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,r){const s={};if(null!=r&&"object"==typeof r)for(const[e,t]of Object.entries(r))void 0!==t&&(s[e]=t);const n={...t._default,...s};if(this.cppRegistry_){const r=`add${t._cppName}`,s=this.cppRegistry_[r];s?.call(this.cppRegistry_,e,me(n))}return n}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const r=`get${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const r=`has${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const r=`remove${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e)}insertScript(e,t,r){const s=t.create(r);return this.getStorage(t).set(e,s),s}getScript(e,t){const r=this.tsStorage_.get(t._id);if(!r)throw new Error(`Component not found: ${t._name}`);return r.get(e)}hasScript(e,t){const r=this.tsStorage_.get(t._id);return r?.has(e)??!1}removeScript(e,t){const r=this.tsStorage_.get(t._id);r?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();let t=null,r=1/0;for(const s of e)if(!D(s)){const e=this.tsStorage_.get(s._id),n=e?e.size:0;n<r&&(r=n,t=e??null)}const s=[],n=t?t.keys():this.entities_;for(const t of n){let r=!0;for(const s of e)if(!this.has(t,s)){r=!1;break}r&&s.push(t)}return s}}var xe,ye,_e;exports.TextAlign=void 0,(xe=exports.TextAlign||(exports.TextAlign={}))[xe.Left=0]="Left",xe[xe.Center=1]="Center",xe[xe.Right=2]="Right",exports.TextVerticalAlign=void 0,(ye=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[ye.Top=0]="Top",ye[ye.Middle=1]="Middle",ye[ye.Bottom=2]="Bottom",exports.TextOverflow=void 0,(_e=exports.TextOverflow||(exports.TextOverflow={}))[_e.Visible=0]="Visible",_e[_e.Clip=1]="Clip",_e[_e.Ellipsis=2]="Ellipsis";const we=B("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2});class be{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const r=this.ctx,s=this.canvas;r.font=`${e.fontSize}px ${e.fontFamily}`;const n=t&&t.size.x>0&&t.size.y>0,o=n?t.size.x:0,i=n?t.size.y:0,a=e.wordWrap&&n;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=n?Math.ceil(o):d+2*u,f=n?Math.ceil(i):h+2*u;if(n&&e.overflow===exports.TextOverflow.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<p||s.height<f){const e=Math.max(s.width,this.nextPowerOf2(p)),t=Math.max(s.height,this.nextPowerOf2(f));s.width=e,s.height=t}const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),x=Math.round(255*e.color.b),y=e.color.a;r.clearRect(0,0,s.width,s.height),r.font=`${e.fontSize}px ${e.fontFamily}`,r.textAlign=this.mapAlign(e.align),r.textBaseline="top",r.fillStyle=`rgba(${m}, ${g}, ${x}, ${y})`,n&&e.overflow===exports.TextOverflow.Clip&&(r.save(),r.beginPath(),r.rect(0,0,p,f),r.clip());const _=l.length*c;let w;if(n)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-_)/2;break;case exports.TextVerticalAlign.Bottom:w=f-_-u;break;default:w=u}else w=u;let b=w;for(const t of l){let s;switch(e.align){case exports.TextAlign.Left:s=u;break;case exports.TextAlign.Center:s=p/2;break;case exports.TextAlign.Right:s=p-u;break;default:s=u}r.fillText(t,s,b),b+=c}n&&e.overflow===exports.TextOverflow.Clip&&r.restore();const v=r.getImageData(0,0,p,f),S=new Uint8Array(v.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const T=P.createTexture(p,f,C,S.length,1,!0);return this.module._free(C),{textureHandle:T,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let r=e;for(;r.length>0&&this.ctx.measureText(r+"...").width>t;)r=r.slice(0,-1);return r+"..."}renderForEntity(e,t,r){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const n=this.renderText(t,r);return this.cache.set(e,n),n}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[r,s]of this.cache)e(r)||(t.releaseTexture(s.textureHandle),this.cache.delete(r))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const r=e.split("\n"),s=[];for(const e of r){if(!e){s.push("");continue}let r="";for(const n of e){const e=r+n;this.ctx.measureText(e).width>t&&r?(s.push(r),r=n):r=e}r&&s.push(r)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const r of e){const e=this.ctx.measureText(r),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const ve=B("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}});function Se(e){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight}}function Pe(e,t){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight}class Ce{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const r=new be(t),s=e.world,n=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,le([],()=>{r.cleanupOrphaned(e=>s.valid(e)&&s.has(e,we));for(const e of n.keys())s.valid(e)&&s.has(e,we)||n.delete(e);const e=s.getEntitiesWithComponents([we]);for(const t of e){const e=s.get(t,we),o=n.get(t);if(o&&!Pe(o,e))continue;s.has(t,L)||s.insert(t,L,{texture:b,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const i=s.has(t,ve)?s.get(t,ve):null,a=r.renderForEntity(t,e,i),l=s.get(t,L);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,L,l),n.set(t,Se(e))}}))}}const Te=new Ce,Ae=B("UIMask",{enabled:!0});function Ee(e,t){const r=Math.max(e.x,t.x),s=Math.max(e.y,t.y),n=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:r,y:s,w:Math.max(0,n-r),h:Math.max(0,o-s)}}function Me(e,t,r,s,n,o,i,a,l,c,u){const d=e-r*n,h=e+r*(1-n),p=t-s*o,f=t+s*(1-o);function m(e,t){const r=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],n=i[3]*e+i[7]*t+i[15];return[a+(.5*(r/n)+.5)*c,l+(.5*(s/n)+.5)*u]}const[g,x]=m(d,p),[y,_]=m(h,f),w=Math.min(g,y),b=Math.max(g,y),v=Math.min(x,_),S=Math.max(x,_);return{x:Math.round(w),y:Math.round(v),w:Math.round(b-w),h:Math.round(S-v)}}function Re(e,t){const r=t??new Float32Array(16),s=e[0],n=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],m=e[12],g=e[13],x=e[14],y=e[15],_=s*l-n*a,w=s*c-o*a,b=s*u-i*a,v=n*c-o*l,S=n*u-i*l,P=o*u-i*c,C=d*g-h*m,T=d*x-p*m,A=d*y-f*m,E=h*x-p*g,M=h*y-f*g,R=p*y-f*x;let I=_*R-w*M+b*E+v*A-S*T+P*C;return 0===I||(I=1/I,r[0]=(l*R-c*M+u*E)*I,r[1]=(o*M-n*R-i*E)*I,r[2]=(g*P-x*S+y*v)*I,r[3]=(p*S-h*P-f*v)*I,r[4]=(c*A-a*R-u*T)*I,r[5]=(s*R-o*A+i*T)*I,r[6]=(x*b-m*P-y*w)*I,r[7]=(d*P-p*b+f*w)*I,r[8]=(a*M-l*A+u*C)*I,r[9]=(n*A-s*M-i*C)*I,r[10]=(m*S-g*b+y*_)*I,r[11]=(h*b-d*S-f*_)*I,r[12]=(l*T-a*E-c*C)*I,r[13]=(s*E-n*T+o*C)*I,r[14]=(g*w-m*v-x*_)*I,r[15]=(d*v-h*w+p*_)*I),r}function Ie(e,t,r,s,n,o,i){const a=(e-s)/o*2-1,l=(t-n)/i*2-1,c=r[0]*a+r[4]*l+r[12],u=r[1]*a+r[5]*l+r[13],d=r[3]*a+r[7]*l+r[15];return{x:c/d,y:u/d}}function Be(e,t,r,s,n,o,i,a){return e>=r-n*i&&e<=r+n*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function Fe(e,t,r,s,n,o,i){if(!e.has(t,ve)||!e.has(t,z))return null;const a=e.get(t,ve),l=e.get(t,z),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return Me(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,r,s,n,o,i)}function Ue(e,t){return(r,s,n,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Ae]);if(0!==l.length)try{!function(e,t,r,s,n,o,i,a,l){const c=new Set;for(const e of s){t.get(e,Ae).enabled&&c.add(e)}const u=[];for(const e of s){if(!c.has(e))continue;let r=!0,s=e;for(;t.has(s,j);){const e=t.get(s,j);if(c.has(e.entity)){r=!1;break}s=e.entity}r&&u.push(e)}function d(s,u){const h=e.getChildEntities(r,s);for(const r of h){let s=u;if(c.has(r)){const e=Fe(t,r,n,o,i,a,l);e&&(s=Ee(u,e))}e.renderer_setEntityClipRect(r,s.x,s.y,s.w,s.h),d(r,s)}}for(const e of u){const r=Fe(t,e,n,o,i,a,l);r&&d(e,r)}}(e,t,r,l,s,n,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class ke{build(e){if(!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Ue(e.wasmModule,e.world))}}const We=new ke,De=B("Interactable",{enabled:!0}),$e=B("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var ze;exports.ButtonState=void 0,(ze=exports.ButtonState||(exports.ButtonState={}))[ze.Normal=0]="Normal",ze[ze.Hovered=1]="Hovered",ze[ze.Pressed=2]="Pressed",ze[ze.Disabled=3]="Disabled";const Le=B("Button",{state:exports.ButtonState.Normal,transition:null});class He{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(r=>r.entity===e&&r.type===t)}}const Oe=K(new He,"UIEvents"),Ne=K({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo"),je=new Float32Array(16);class Xe{build(e){const t=e.world,r=new He;e.insertResource(Oe,r);let s=null,n=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,le([Q(he),Q(Ne)],(e,o)=>{r.drain();const i=t.getEntitiesWithComponents([$e]);for(const e of i){const r=t.get(e,$e);r.justPressed=!1,r.justReleased=!1}if(!o.valid)return;const a="undefined"!=typeof window&&window.devicePixelRatio||1,l=e.mouseX*a,c=o.screenH-e.mouseY*a;Re(o.viewProjection,je);const u=Ie(l,c,je,o.vpX,o.vpY,o.vpW,o.vpH),d=t.getEntitiesWithComponents([De,ve,z]);let h=null,p=-1/0;for(const e of d){t.has(e,$e)||t.insert(e,$e);if(!t.get(e,De).enabled)continue;const r=t.get(e,z),s=t.get(e,ve),n=s.size.x*r.scale.x,o=s.size.y*r.scale.y;if(Be(u.x,u.y,r.position.x,r.position.y,n,o,s.pivot.x,s.pivot.y)){let r=0;t.has(e,L)&&(r=t.get(e,L).layer),r>=p&&(p=r,h=e)}}if(s!==h){if(null!==s&&t.valid(s)&&t.has(s,$e)){t.get(s,$e).hovered=!1,r.emit(s,"hover_exit")}if(null!==h){t.get(h,$e).hovered=!0,r.emit(h,"hover_enter")}s=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,$e);e.pressed=!0,e.justPressed=!0,n=h,r.emit(h,"press")}if(e.isMouseButtonReleased(0)&&null!==n){if(t.valid(n)&&t.has(n,$e)){const e=t.get(n,$e);e.pressed=!1,e.justReleased=!0,r.emit(n,"release"),n===s&&r.emit(n,"click")}n=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(exports.Schedule.Update,le([],()=>{const e=t.getEntitiesWithComponents([Le]);for(const r of e){if(t.has(r,De)||t.insert(r,De,{enabled:!0}),!t.has(r,$e))continue;const e=t.get(r,$e),s=t.get(r,Le),n=t.get(r,De),o=s.state;if(n.enabled?e.pressed?s.state=exports.ButtonState.Pressed:e.hovered?s.state=exports.ButtonState.Hovered:s.state=exports.ButtonState.Normal:s.state=exports.ButtonState.Disabled,o!==s.state&&s.transition&&t.has(r,L)){const e=t.get(r,L),n=s.transition;switch(s.state){case exports.ButtonState.Normal:e.color={...n.normalColor};break;case exports.ButtonState.Hovered:e.color={...n.hoveredColor};break;case exports.ButtonState.Pressed:e.color={...n.pressedColor};break;case exports.ButtonState.Disabled:e.color={...n.disabledColor}}t.insert(r,L,e)}}},{name:"ButtonSystem"}))}}const Ve=new Xe,Ge=F("ScreenSpace");function Ye(e,t,r,s,n,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,p,f,m;if(l===c&&u===d){const e=l+r.x,t=u+r.y,s=.5*n.x,o=.5*n.y;h=e-s,p=t-o,f=e+s,m=t+o}else h=l+r.x,p=u+r.y,f=c+s.x,m=d+s.y;return{centerX:.5*(h+f),centerY:.5*(p+m),width:f-h,height:m-p,rect:{left:h,bottom:p,right:f,top:m}}}function qe(e,t,r,s,n,o){if(!e.has(t,ve))return;const i=e.get(t,ve),a=Ye(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,r);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,$);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-n),e.insert(t,$,l),!e.has(t,X))return;const c=e.get(t,X);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&qe(e,t,a.rect,a.centerX,a.centerY,!1)}class Je{build(e){const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,le([Q(Ne)],e=>{if(!e.valid)return;const r={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(r.left+r.right),n=.5*(r.bottom+r.top),o=t.getEntitiesWithComponents([Ge,ve,$]);for(const e of o)qe(t,e,r,s,n,!0)},{name:"UILayoutSystem"}))}}const Ke=new Je,Qe=B("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class Ze{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const r=e.world,s=new Map,n=i(512,64),o=n.getContext("2d",{willReadFrequently:!0});let a=null,l=!1,c=!0,u=0,d=0;const h=function(){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}();function p(){if(null===a||!r.valid(a))return;const t=r.get(a,Qe);if(t.readOnly)return;let s=h.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),h.value=s),s!==t.value){t.value=s;e.getResource(Oe).emit(a,"change")}t.cursorPos=h.selectionStart??s.length,t.dirty=!0,g()}function f(e){if(a===e)return;m();const t=r.get(e,Qe);t.readOnly||(a=e,t.focused=!0,t.dirty=!0,h.value=t.value,h.selectionStart=t.cursorPos,h.selectionEnd=t.cursorPos,h.focus(),g())}function m(){if(null!==a&&r.valid(a)&&r.has(a,Qe)){const e=r.get(a,Qe);e.focused=!1,e.dirty=!0}a=null,h.blur()}function g(){c=!0,u=0}function x(e,i,a,l){(n.width<a||n.height<l)&&(n.width=tt(Math.max(n.width,a)),n.height=tt(Math.max(n.height,l))),o.clearRect(0,0,n.width,n.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,l),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,l),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,p=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*p.r)}, ${Math.round(255*p.g)}, ${Math.round(255*p.b)}, ${p.a})`;const f=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=et(o,h,a-2*m);let t=m;for(const r of e)o.fillText(r,m,t),t+=f}else{const e=(l-i.fontSize)/2;o.fillText(h,m,e)}if(i.focused&&c){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,r,s;if(i.multiline){const e=et(o,i.value.substring(0,i.cursorPos),a-2*m),n=e.length>0?e[e.length-1]:"";t=m+o.measureText(n).width,r=m+(e.length-1)*f,s=f}else t=m+o.measureText(e).width,r=(l-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,r,2,s)}o.restore();const g=o.getImageData(0,0,a,l),x=new Uint8Array(g.data.buffer),y=t.getResourceManager(),_=t._malloc(x.length);t.HEAPU8.set(x,_);const w=s.get(e);void 0!==w&&y.releaseTexture(w);const b=y.createTexture(a,l,_,x.length,1,!0);s.set(e,b),t._free(_);const v=r.get(e,L);v.texture=b,v.size.x=a,v.size.y=l,v.uvOffset.x=0,v.uvOffset.y=0,v.uvScale.x=1,v.uvScale.y=1,v.color={r:1,g:1,b:1,a:1},r.insert(e,L,v)}h.addEventListener("input",()=>{l||null===a||p()}),h.addEventListener("compositionstart",()=>{l=!0}),h.addEventListener("compositionend",()=>{l=!1,p()}),h.addEventListener("keydown",t=>{if(null===a)return;if("Escape"===t.key)return void m();const s=r.get(a,Qe);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(Oe).emit(a,"submit"),void m()}let n=s.cursorPos;"ArrowLeft"===t.key?n=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?n=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?n=0:"End"===t.key&&(n=s.value.length),n!==s.cursorPos&&(s.cursorPos=n,h.selectionStart=n,h.selectionEnd=n,s.dirty=!0,g())}),h.addEventListener("blur",()=>{if(null!==a&&r.valid(a)&&r.has(a,Qe)){const e=r.get(a,Qe);e.focused=!1,e.dirty=!0}a=null}),e.addSystemToSchedule(exports.Schedule.PreUpdate,le([Q(Oe)],e=>{const t=r.getEntitiesWithComponents([Qe,De]);for(const e of t){if(!r.has(e,$e))continue;if(r.get(e,$e).justPressed)return void f(e)}if(null!==a){const e=r.getEntitiesWithComponents([De]);for(const t of e){if(r.has(t,Qe))continue;if(!r.has(t,$e))continue;if(r.get(t,$e).justPressed)return void m()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(exports.Schedule.PreUpdate,le([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),n=0===d?0:(e-d)/1e3;if(d=e,null!==a&&(u+=n,u>=.5&&(u-=.5,c=!c,null!==a&&r.valid(a)&&r.has(a,Qe)))){r.get(a,Qe).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)r.valid(e)&&r.has(e,Qe)||(o.releaseTexture(t),s.delete(e));const i=r.getEntitiesWithComponents([Qe,ve]);for(const e of i){const t=r.get(e,Qe);if(!t.dirty)continue;const s=r.get(e,ve),n=Math.ceil(s.size.x),o=Math.ceil(s.size.y);n<=0||o<=0||(r.has(e,L)||r.insert(e,L,{texture:b,color:{r:1,g:1,b:1,a:1},size:{x:n,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),x(e,t,n,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function et(e,t,r){if(!t)return[""];if(r<=0)return t.split("\n");const s=t.split("\n"),n=[];for(const t of s){if(!t){n.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>r&&s?(n.push(s),s=o):s=t}s&&n.push(s)}return n.length>0?n:[""]}function tt(e){let t=1;for(;t<e;)t*=2;return t}const rt=new Ze;var st;function nt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(st=exports.BlendMode||(exports.BlendMode={}))[st.Normal=0]="Normal",st[st.Additive=1]="Additive",st[st.Multiply=2]="Multiply",st[st.Screen=3]="Screen",st[st.PremultipliedAlpha=4]="PremultipliedAlpha";let ot=null,it=null,at=1;const lt=new Map;function ct(e){ot=e,it=e.getResourceManager(),_t()}function ut(){0!==ft&&ot&&(ot._free(ft),ft=0),lt.clear(),at=1,pt=!1,it=null,ot=null}function dt(){if(!it)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return it}const ht={createShader:(e,t)=>dt().createShader(e,t),releaseShader(e){e>0&&dt().releaseShader(e)},create(e){const t=at++,r={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))r.uniforms.set(t,s);return lt.set(t,r),t},get:e=>lt.get(e),setUniform(e,t,r){const s=lt.get(e);s&&s.uniforms.set(t,r)},getUniform(e,t){const r=lt.get(e);return r?.uniforms.get(t)},setBlendMode(e,t){const r=lt.get(e);r&&(r.blendMode=t)},getBlendMode(e){const t=lt.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const r=lt.get(e);r&&(r.depthTest=t)},getShader(e){const t=lt.get(e);return t?.shader??0},release(e){lt.delete(e)},isValid:e=>lt.has(e),createFromAsset(e,t){const r={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)r[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?r[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(r[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:r,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=lt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const r=at++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return lt.set(r,s),r},toAssetData(e,t){const r=lt.get(e);if(!r)return null;const s={};for(const[e,t]of r.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:r.blendMode,depthTest:r.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 pt=!1,ft=0;const mt=4096,gt=new Map;let xt=null;function yt(e){const t=(0===ft&&ot&&(ft=ot._malloc(mt)),ft);if(0===t||!ot)return{ptr:0,count:0};let r=0,s=0;const n=ot.HEAPU8,o=ot.HEAPU32,i=ot.HEAPF32;for(const[a,l]of e){if(r+128>mt)break;let e=gt.get(a);e||(xt||(xt=new TextEncoder),e=xt.encode(a),gt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+r>>2]=c,r+=4,n.set(e,t+r),r+=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+r>>2]=d,r+=4;for(let e=0;e<4;e++)i[t+r>>2]=h[e],r+=4;s++}return{ptr:t,count:s}}function _t(){if(!ot||pt)return;ot.materialDataProvider=(e,t,r,s,n)=>{const o=lt.get(e);if(!o)return ot.HEAPU32[t>>2]=0,ot.HEAPU32[r>>2]=0,ot.HEAPU32[s>>2]=0,void(ot.HEAPU32[n>>2]=0);ot.HEAPU32[t>>2]=o.shader,ot.HEAPU32[r>>2]=o.blendMode;const{ptr:i,count:a}=yt(o.uniforms);ot.HEAPU32[s>>2]=i,ot.HEAPU32[n>>2]=a},pt=!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 bt{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const r=this.pending_.get(e);if(r)return r;const s=this.loadInternal(e);this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}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 o(t))throw new Error(`Material file not found: ${t}`);const r=await n(t);if(!r)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(r);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),a=await this.shaderLoader_.load(i);return{handle:ht.createFromAsset(s,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 r=e.substring(0,e.lastIndexOf("/"));return r?`${r}/${t}`:t}}function vt(e,t){const r=new Map;for(const s of t.entities){const t=e.spawn();if(r.set(s.id,t),e.insert(t,Y,{value:s.name}),!1!==s.visible)for(const r of s.components)Pt(e,t,r)}for(const s of t.entities)if(null!==s.parent){const t=r.get(s.id),n=r.get(s.parent);void 0!==t&&void 0!==n&&e.setParent(t,n)}return r}async function St(e,t,r){const s=new Map,n=r?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();if(s.set(i.id,t),e.insert(t,Y,{value:i.name}),!1!==i.visible)for(const s of i.components){if("Sprite"===s.type&&n){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:r?.assetBaseUrl?`${r.assetBaseUrl}/${t}`:`/${t}`;try{const r=await n.loadTexture(s);e.texture=r.handle,o.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("BitmapText"===s.type&&n){const e=s.data;if("string"==typeof e.font&&e.font)try{const t=await n.loadBitmapFont(e.font,r?.assetBaseUrl);e.font=t}catch(t){console.warn(`Failed to load bitmap font: ${e.font}`,t),e.font=0}}if("SpineAnimation"===s.type&&n){const e=s.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await n.loadSpine(t,o,r?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Pt(e,t,s)}}for(const r of t.entities)if(null!==r.parent){const t=s.get(r.id),n=s.get(r.parent);void 0!==t&&void 0!==n&&e.setParent(t,n)}if(n&&t.textureMetadata)for(const[e,r]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&r.sliceBorder&&n.setTextureMetadataByPath(t,r.sliceBorder)}return s}function Pt(e,t,r){const s=r.data;switch(r.type){case"LocalTransform":e.insert(t,$,s);break;case"Sprite":e.insert(t,L,s);break;case"Camera":e.insert(t,H,s);break;case"Canvas":e.insert(t,O,s);break;case"Text":e.insert(t,we,s);break;case"BitmapText":e.insert(t,V,s);break;case"SpineAnimation":e.insert(t,G,s);break;case"UIRect":{const r=s;r.anchor&&!r.anchorMin&&(r.anchorMin={...r.anchor},r.anchorMax={...r.anchor},delete r.anchor),e.insert(t,ve,r);break}case"UIMask":e.insert(t,Ae,s);break;case"Interactable":e.insert(t,De,s);break;case"Button":e.insert(t,Le,s);break;case"RigidBody":e.insert(t,P,s);break;case"BoxCollider":e.insert(t,C,s);break;case"CircleCollider":e.insert(t,T,s);break;case"CapsuleCollider":e.insert(t,A,s);break;default:{const n=U(r.type);n?e.insert(t,n,s):console.warn(`Unknown component type: ${r.type}`);break}}}class Ct{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const r=this.cache_.get(e);if(void 0!==r)return r;const s=this.pending_.get(e);if(s)return s;const n=t();this.pending_.set(e,n);try{const t=await n;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}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()}values(){return this.cache_.values()}}class Tt{constructor(e){this.textureCache_=new Ct,this.shaderCache_=new Ct,this.jsonCache_=new Ct,this.textCache_=new Ct,this.binaryCache_=new Ct,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Ct,this.prefabCache_=new Ct,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.module_=e,this.canvas_=i(512,512),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,r]of Object.entries(e))this.embedded_.set(t,r);this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const r of[!0,!1]){const s=this.textureCacheKey(e,r),n=this.textureCache_.get(s);n&&(t.releaseTexture(n.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);this.textureCache_.clear(),this.fontCache_.clear(),this.prefabCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.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 r=this.textureCache_.get(this.textureCacheKey(e,!0));return!!r&&(this.setTextureMetadata(r.handle,t),!0)}async loadSpine(e,t,r){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const n=this.resolveUrl(t,r),o=await this.fetchText(n);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);for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,r);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,r),c=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);return this.writeToVirtualFS(e,c)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const r=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(r,async()=>e.endsWith(".bmfont")?this.loadBmfontAsset(r):this.loadFntFile(r))}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),r=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 n=r?`${r}/${s}`:s;return this.loadFntFile(n)}async loadFntFile(e){const t=await this.fetchText(e),r=t.match(/file="([^"]+)"/);if(!r)throw new Error(`No page texture found in .fnt file: ${e}`);const s=r[1],n=e.substring(0,e.lastIndexOf("/")),o=n?`${n}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const r=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(r,()=>this.fetchJson(r))}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 r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(r):this.jsonCache_.getOrLoad(r,()=>this.fetchJson(r))}async loadText(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(r):this.textCache_.getOrLoad(r,()=>this.fetchText(r))}async loadBinary(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(r):this.binaryCache_.getOrLoad(r,()=>this.fetchBinary(r))}async loadScene(e,t){return St(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const r of Object.values(e.groups))r.assets&&t.push(...Object.values(r.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,r]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(r.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let r=this.labelIndex_.get(e);r||(r=[],this.labelIndex_.set(e,r)),r.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},r=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":r.push(this.loadTexture(s.path).then(r=>{t.textures.set(e,r)}));break;case"material":r.push(this.loadMaterial(s.path).then(r=>{t.materials.set(e,r)}));break;case"spine":{const n=s.metadata?.atlas;n&&r.push(this.loadSpine(s.path,n).then(r=>{t.spine.set(e,r)}));break}case"bitmap-font":r.push(this.loadBitmapFont(s.path).then(r=>{t.fonts.set(e,r)}));break;case"prefab":r.push(this.loadPrefab(s.path).then(r=>{t.prefabs.set(e,r)}));break;case"audio":case"binary":default:r.push(this.loadBinary(s.path).then(r=>{t.binary.set(e,r)}));break;case"json":r.push(this.loadJson(s.path).then(r=>{t.json.set(e,r)}));break;case"text":r.push(this.loadText(s.path).then(r=>{t.text.set(e,r)}))}}return await Promise.all(r),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const r=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(r,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const r=await this.loadImage(e);return this.createTextureFromImage(r,t)}async loadImage(e){const r=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(r);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const n=s??r;return new Promise((r,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 r(e)}catch{}r(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=n})}createTextureFromImage(e,t){const{width:r,height:s}=e,n=this.getWebGL2Context();return n?this.createTextureWebGL2(n,e,r,s,t):this.createTextureFallback(e,r,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,r,s,n){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,n?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,r,s),width:r,height:s}}createTextureFallback(e,t,r,s){(this.canvas_.width<t||this.canvas_.height<r)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(r))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const n=this.ctx_.getImageData(0,0,t,r),o=new Uint8Array(n.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,r,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:r}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const r=e[t+3];if(r>0&&r<255){const s=255/r;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,r=this.embedded_.get(t);if(r){const t=this.decodeDataUrlText(r),{vertex:s,fragment:n}=this.parseEsShader(t);if(!s||!n)throw new Error(`Invalid shader format: ${e}`);return ht.createShader(s,n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await o(t))throw new Error(`Shader file not found: ${e}`);const s=await n(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:a}=this.parseEsShader(s);if(!i||!a)throw new Error(`Invalid shader format: ${e}`);return ht.createShader(i,a)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),r=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:r?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r.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 r=this.embedded_.get(t);if(r)return JSON.parse(this.decodeDataUrlText(r));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const r=this.embedded_.get(t);if(r)return this.decodeDataUrlText(r);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return n(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const r=this.embedded_.get(t);if(r)return this.decodeDataUrlBinary(r);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return s(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 r=this.module_.FS;if(!r)return!1;try{return this.ensureVirtualDir(e),r.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 r=e.substring(0,e.lastIndexOf("/"));if(!r)return;const s=r.split("/").filter(e=>e);let n="";for(const e of s){n=n?`${n}/${e}`:e;try{t.analyzePath(n).exists||t.mkdir(n)}catch{try{t.mkdir(n)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const r=t??this.baseUrl;return r?`${r}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const At=K(null,"Assets");class Et{build(e){const t=e.wasmModule;t?e.insertResource(At,new Tt(t)):console.warn("AssetPlugin: No WASM module available")}}const Mt=new Et;async function Rt(e,t,r){const{entities:s,rootId:n}=await It(t,r?.overrides??[],r),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 St(e,o,{assetServer:r?.assetServer,assetBaseUrl:r?.assetBaseUrl}),a=i.get(n);return void 0!==r?.parent&&e.setParent(a,r.parent),{root:a,entities:i}}async function It(e,t,r,s){const n=new Map;let o;if(void 0===s){o=0;for(const t of e.entities)t.nestedPrefab||(n.set(t.prefabEntityId,t.prefabEntityId),o=Math.max(o,t.prefabEntityId+1))}else{o=s;for(const t of e.entities)t.nestedPrefab||n.set(t.prefabEntityId,o++)}const i=[];for(const s of e.entities){if(s.nestedPrefab){if(!r?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);const e=await r.assetServer.loadPrefab(s.nestedPrefab.prefabPath,r.assetBaseUrl),t=await It(e,s.nestedPrefab.overrides,r,o);n.set(s.prefabEntityId,t.rootId),o=t.nextId;const a=t.entities.find(e=>e.id===t.rootId);a&&(a.parent=null!==s.parent?n.get(s.parent)??null:null),i.push(...t.entities);continue}const a=n.get(s.prefabEntityId),l=s.prefabEntityId===e.rootEntityId,c={id:a,prefabEntityId:s.prefabEntityId,name:s.name,parent:l?null:null!==s.parent?n.get(s.parent)??null:null,children:s.children.map(e=>n.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};Bt(c,t),i.push(c)}const a=n.get(e.rootEntityId);if(void 0===a)throw new Error("Failed to resolve prefab root entity");return{entities:i,rootId:a,nextId:o}}function Bt(e,t){for(const r of t)if(r.prefabEntityId===e.prefabEntityId)switch(r.type){case"property":if(r.componentType&&void 0!==r.propertyName){const t=e.components.find(e=>e.type===r.componentType);t&&(t.data[r.propertyName]=r.value)}break;case"name":"string"==typeof r.value&&(e.name=r.value);break;case"visibility":"boolean"==typeof r.value&&(e.visible=r.value);break;case"component_added":if(r.componentData){e.components.some(e=>e.type===r.componentData.type)||e.components.push({type:r.componentData.type,data:JSON.parse(JSON.stringify(r.componentData.data))})}break;case"component_removed":r.componentType&&(e.components=e.components.filter(e=>e.type!==r.componentType))}}class Ft{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const r=this.assetServer_.resolveAddress(e),s=r?r.path:e,n=await this.assetServer_.loadPrefab(s,t?.baseUrl);return Rt(this.world_,n,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Ut=K(null,"Prefabs");class kt{build(e){const t=e.getResource(At);t?e.insertResource(Ut,new Ft(e.world,t)):console.warn("PrefabsPlugin: Assets resource not available")}}const Wt=new kt;let Dt=null,$t=0,zt=0,Lt=0;const Ht=new Float32Array(256);function Ot(e){Dt=e,$t=Dt._malloc(64),zt=Dt._malloc(64),Lt=Dt._malloc(1024)}function Nt(){Dt&&($t&&(Dt._free($t),$t=0),zt&&(Dt._free(zt),zt=0),Lt&&(Dt._free(Lt),Lt=0)),Dt=null}function jt(){if(!Dt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Dt}const Xt={r:1,g:1,b:1,a:1},Vt={begin(e){const t=jt();t.HEAPF32.set(e,$t/4),t.draw_begin($t)},end(){jt().draw_end()},line(e,t,r,s=1){jt().draw_line(e.x,e.y,t.x,t.y,r.r,r.g,r.b,r.a,s)},rect(e,t,r,s=!0){jt().draw_rect(e.x,e.y,t.x,t.y,r.r,r.g,r.b,r.a,s)},rectOutline(e,t,r,s=1){jt().draw_rectOutline(e.x,e.y,t.x,t.y,r.r,r.g,r.b,r.a,s)},circle(e,t,r,s=!0,n=32){jt().draw_circle(e.x,e.y,t,r.r,r.g,r.b,r.a,s,n)},circleOutline(e,t,r,s=1,n=32){jt().draw_circleOutline(e.x,e.y,t,r.r,r.g,r.b,r.a,s,n)},texture(e,t,r,s=Xt){jt().draw_texture(e.x,e.y,t.x,t.y,r,s.r,s.g,s.b,s.a)},textureRotated(e,t,r,s,n=Xt){jt().draw_textureRotated(e.x,e.y,t.x,t.y,r,s,n.r,n.g,n.b,n.a)},setLayer(e){jt().draw_setLayer(e)},setDepth(e){jt().draw_setDepth(e)},getDrawCallCount:()=>Dt?Dt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Dt?Dt.draw_getPrimitiveCount():0,setBlendMode(e){jt().draw_setBlendMode(e)},setDepthTest(e){jt().draw_setDepthTest(e)},drawMesh(e,t,r){const s=jt();s.HEAPF32.set(r,zt/4),s.draw_mesh(e,t,zt)},drawMeshWithMaterial(e,t,r){const s=jt(),n=ht.get(t);if(!n)return;if(Vt.setBlendMode(n.blendMode),Vt.setDepthTest(n.depthTest),0===n.uniforms.size)return void Vt.drawMesh(e,n.shader,r);s.HEAPF32.set(r,zt/4);let o=0,i=0;for(const[e,t]of n.uniforms){const r=Yt(e);if(!(r<0)){if(nt(t))Ht[o++]=10,Ht[o++]=r,Ht[o++]=t.slot??i++,Ht[o++]=t.textureId;else if("number"==typeof t)Ht[o++]=1,Ht[o++]=r,Ht[o++]=t;else if(Array.isArray(t)){Ht[o++]=t.length,Ht[o++]=r;for(let e=0;e<t.length;e++)Ht[o++]=t[e]}else"w"in t?(Ht[o++]=4,Ht[o++]=r,Ht[o++]=t.x,Ht[o++]=t.y,Ht[o++]=t.z,Ht[o++]=t.w):"z"in t?(Ht[o++]=3,Ht[o++]=r,Ht[o++]=t.x,Ht[o++]=t.y,Ht[o++]=t.z):(Ht[o++]=2,Ht[o++]=r,Ht[o++]=t.x,Ht[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(Ht.subarray(0,o),Lt/4),s.draw_meshWithUniforms(e,n.shader,zt,Lt,o)):s.draw_mesh(e,n.shader,zt)}},Gt={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function Yt(e){return Gt[e]??-1}var qt;exports.DataType=void 0,(qt=exports.DataType||(exports.DataType={}))[qt.Float=1]="Float",qt[qt.Float2=2]="Float2",qt[qt.Float3=3]="Float3",qt[qt.Float4=4]="Float4",qt[qt.Int=5]="Int",qt[qt.Int2=6]="Int2",qt[qt.Int3=7]="Int3",qt[qt.Int4=8]="Int4";let Jt=null,Kt=0,Qt=0,Zt=0;function er(e){Jt=e,Kt=Jt._malloc(262144),Qt=Jt._malloc(65536),Zt=Jt._malloc(256)}function tr(){Jt&&(Kt&&Jt._free(Kt),Qt&&Jt._free(Qt),Zt&&Jt._free(Zt),Kt=0,Qt=0,Zt=0),Jt=null}function rr(){if(!Jt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Jt}const sr={create(e){const t=rr(),r=t.geometry_create();if(0===r)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,Kt/4);const n=e.layout.length,o=new Int32Array(n);for(let t=0;t<n;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Zt,n).set(o),t.geometry_init(r,Kt,s,Zt,n,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,Qt,s).set(e.indices),t.geometry_setIndices16(r,Qt,s)}else{new Uint32Array(t.HEAPU8.buffer,Qt,s).set(e.indices),t.geometry_setIndices32(r,Qt,s)}}return r},updateVertices(e,t,r=0){const s=rr(),n=t.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);s.HEAPF32.set(t,Kt/4),s.geometry_updateVertices(e,Kt,n,r)},release(e){e>0&&rr().geometry_release(e)},isValid:e=>!(!Jt||e<=0)&&Jt.geometry_isValid(e),createQuad(e=1,t=1){const r=e/2,s=t/2;return sr.create({vertices:new Float32Array([-r,-s,0,0,r,-s,1,0,r,s,1,1,-r,s,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 r=[],s=[];r.push(0,0,.5,.5);for(let s=0;s<=t;s++){const n=s/t*Math.PI*2,o=Math.cos(n)*e,i=Math.sin(n)*e,a=(Math.cos(n)+1)/2,l=(Math.sin(n)+1)/2;r.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return sr.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.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,r=1/0,s=-1/0,n=-1/0;for(const o of e)t=Math.min(t,o.x),r=Math.min(r,o.y),s=Math.max(s,o.x),n=Math.max(n,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-r)/(n-r);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 sr.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 nr=null;function or(e){nr=e}function ir(){nr&&lr.isInitialized()&&lr.shutdown(),nr=null}function ar(){if(!nr)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return nr}const lr={init:(e,t)=>ar().postprocess_init(e,t),shutdown(){ar().postprocess_shutdown()},resize(e,t){ar().postprocess_resize(e,t)},addPass:(e,t)=>ar().postprocess_addPass(e,t),removePass(e){ar().postprocess_removePass(e)},setEnabled(e,t){ar().postprocess_setPassEnabled(e,t)},isEnabled:e=>ar().postprocess_isPassEnabled(e),setUniform(e,t,r){ar().postprocess_setUniformFloat(e,t,r)},setUniformVec4(e,t,r){ar().postprocess_setUniformVec4(e,t,r.x,r.y,r.z,r.w)},begin(){ar().postprocess_begin()},end(){ar().postprocess_end()},getPassCount:()=>ar().postprocess_getPassCount(),isInitialized:()=>!!nr&&nr.postprocess_isInitialized(),setBypass(e){ar().postprocess_setBypass(e)},isBypassed:()=>!nr||nr.postprocess_isBypassed(),createBlur:()=>ht.createShader(cr,"#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(cr,"#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(cr,"#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(cr,"#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")},cr="#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 ur;exports.RenderStage=void 0,(ur=exports.RenderStage||(exports.RenderStage={}))[ur.Background=0]="Background",ur[ur.Opaque=1]="Opaque",ur[ur.Transparent=2]="Transparent",ur[ur.Overlay=3]="Overlay";let dr=null,hr=0;function pr(e){dr=e,hr=dr._malloc(64)}function fr(){dr&&hr&&(dr._free(hr),hr=0),dr=null}const mr={init(e,t){dr?.renderer_init(e,t)},resize(e,t){dr?.renderer_resize(e,t)},begin(e,t){dr&&hr&&(dr.HEAPF32.set(e,hr/4),dr.renderer_begin(hr,t??0))},flush(){dr?.renderer_flush()},end(){dr?.renderer_end()},submitSprites(e){dr&&dr.renderer_submitSprites(e._cpp)},submitBitmapText(e){dr&&dr.renderer_submitBitmapText(e._cpp)},submitSpine(e){dr&&dr.renderer_submitSpine?.(e._cpp)},setStage(e){dr?.renderer_setStage(e)},createRenderTarget:(e,t,r=1)=>dr?.renderer_createTarget(e,t,r)??0,releaseRenderTarget(e){dr?.renderer_releaseTarget(e)},getTargetTexture:e=>dr?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>dr?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,r,s){dr?.renderer_setClearColor?.(e,t,r,s)},setViewport(e,t,r,s){dr?.renderer_setViewport(e,t,r,s)},setScissor(e,t,r,s,n){dr?.renderer_setScissor(e,t,r,s,n)},clearBuffers(e){dr?.renderer_clearBuffers(e)},measureBitmapText:(e,t,r,s)=>dr?dr.getResourceManager().measureBitmapText(e,t,r,s):{width:0,height:0},getStats:()=>dr?{drawCalls:dr.renderer_getDrawCalls(),triangles:dr.renderer_getTriangles(),sprites:dr.renderer_getSprites(),text:dr.renderer_getText(),spine:dr.renderer_getSpine?.()??0,meshes:dr.renderer_getMeshes(),culled:dr.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let gr=null;function xr(e){gr=e}function yr(){gr=null}const _r={enable(){gr?.gl_enableErrorCheck(!0)},disable(){gr?.gl_enableErrorCheck(!1)},check:e=>gr?.gl_checkErrors(e)??0,diagnose(){gr?.renderer_diagnose()}},wr=new Map;function br(e){wr.delete(e)}class vr{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:r,width:s,height:n,elapsed:o}=e;s===this.lastWidth_&&n===this.lastHeight_||(mr.resize(s,n),lr.isInitialized()&&lr.getPassCount()>0&&lr.resize(s,n),this.lastWidth_=s,this.lastHeight_=n),mr.setViewport(0,0,s,n),mr.clearBuffers(3),mr.begin(r),this.maskProcessor_&&this.maskProcessor_(t._cpp,r,0,0,s,n),mr.submitSprites(t),mr.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):mr.submitSpine(t),mr.flush(),this.executeDrawCallbacks(r,o),mr.end()}renderCamera(e){const{registry:t,viewProjection:r,viewportPixels:s,clearFlags:n,elapsed:o}=e;mr.setViewport(s.x,s.y,s.w,s.h),mr.setScissor(s.x,s.y,s.w,s.h,!0),mr.clearBuffers(n),mr.setScissor(0,0,0,0,!1),mr.begin(r),this.maskProcessor_&&this.maskProcessor_(t._cpp,r,s.x,s.y,s.w,s.h),mr.submitSprites(t),mr.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):mr.submitSpine(t),mr.flush(),this.executeDrawCallbacks(r,o),mr.end()}executeDrawCallbacks(e,t){const r=wr;if(r.size>0){Vt.begin(e);const s=[];for(const[e,n]of r.entries())try{n(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}Vt.end();for(const e of s)br(e)}}}class Sr{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=a(),t=e-this.lastTime_;this.lastTime_=e;const r=t/1e3;for(this.updateTime(r),this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=r;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate);this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),requestAnimationFrame(this.mainLoop)},this.world_=new ge,this.resources_=new ee;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Sr}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new ue(this.world_,this.resources_),this.resources_.insert(te,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1,yr(),fr(),ir(),tr(),ut(),Nt()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(te);t.delta=e,t.elapsed+=e,t.frameCount++}}const Pr=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Cr(e,t,r,s,n){const o=e*t/r,i=e;switch(s){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=n;return Math.pow(o,1-e)*Math.pow(i,e)}}}function Tr(e,t,r,s){if(0===r||0===s)return[];const n=e.registry_getCameraEntities(t);if(0===n.length)return[];const o=function(e,t){const r=e.registry_getCanvasEntity(t);return r<0?null:t.getCanvas(r)}(e,t),i=[];for(const e of n){const n=t.getCamera(e),a=t.getLocalTransform(e),l={x:n.viewportX,y:n.viewportY,w:n.viewportW,h:n.viewportH},c=l.w*r/(l.h*s);let u,d=0,h=0;if(1===n.projectionType){if(h=n.orthoSize,o){h=Cr(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=Er(-d,d,-h,h,-n.farPlane,n.farPlane)}else u=Rr(n.fov*Math.PI/180,c,n.nearPlane,n.farPlane);const p=Br(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:Fr(u,p),viewportRect:l,clearFlags:n.clearFlags,priority:n.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const Ar=new Float32Array(16);function Er(e,t,r,s,n,o){const i=Ar;i.fill(0);const a=t-e,l=s-r,c=o-n;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+r)/l,i[14]=-(o+n)/c,i[15]=1,i}const Mr=new Float32Array(16);function Rr(e,t,r,s){const n=Mr;n.fill(0);const o=1/Math.tan(e/2),i=r-s;return n[0]=o/t,n[5]=o,n[10]=(s+r)/i,n[11]=-1,n[14]=2*s*r/i,n}const Ir=new Float32Array(16);function Br(e,t,r){const s=Ir;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]=-r,s[15]=1,s}function Fr(e,t){const r=new Float32Array(16);for(let s=0;s<4;s++)for(let n=0;n<4;n++)r[4*n+s]=e[0+s]*t[4*n+0]+e[4+s]*t[4*n+1]+e[8+s]*t[4*n+2]+e[12+s]*t[4*n+3];return r}async function Ur(e,t){if(t)return t();return(0,(await import(e)).default)()}const kr=K({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Wr=K(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 $r(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class zr{constructor(e,t={},r){this.wasmUrl_=e,this.factory_=r,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,r=new Map,s=Ur(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const n=function(e){const t=e.world.getEntitiesWithComponents([O]);for(const r of t){const t=e.world.get(r,O);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/n,i=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,le([Q(te)],a=>{const l=i.getEntitiesWithComponents([P,$,z]),c=new Set;for(const n of l){c.add(n);const a=i.get(n,P),l=i.get(n,z);if(t.has(n)){const e=r.get(n);!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(n,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);s._physics_createBody(n,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),Lr(e,s,n),t.add(n),r.set(n,{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=Dr(l.rotation);s._physics_setBodyTransform(n,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),r.delete(e));s._physics_step(a.delta),function(e,t,r){const s=t._physics_getDynamicBodyCount();if(0===s)return;const n=t._physics_getDynamicBodyTransforms(),o=n>>2;for(let n=0;n<s;n++){const s=o+4*n,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*r,l=t.HEAPF32[s+2]*r,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,$);if(!u)continue;let d=a,h=l,p=c;if(e.world.has(i,j)){const t=e.world.get(i,j);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,z)){const r=e.world.get(t.entity,z),s=Dr(r.rotation),n=a-r.position.x,o=l-r.position.y,i=Math.cos(-s),u=Math.sin(-s);d=(n*i-o*u)/(0!==r.scale.x?r.scale.x:1),h=(n*u+o*i)/(0!==r.scale.y?r.scale.y:1),p=c-s}}u.position.x=d,u.position.y=h;const f=$r(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,$,u)}}(e,s,n),function(e,t,r){t._physics_collectEvents();const s=[],n=t._physics_getCollisionEnterCount();if(n>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<n;o++){const n=e+6*o;s.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1],normalX:t.HEAPF32[n+2],normalY:t.HEAPF32[n+3],contactX:t.HEAPF32[n+4]*r,contactY:t.HEAPF32[n+5]*r})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let r=0;r<i;r++){const s=e+2*r;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 r=0;r<l;r++){const s=e+2*r;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 r=0;r<u;r++){const s=e+2*r;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(kr,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,n)},{name:"PhysicsSystem"})),e.__physicsModule=s,e.insertResource(Wr,Hr._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=s}}function Lr(e,t,r){const s=e.world;if(s.has(r,C)){const e=s.get(r,C);return void t._physics_addBoxShape(r,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(r,T)){const e=s.get(r,T);return void t._physics_addCircleShape(r,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(r,A)){const e=s.get(r,A);t._physics_addCapsuleShape(r,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Hr{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(Hr.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function Or(e,t,r=!0){const s=e.getResourceManager(),n=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,n);const o=s.createTexture(t.width,t.height,n,t.pixels.length,1,r);return e._free(n),o}function Nr(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function jr(e,t,r,s){const n=e.scale.x*t*(r?-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,p=c+c,f=a*d,m=a*h,g=a*p,x=l*h,y=l*p,_=c*p,w=u*d,b=u*h,v=u*p;return new Float32Array([(1-(x+_))*n,(m+v)*n,(g-b)*n,0,(m-v)*o,(1-(f+_))*o,(y+w)*o,0,(g+b)*i,(y-w)*i,(1-(f+x))*i,0,e.position.x,e.position.y,e.position.z,1])}async function Xr(e,t,r,s,n,o,i,a){const l=await async function(e,t,r){const s={};for(const n of t.entities)for(const t of n.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const n=t.data.texture;if(void 0!==s[n])continue;try{s[n]=Or(e,await r.loadPixels(n))}catch{s[n]=0}}return s}(t,r,s);!function(e,t,r){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const n=r[e];if(n&&n>0){const r=t.textureMetadata[e];if(r?.sliceBorder){const e=r.sliceBorder;s.setTextureMetadata(n,e.left,e.right,e.top,e.bottom)}}}}(t,r,l);let c={},u=null;if(n&&(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"])}}(n),c=await async function(e,t,r,s,n){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=n.resolvePath(i),c=n.resolvePath(a);try{const s=n.readText(a),u=l.endsWith(".skel");let d,h;if(u){const e=n.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=n.readText(i),r=(new TextEncoder).encode(e);h=r.length,d=t._malloc(h+1),t.HEAPU8.set(r,d),t.HEAPU8[d+h]=0}const p=r.loadSkeleton(d,h,s,s.length,u);if(t._free(d),p<0)continue;o[i]=p;const f=Nr(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const s=m+"/"+f[t];try{const o=n.loadPixelsRaw?await n.loadPixelsRaw(s):await n.loadPixels(s),i=Or(e,o,!1),a=e.getResourceManager().getTextureGLId(i);r.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,n,u,r,s)),o){new zr("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,r){const s={};for(const n of t.entities)for(const t of n.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const n=t.data.font;if(void 0===s[n])try{let t,o;if(n.endsWith(".bmfont")){const e=JSON.parse(r.readText(n)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[n]=0;continue}const a=n.substring(0,n.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=r.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=r.readText(n),o=n.substring(0,n.lastIndexOf("/"));const i=t.match(/file="([^"]+)"/);if(!i){s[n]=0;continue}const a=o?`${o}/${i[1]}`:i[1],l=r.loadPixelsRaw?await r.loadPixelsRaw(a):await r.loadPixels(a),c=Or(e,l,!1),u=e.getResourceManager();s[n]=u.loadBitmapFont(t,c,l.width,l.height)}catch{s[n]=0}}return s}(t,r,s),h=function(e,t){const r={},s={};for(const n of e.entities)for(const e of n.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const n=e.data.material;if(void 0===r[n])try{const e=JSON.parse(t.readText(n));if(!e.vertexSource||!e.fragmentSource){r[n]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=ht.createShader(e.vertexSource,e.fragmentSource),s[o]=i),r[n]=ht.createFromAsset(e,i)}catch{r[n]=0}}return r}(r,s),p=vt(e.world,r);if(function(e,t,r,s){for(const n of t.entities){const t=s.get(n.id);if(void 0!==t)for(const s of n.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const n=e.get(t,L);n&&(n.texture=r[s.data.texture]||0,e.insert(t,L,n))}}}(e.world,r,l,p),function(e,t,r,s){for(const n of t.entities){const t=s.get(n.id);if(void 0!==t)for(const s of n.components){if("BitmapText"!==s.type||!s.data.font||"string"!=typeof s.data.font)continue;const n=r[s.data.font]||0;if(!n)continue;const o=e.get(t,V);o&&(o.font=n,e.insert(t,V,o))}}}(e.world,r,d,p),function(e,t,r,s){for(const n of t.entities){const t=s.get(n.id);if(void 0!==t)for(const s of n.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const n=r[s.data.material]||0;if(n)if("Sprite"===s.type){const r=e.get(t,L);r&&(r.material=n,e.insert(t,L,r))}else if("SpineAnimation"===s.type){const r=e.get(t,G);r&&(r.material=n,e.insert(t,G,r))}}}}(e.world,r,h,p),n&&u){const s=function(e,t,r,s){const n={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=r[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(n[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return n}(u,r,c,p);!function(e,t,r,s,n){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in n){const o=Number(e),i=n[e],a=c.has(o,G)?c.get(o,G):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(i,l*d);let h=0;if(c.has(o,z)){const e=jr(c.get(o,z),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=s.getMeshBatchCount(i);for(let e=0;e<p;e++){const n=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!n||!o)continue;const a=8*n*4,l=2*o,c=r._malloc(a),u=r._malloc(l),d=r._malloc(4),p=r._malloc(4);s.getMeshBatchData(i,e,c,u,d,p);const f=r.HEAPU32[d>>2],m=r.HEAPU32[p>>2],g=new Float32Array(r.HEAPF32.buffer,c,8*n),x=new Uint16Array(r.HEAPU8.buffer,u,o),y=t._malloc(a),_=t._malloc(l);t.HEAPF32.set(g,y>>2),new Uint16Array(t.HEAPU8.buffer,_,o).set(x),t.renderer_submitTriangles(y,n,_,o,f,m,h),t._free(y),t._free(_),r._free(c),r._free(u),r._free(d),r._free(p)}h&&t._free(h)}})}(e,t,n,u,s)}if(a){const t=e.getResource(At);t&&t.setAddressableManifest(a)}}class Vr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,r=new Set,s=new Set;for(const n of e.entities)for(const e of n.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,n=e.data.atlasPath;s&&(s.endsWith(".skel")?r.add(s):t.add(s)),n&&t.add(n)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const n=[];for(const e of t)n.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of r)n.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(n);const o=[];for(const e of s){if(!e.endsWith(".bmfont"))continue;const t=this.textCache_.get(e);if(t)try{const r=JSON.parse(t),s="label-atlas"===r.type?r.generatedFnt:r.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),r=t?`${t}/${s}`:s;this.textCache_.has(r)||o.push(fetch(this.resolveUrl(r)).then(e=>e.text()).then(e=>{this.textCache_.set(r,e)}).catch(()=>{}))}}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),r=await fetch(t),s=await r.blob(),n=await createImageBitmap(s),o=new OffscreenCanvas(n.width,n.height).getContext("2d");o.drawImage(n,0,0);const i=o.getImageData(0,0,n.width,n.height);return n.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Gr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),r=mr.createRenderTarget(e.width,e.height,t);return{_handle:r,textureId:mr.getTargetTexture(r),width:e.width,height:e.height}},release(e){mr.releaseRenderTarget(e._handle)},resize:(e,t,r)=>(mr.releaseRenderTarget(e._handle),Gr.create({width:t,height:r,depth:!0})),begin(e,t){mr.begin(t,e._handle)},end(){mr.end()},getDepthTexture:e=>mr.getTargetDepthTexture(e._handle)};let Yr=!1;_||(_=!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 r="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},n=await l(r,s);return{ok:n.ok,status:n.status,statusText:n.statusText,headers:new Headers(n.headers),json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.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:r}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return c(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),r=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);n<128?r[s++]=n:n<2048?(r[s++]=192|n>>6,r[s++]=128|63&n):n>=55296&&n<=56319?(n=e.charCodeAt(++t)-56320+(n-55296<<10)+65536,r[s++]=240|n>>18,r[s++]=128|n>>12&63,r[s++]=128|n>>6&63,r[s++]=128|63&n):(r[s++]=224|n>>12,r[s++]=128|n>>6&63,r[s++]=128|63&n)}return r.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let r="";for(let e=0;e<t.length;){const s=t[e];if(s<128)r+=String.fromCharCode(s),e++;else if(192==(224&s))r+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))r+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const n=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;r+=String.fromCharCode(55296+(n>>10),56320+(1023&n)),e+=4}}return r}})}(),console.log("[ESEngine] WeChat platform initialized")),e=w,exports.App=Sr,exports.AssetPlugin=Et,exports.AssetServer=Tt,exports.Assets=At,exports.AsyncCache=Ct,exports.BitmapText=V,exports.BodyType=E,exports.BoxCollider=C,exports.Button=Le,exports.Camera=H,exports.Canvas=O,exports.CapsuleCollider=A,exports.Children=X,exports.CircleCollider=T,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=oe,exports.Draw=Vt,exports.EntityCommands=ne,exports.GLDebug=_r,exports.Geometry=sr,exports.INVALID_ENTITY=0,exports.INVALID_FONT=v,exports.INVALID_TEXTURE=b,exports.Input=he,exports.InputPlugin=pe,exports.InputState=de,exports.Interactable=De,exports.LocalTransform=$,exports.Material=ht,exports.MaterialLoader=bt,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=Y,exports.Parent=j,exports.Physics=Hr,exports.PhysicsEvents=kr,exports.PhysicsPlugin=zr,exports.PostProcess=lr,exports.PrefabServer=Ft,exports.Prefabs=Ut,exports.PrefabsPlugin=kt,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(!this.app_)return;let e="fetch scene";try{const t=await r(this.sceneUrl_);if(!t.ok)throw new Error(`Failed to fetch scene: ${t.status}`);e="parse scene JSON";const s=await t.json();e="prefetch assets";const n=new Vr(this.baseUrl_);await n.prefetch(s);let o=null;const i=this.app_.__spineInitPromise;if(i){e="init spine";o=(await i).controller.raw}e="loadRuntimeScene",await Xr(this.app_,this.app_.wasmModule,s,n,o),e="ensureCamera",this.ensureCamera()}catch(t){const r=t instanceof Error?t.message:String(t),s=t instanceof Error?t.stack:"";throw console.error(`[PreviewPlugin] Failed at step "${e}": ${r}\n${s}`),new Error(`[PreviewPlugin:${e}] ${r}`)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const r=e.getEntitiesWithComponents([H]);for(const s of r){if(e.get(s,H).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,r=1920/1080;const s=e.getEntitiesWithComponents([O]);for(const n of s){const s=e.get(n,O);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,r=s.designResolution.x/s.designResolution.y;break}}const n=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(n,$,o);const i={isActive:!0,projectionType:1,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:r,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3};e.insert(n,H,i)}}},exports.Query=function(...e){return function(e,t=[],r=[]){const s=[];return e.forEach((e,t)=>{re(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:r}}(e)},exports.QueryInstance=se,exports.RenderPipeline=vr,exports.RenderTexture=Gr,exports.Renderer=mr,exports.Res=Q,exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.RigidBody=P,exports.ScreenSpace=Ge,exports.ShaderSources=wt,exports.SpineAnimation=G,exports.Sprite=L,exports.SystemRunner=ue,exports.Text=we,exports.TextInput=Qe,exports.TextInputPlugin=Ze,exports.TextPlugin=Ce,exports.TextRenderer=be,exports.Time=te,exports.UICameraInfo=Ne,exports.UIEventQueue=He,exports.UIEvents=Oe,exports.UIInteraction=$e,exports.UIInteractionPlugin=Xe,exports.UILayoutPlugin=Je,exports.UIMask=Ae,exports.UIMaskPlugin=ke,exports.UIRect=ve,exports.Velocity=N,exports.WebAssetProvider=Vr,exports.World=ge,exports.WorldTransform=z,exports.addStartupSystem=function(e){ce().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){ce().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){ce().push({schedule:e,system:t})},exports.assetPlugin=Mt,exports.clearDrawCallbacks=function(){wr.clear()},exports.clearUserComponents=function(){I().clear()},exports.color=(e=1,t=1,r=1,s=1)=>({r:e,g:t,b:r,a:s}),exports.computeUIRectLayout=Ye,exports.createMaskProcessor=Ue,exports.createWebApp=function(e,t){const r=Sr.new(),s=new e.Registry;r.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ot(e),ct(e),er(e),or(e),pr(e),xr(e);const n=new vr;r.pipeline_=n;let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function l(t,n){const o=Tr(e,s,t,n),i=r.getResource(Ne);if(o.length>0){const e=o[0],r=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(r.x*t),i.vpY=Math.round((1-r.y-r.h)*n),i.vpW=Math.round(r.w*t),i.vpH=Math.round(r.h*n),i.screenW=t,i.screenH=n,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}r.insertResource(Ne,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();l(e,t)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:r}=i();if(0===t||0===r)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;mr.setClearColor(e.x,e.y,e.z,e.w)}const u=(a()-o)/1e3;mr.resize(t,r),lr.isInitialized()&&lr.getPassCount()>0&&!lr.isBypassed()&&lr.resize(t,r);const d=Tr(e,s,t,r);if(l(t,r),0===d.length)n.render({registry:{_cpp:s},viewProjection:Pr,width:t,height:r,elapsed:u});else{for(const e of d){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*r),l=Math.round(o.w*t),c=Math.round(o.h*r);n.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:c},clearFlags:e.clearFlags,elapsed:u})}mr.setViewport(0,0,t,r)}}};return r.addSystemToSchedule(exports.Schedule.First,c),r.addSystemToSchedule(exports.Schedule.Last,u),r.addPlugin(Mt),r.addPlugin(Wt),r.addPlugin(fe),r.addPlugin(Te),r.addPlugin(We),r.addPlugin(Ke),r.addPlugin(Ve),r.addPlugin(rt),r},exports.defineComponent=B,exports.defineResource=K,exports.defineSystem=le,exports.defineTag=F,exports.findEntityByName=function(e,t){const r=e.getEntitiesWithComponents([Y]);for(const s of r){const r=e.get(s,Y);if(r&&r.value===t)return s}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const r of t)e.addSystemToSchedule(r.schedule,r.system);t.length=0}},exports.getComponentDefaults=function(e){const t=q[e];if(t)return{...t._default};const r=U(e);return r?{...r._default}:null},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=U,exports.initDrawAPI=Ot,exports.initGLDebugAPI=xr,exports.initGeometryAPI=er,exports.initMaterialAPI=ct,exports.initPostProcessAPI=or,exports.initRendererAPI=pr,exports.inputPlugin=fe,exports.instantiatePrefab=Rt,exports.intersectRects=Ee,exports.invertMatrix4=Re,exports.isBuiltinComponent=D,exports.isEditor=function(){return Yr},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!Yr},exports.isTextureRef=nt,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=Pt,exports.loadPhysicsModule=Ur,exports.loadRuntimeScene=Xr,exports.loadSceneData=vt,exports.loadSceneWithAssets=St,exports.platformFetch=r,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,r){return t().instantiateWasm(e,r)},exports.platformReadFile=s,exports.platformReadTextFile=n,exports.pointInWorldRect=Be,exports.prefabsPlugin=Wt,exports.quat=(e=1,t=0,r=0,s=0)=>({w:e,x:t,y:r,z:s}),exports.registerDrawCallback=function(e,t){wr.set(e,t)},exports.registerEmbeddedAssets=function(e,t){const r=e.getResource(At);r&&r.registerEmbeddedAssets(t)},exports.registerMaterialCallback=_t,exports.screenToWorld=Ie,exports.setEditorMode=function(e){Yr=e},exports.shutdownDrawAPI=Nt,exports.shutdownGLDebugAPI=yr,exports.shutdownGeometryAPI=tr,exports.shutdownMaterialAPI=ut,exports.shutdownPostProcessAPI=ir,exports.shutdownRendererAPI=fr,exports.textInputPlugin=rt,exports.textPlugin=Te,exports.uiInteractionPlugin=Ve,exports.uiLayoutPlugin=Ke,exports.uiMaskPlugin=We,exports.unregisterDrawCallback=br,exports.updateCameraAspectRatio=function(e,t){const r=e.getEntitiesWithComponents([H]);for(const s of r){const r=e.get(s,H);r&&(r.aspectRatio=t,e.insert(s,H,r))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,r=0)=>({x:e,y:t,z:r}),exports.vec4=(e=0,t=0,r=0,s=1)=>({x:e,y:t,z:r,w:s}),exports.worldRectToScreen=Me,exports.wxFileExists=f,exports.wxFileExistsSync=function(e){const t=d();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=y,exports.wxLoadImage=x,exports.wxLoadImagePixels=async function(e){return y(await x(e))},exports.wxReadFile=h,exports.wxReadTextFile=p,exports.wxWriteFile=function(e,t){return new Promise((r,s)=>{d().writeFile({filePath:e,data:t,success:()=>r(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};
//# sourceMappingURL=index.wechat.cjs.js.map
diff --git a/desktop/public/sdk/cjs/index.wechat.js b/desktop/public/sdk/cjs/index.wechat.js
index 7cd9cadf0..71274691c 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}`)}}let m=null;function g(){return m||(m=wx.getFileSystemManager()),m}function y(e){return new Promise((t,n)=>{g().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function _(e,t="utf-8"){return new Promise((n,s)=>{g().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function w(e){return new Promise(t=>{g().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function x(e){const t=g();try{return t.accessSync(e),!0}catch{return!1}}function b(e,t){return new Promise((n,s)=>{g().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}let v=null,S=null;function P(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 C(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){return v||(v=wx.createCanvas(),v.width=e,v.height=t,S=v.getContext("2d")),(v.width<e||v.height<t)&&(v.width=Math.max(v.width,e),v.height=Math.max(v.height,t)),{canvas:v,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 E(e){return C(await P(e))}let T=!1;const M=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return y(e)}async readTextFile(e){return _(e)}async fileExists(e){return w(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return p(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const n=wx.createCanvas();return n.width=e,n.height=t,n}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{const n=t.touches[0];n&&e.onPointerDown(0,n.clientX,n.clientY)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX,n.clientY)}),wx.onTouchEnd(()=>{e.onPointerUp(0)})}},A=0,R=4294967295,F=4294967295,U=(e=0,t=0)=>({x:e,y:t}),B=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),I=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),k=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),W=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function $(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const z=$("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),D=$("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),H=$("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),L=$("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),O={Static:0,Kinematic:1,Dynamic:2};let N=0;function j(e,t){const n=++N;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function X(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function V(e,t){const n=X(),s=n.get(e);if(s)return s;const r=j(e,t);return n.set(e,r),J(e,t,!1),r}function G(e){const t=X(),n=t.get(e);if(n)return n;const s=j(e,{});return t.set(e,s),J(e,{},!0),s}function Y(e){return X().get(e)}function q(){X().clear()}function J(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function K(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function Q(e){return!0===e._builtin}const Z=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}}),ee=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}}),te=K("Sprite",{texture:R,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}),ne=K("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),se=K("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),re=K("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),oe=K("Parent",{entity:0}),ie=K("Children",{entities:[]}),ae=K("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:F}),le=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}),ce={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},ue={LocalTransform:Z,WorldTransform:ee,Sprite:te,Camera:ne,Canvas:se,Velocity:re,Parent:oe,Children:ie,BitmapText:ae,SpineAnimation:le,RigidBody:z,BoxCollider:D,CircleCollider:H,CapsuleCollider:L};function de(e){const t=ue[e];if(t)return{...t._default};const n=Y(e);return n?{...n._default}:null}let he=0;function fe(e,t){const n=++he;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function pe(e){return{_type:"res",_resource:e}}function me(e){return{_type:"res_mut",_resource:e}}class ge{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}}class ye{constructor(){this.resources_=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)}getResMut(e){return new ge(this.get(e),t=>this.set(e,t))}}const _e=fe({delta:0,elapsed:0,frameCount:0},"Time");function we(e){return{_type:"mut",_component:e}}function xe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function be(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{xe(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class ve{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>xe(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with)}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),r=n.length,o=e.length>0,i=t.length>0,a=new Array(r+1);let l=null,c=[];try{for(const u of s){if(null!==l&&o){for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}c.length=0}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(u,t[n])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,n[e]);if(o){for(let t=0;t<e.length;t++){const s=e[t];c.push({component:n[s],data:a[s+1]})}l=u}yield a}}finally{if(null!==l&&o)for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,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 Se(){return{_type:"commands"}}class Pe{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 Ce{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Pe(this,null);return this.spawned_.push(e),e}entity(e){return new Pe(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_=[];for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}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":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Ee;!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"}(Ee||(Ee={}));let Te=0;function Me(e,t,n){const s=++Te;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Ae(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Re(e){Ae().push({schedule:Ee.Update,system:e})}function Fe(e){Ae().push({schedule:Ee.Startup,system:e})}function Ue(e,t){Ae().push({schedule:e,system:t})}class Be{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Ce&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new ve(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Ce(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ie{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const ke=fe(new Ie,"Input");class We{constructor(e){this.target_=e??null}build(e){const n=new Ie;e.insertResource(ke,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(Ee.Last,Me([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const $e=new We;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 De{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return 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)}remove(e,t){Q(t)?this.removeBuiltin(e,t):this.removeScript(e,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 r={...t._default,...s};if(this.cppRegistry_){const n=`add${t._cppName}`,s=this.cppRegistry_[n];s?.call(this.cppRegistry_,e,ze(r))}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const n=`get${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const n=`has${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const n=`remove${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e)}insertScript(e,t,n){const s=t.create(n);return this.getStorage(t).set(e,s),s}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)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();let t=null,n=1/0;for(const s of e)if(!Q(s)){const e=this.tsStorage_.get(s._id),r=e?e.size:0;r<n&&(n=r,t=e??null)}const s=[],r=t?t.keys():this.entities_;for(const t of r){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&s.push(t)}return s}}var He,Le,Oe;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(He||(He={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Le||(Le={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Oe||(Oe={}));const Ne=V("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:He.Left,verticalAlign:Le.Top,wordWrap:!0,overflow:Oe.Visible,lineHeight:1.2});class je{constructor(e){this.cache=new Map,this.module=e,this.canvas=d(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=r?Math.ceil(o):d+2*u,p=r?Math.ceil(i):h+2*u;if(r&&e.overflow===Oe.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${g}, ${y}, ${_})`,r&&e.overflow===Oe.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 Le.Top:x=u;break;case Le.Middle:x=(p-w)/2;break;case Le.Bottom:x=p-w-u;break;default:x=u}else x=u;let b=x;for(const t of l){let s;switch(e.align){case He.Left:s=u;break;case He.Center:s=f/2;break;case He.Right:s=f-u;break;default:s=u}n.fillText(t,s,b),b+=c}r&&e.overflow===Oe.Clip&&n.restore();const v=n.getImageData(0,0,f,p),S=new Uint8Array(v.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const E=P.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{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()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case He.Left:return"left";case He.Center:return"center";case He.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const Xe=V("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}});function Ve(e){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight}}function Ge(e,t){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight}class Ye{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new je(t),s=e.world,r=new Map;e.addSystemToSchedule(Ee.PreUpdate,Me([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Ne));for(const e of r.keys())s.valid(e)&&s.has(e,Ne)||r.delete(e);const e=s.getEntitiesWithComponents([Ne]);for(const t of e){const e=s.get(t,Ne),o=r.get(t);if(o&&!Ge(o,e))continue;s.has(t,te)||s.insert(t,te,{texture:R,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const i=s.has(t,Xe)?s.get(t,Xe):null,a=n.renderForEntity(t,e,i),l=s.get(t,te);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,te,l),r.set(t,Ve(e))}}))}}const qe=new Ye,Je=V("UIMask",{enabled:!0});function Ke(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 Qe(e,t,n,s,r,o,i,a,l,c,u){const d=e-n*r,h=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function m(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*u]}const[g,y]=m(d,f),[_,w]=m(h,p),x=Math.min(g,_),b=Math.max(g,_),v=Math.min(y,w),S=Math.max(y,w);return{x:Math.round(x),y:Math.round(v),w:Math.round(b-x),h:Math.round(S-v)}}function Ze(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],f=e[10],p=e[11],m=e[12],g=e[13],y=e[14],_=e[15],w=s*l-r*a,x=s*c-o*a,b=s*u-i*a,v=r*c-o*l,S=r*u-i*l,P=o*u-i*c,C=d*g-h*m,E=d*y-f*m,T=d*_-p*m,M=h*y-f*g,A=h*_-p*g,R=f*_-p*y;let F=w*R-x*A+b*M+v*T-S*E+P*C;return 0===F||(F=1/F,n[0]=(l*R-c*A+u*M)*F,n[1]=(o*A-r*R-i*M)*F,n[2]=(g*P-y*S+_*v)*F,n[3]=(f*S-h*P-p*v)*F,n[4]=(c*T-a*R-u*E)*F,n[5]=(s*R-o*T+i*E)*F,n[6]=(y*b-m*P-_*x)*F,n[7]=(d*P-f*b+p*x)*F,n[8]=(a*A-l*T+u*C)*F,n[9]=(r*T-s*A-i*C)*F,n[10]=(m*S-g*b+_*w)*F,n[11]=(h*b-d*S-p*w)*F,n[12]=(l*E-a*M-c*C)*F,n[13]=(s*M-r*E+o*C)*F,n[14]=(g*x-m*v-y*w)*F,n[15]=(d*v-h*x+f*w)*F),n}function et(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 tt(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 nt(e,t,n,s,r,o,i){if(!e.has(t,Xe)||!e.has(t,ee))return null;const a=e.get(t,Xe),l=e.get(t,ee),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return Qe(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function st(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Je]);if(0!==l.length)try{!function(e,t,n,s,r,o,i,a,l){const c=new Set;for(const e of s){t.get(e,Je).enabled&&c.add(e)}const u=[];for(const e of s){if(!c.has(e))continue;let n=!0,s=e;for(;t.has(s,oe);){const e=t.get(s,oe);if(c.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(c.has(n)){const e=nt(t,n,r,o,i,a,l);e&&(s=Ke(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=nt(t,e,r,o,i,a,l);n&&d(e,n)}}(e,t,n,l,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class rt{build(e){if(!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(st(e.wasmModule,e.world))}}const ot=new rt,it=V("Interactable",{enabled:!0}),at=V("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var lt;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(lt||(lt={}));const ct=V("Button",{state:lt.Normal,transition:null});class ut{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const dt=fe(new ut,"UIEvents"),ht=fe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo"),ft=new Float32Array(16);class pt{build(e){const t=e.world,n=new ut;e.insertResource(dt,n);let s=null,r=null;e.addSystemToSchedule(Ee.PreUpdate,Me([pe(ke),pe(ht)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([at]);for(const e of i){const n=t.get(e,at);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;Ze(o.viewProjection,ft);const u=et(l,c,ft,o.vpX,o.vpY,o.vpW,o.vpH),d=t.getEntitiesWithComponents([it,Xe,ee]);let h=null,f=-1/0;for(const e of d){t.has(e,at)||t.insert(e,at);if(!t.get(e,it).enabled)continue;const n=t.get(e,ee),s=t.get(e,Xe),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(tt(u.x,u.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y)){let n=0;t.has(e,te)&&(n=t.get(e,te).layer),n>=f&&(f=n,h=e)}}if(s!==h){if(null!==s&&t.valid(s)&&t.has(s,at)){t.get(s,at).hovered=!1,n.emit(s,"hover_exit")}if(null!==h){t.get(h,at).hovered=!0,n.emit(h,"hover_enter")}s=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,at);e.pressed=!0,e.justPressed=!0,r=h,n.emit(h,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,at)){const e=t.get(r,at);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Ee.Update,Me([],()=>{const e=t.getEntitiesWithComponents([ct]);for(const n of e){if(t.has(n,it)||t.insert(n,it,{enabled:!0}),!t.has(n,at))continue;const e=t.get(n,at),s=t.get(n,ct),r=t.get(n,it),o=s.state;if(r.enabled?e.pressed?s.state=lt.Pressed:e.hovered?s.state=lt.Hovered:s.state=lt.Normal:s.state=lt.Disabled,o!==s.state&&s.transition&&t.has(n,te)){const e=t.get(n,te),r=s.transition;switch(s.state){case lt.Normal:e.color={...r.normalColor};break;case lt.Hovered:e.color={...r.hoveredColor};break;case lt.Pressed:e.color={...r.pressedColor};break;case lt.Disabled:e.color={...r.disabledColor}}t.insert(n,te,e)}}},{name:"ButtonSystem"}))}}const mt=new pt,gt=G("ScreenSpace");function yt(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,f,p,m;if(l===c&&u===d){const e=l+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;h=e-s,f=t-o,p=e+s,m=t+o}else h=l+n.x,f=u+n.y,p=c+s.x,m=d+s.y;return{centerX:.5*(h+p),centerY:.5*(f+m),width:p-h,height:m-f,rect:{left:h,bottom:f,right:p,top:m}}}function _t(e,t,n,s,r,o){if(!e.has(t,Xe))return;const i=e.get(t,Xe),a=yt(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,Z);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,Z,l),!e.has(t,ie))return;const c=e.get(t,ie);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&_t(e,t,a.rect,a.centerX,a.centerY,!1)}class wt{build(e){const t=e.world;e.addSystemToSchedule(Ee.PreUpdate,Me([pe(ht)],e=>{if(!e.valid)return;const n={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(n.left+n.right),r=.5*(n.bottom+n.top),o=t.getEntitiesWithComponents([gt,Xe,Z]);for(const e of o)_t(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const xt=new wt,bt=V("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class vt{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=d(512,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,u=0;const h=function(){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}();function f(){if(null===i||!n.valid(i))return;const t=n.get(i,bt);if(t.readOnly)return;let s=h.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),h.value=s),s!==t.value){t.value=s;e.getResource(dt).emit(i,"change")}t.cursorPos=h.selectionStart??s.length,t.dirty=!0,g()}function p(e){if(i===e)return;m();const t=n.get(e,bt);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,h.value=t.value,h.selectionStart=t.cursorPos,h.selectionEnd=t.cursorPos,h.focus(),g())}function m(){if(null!==i&&n.valid(i)&&n.has(i,bt)){const e=n.get(i,bt);e.focused=!1,e.dirty=!0}i=null,h.blur()}function g(){l=!0,c=0}function y(e,i,a,c){(r.width<a||r.height<c)&&(r.width=Pt(Math.max(r.width,a)),r.height=Pt(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=St(o,h,a-2*m);let t=m;for(const n of e)o.fillText(n,m,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(h,m,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=St(o,i.value.substring(0,i.cursorPos),a-2*m),r=e.length>0?e[e.length-1]:"";t=m+o.measureText(r).width,n=m+(e.length-1)*p,s=p}else t=m+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const g=o.getImageData(0,0,a,c),y=new Uint8Array(g.data.buffer),_=t.getResourceManager(),w=t._malloc(y.length);t.HEAPU8.set(y,w);const x=s.get(e);void 0!==x&&_.releaseTexture(x);const b=_.createTexture(a,c,w,y.length,1,!0);s.set(e,b),t._free(w);const v=n.get(e,te);v.texture=b,v.size.x=a,v.size.y=c,v.uvOffset.x=0,v.uvOffset.y=0,v.uvScale.x=1,v.uvScale.y=1,v.color={r:1,g:1,b:1,a:1},n.insert(e,te,v)}h.addEventListener("input",()=>{a||null===i||f()}),h.addEventListener("compositionstart",()=>{a=!0}),h.addEventListener("compositionend",()=>{a=!1,f()}),h.addEventListener("keydown",t=>{if(null===i)return;if("Escape"===t.key)return void m();const s=n.get(i,bt);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(dt).emit(i,"submit"),void m()}let r=s.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?r=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=s.value.length),r!==s.cursorPos&&(s.cursorPos=r,h.selectionStart=r,h.selectionEnd=r,s.dirty=!0,g())}),h.addEventListener("blur",()=>{if(null!==i&&n.valid(i)&&n.has(i,bt)){const e=n.get(i,bt);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(Ee.PreUpdate,Me([pe(dt)],e=>{const t=n.getEntitiesWithComponents([bt,it]);for(const e of t){if(!n.has(e,at))continue;if(n.get(e,at).justPressed)return void p(e)}if(null!==i){const e=n.getEntitiesWithComponents([it]);for(const t of e){if(n.has(t,bt))continue;if(!n.has(t,at))continue;if(n.get(t,at).justPressed)return void m()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Ee.PreUpdate,Me([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,bt)))){n.get(i,bt).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,bt)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([bt,Xe]);for(const e of a){const t=n.get(e,bt);if(!t.dirty)continue;const s=n.get(e,Xe),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,te)||n.insert(e,te,{texture:R,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),y(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function St(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function Pt(e){let t=1;for(;t<e;)t*=2;return t}const Ct=new vt;var Et;function Tt(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"}(Et||(Et={}));let Mt=null,At=null,Rt=1;const Ft=new Map;function Ut(e){Mt=e,At=e.getResourceManager(),Ot()}function Bt(){0!==$t&&Mt&&(Mt._free($t),$t=0),Ft.clear(),Rt=1,Wt=!1,At=null,Mt=null}function It(){if(!At)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return At}const kt={createShader:(e,t)=>It().createShader(e,t),releaseShader(e){e>0&&It().releaseShader(e)},create(e){const t=Rt++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Et.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return Ft.set(t,n),t},get:e=>Ft.get(e),setUniform(e,t,n){const s=Ft.get(e);s&&s.uniforms.set(t,n)},getUniform(e,t){const n=Ft.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Ft.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Ft.get(e);return t?.blendMode??Et.Normal},setDepthTest(e,t){const n=Ft.get(e);n&&(n.depthTest=t)},getShader(e){const t=Ft.get(e);return t?.shader??0},release(e){Ft.delete(e)},isValid:e=>Ft.has(e),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??Et.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ft.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};return Ft.set(n,s),n},toAssetData(e,t){const n=Ft.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=Ft.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Wt=!1,$t=0;const zt=4096,Dt=new Map;let Ht=null;function Lt(e){const t=(0===$t&&Mt&&($t=Mt._malloc(zt)),$t);if(0===t||!Mt)return{ptr:0,count:0};let n=0,s=0;const r=Mt.HEAPU8,o=Mt.HEAPU32,i=Mt.HEAPF32;for(const[a,l]of e){if(n+128>zt)break;let e=Dt.get(a);e||(Ht||(Ht=new TextEncoder),e=Ht.encode(a),Dt.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 Ot(){if(!Mt||Wt)return;Mt.materialDataProvider=(e,t,n,s,r)=>{const o=Ft.get(e);if(!o)return Mt.HEAPU32[t>>2]=0,Mt.HEAPU32[n>>2]=0,Mt.HEAPU32[s>>2]=0,void(Mt.HEAPU32[r>>2]=0);Mt.HEAPU32[t>>2]=o.shader,Mt.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Lt(o.uniforms);Mt.HEAPU32[s>>2]=i,Mt.HEAPU32[r>>2]=a},Wt=!0}const Nt={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class jt{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const n=this.pending_.get(e);if(n)return n;const s=this.loadInternal(e);this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(kt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())kt.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:kt.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function Xt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,ce,{value:s.name}),!1!==s.visible)for(const n of s.components)Gt(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function Vt(e,t,n){const s=new Map,r=n?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();if(s.set(i.id,t),e.insert(t,ce,{value:i.name}),!1!==i.visible)for(const s of i.components){if("Sprite"===s.type&&r){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:n?.assetBaseUrl?`${n.assetBaseUrl}/${t}`:`/${t}`;try{const n=await r.loadTexture(s);e.texture=n.handle,o.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("BitmapText"===s.type&&r){const e=s.data;if("string"==typeof e.font&&e.font)try{const t=await r.loadBitmapFont(e.font,n?.assetBaseUrl);e.font=t}catch(t){console.warn(`Failed to load bitmap font: ${e.font}`,t),e.font=0}}if("SpineAnimation"===s.type&&r){const e=s.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await r.loadSpine(t,o,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Gt(e,t,s)}}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function Gt(e,t,n){const s=n.data;switch(n.type){case"LocalTransform":e.insert(t,Z,s);break;case"Sprite":e.insert(t,te,s);break;case"Camera":e.insert(t,ne,s);break;case"Canvas":e.insert(t,se,s);break;case"Text":e.insert(t,Ne,s);break;case"BitmapText":e.insert(t,ae,s);break;case"SpineAnimation":e.insert(t,le,s);break;case"UIRect":{const n=s;n.anchor&&!n.anchorMin&&(n.anchorMin={...n.anchor},n.anchorMax={...n.anchor},delete n.anchor),e.insert(t,Xe,n);break}case"UIMask":e.insert(t,Je,s);break;case"Interactable":e.insert(t,it,s);break;case"Button":e.insert(t,ct,s);break;case"RigidBody":e.insert(t,z,s);break;case"BoxCollider":e.insert(t,D,s);break;case"CircleCollider":e.insert(t,H,s);break;case"CapsuleCollider":e.insert(t,L,s);break;default:{const r=Y(n.type);r?e.insert(t,r,s):console.warn(`Unknown component type: ${n.type}`);break}}}function Yt(e,t){const n=e.getEntitiesWithComponents([ne]);for(const s of n){const n=e.get(s,ne);n&&(n.aspectRatio=t,e.insert(s,ne,n))}}function qt(e,t){const n=e.getEntitiesWithComponents([ce]);for(const s of n){const n=e.get(s,ce);if(n&&n.value===t)return s}return null}class Jt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const n=this.cache_.get(e);if(void 0!==n)return n;const s=this.pending_.get(e);if(s)return s;const r=t();this.pending_.set(e,r);try{const t=await r;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}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()}values(){return this.cache_.values()}}class Kt{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.module_=e,this.canvas_=d(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new jt(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);this.textureCache_.clear(),this.fontCache_.clear(),this.prefabCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.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)}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);for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,n),c=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);return this.writeToVirtualFS(e,c)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}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()=>e.endsWith(".bmfont")?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 Vt(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)}}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)}))}}return await Promise.all(n),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??n;return new Promise((n,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return kt.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 kt.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 Qt=fe(null,"Assets");class Zt{build(e){const t=e.wasmModule;t?e.insertResource(Qt,new Kt(t)):console.warn("AssetPlugin: No WASM module available")}}const en=new Zt;function tn(e,t){const n=e.getResource(Qt);n&&n.registerEmbeddedAssets(t)}async function nn(e,t,n){const{entities:s,rootId:r}=await sn(t,n?.overrides??[],n),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 Vt(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}async function sn(e,t,n,s){const r=new Map;let o;if(void 0===s){o=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),o=Math.max(o,t.prefabEntityId+1))}else{o=s;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,o++)}const i=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await sn(e,s.nestedPrefab.overrides,n,o);r.set(s.prefabEntityId,t.rootId),o=t.nextId;const a=t.entities.find(e=>e.id===t.rootId);a&&(a.parent=null!==s.parent?r.get(s.parent)??null:null),i.push(...t.entities);continue}const a=r.get(s.prefabEntityId),l=s.prefabEntityId===e.rootEntityId,c={id:a,prefabEntityId:s.prefabEntityId,name:s.name,parent:l?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};rn(c,t),i.push(c)}const a=r.get(e.rootEntityId);if(void 0===a)throw new Error("Failed to resolve prefab root entity");return{entities:i,rootId:a,nextId:o}}function rn(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 on{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=await this.assetServer_.loadPrefab(e,t?.baseUrl);return nn(this.world_,n,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const an=fe(null,"Prefabs");class ln{build(e){const t=e.getResource(Qt);t?e.insertResource(an,new on(e.world,t)):console.warn("PrefabsPlugin: Assets resource not available")}}const cn=new ln;let un=null,dn=0,hn=0,fn=0;const pn=new Float32Array(256);function mn(e){un=e,dn=un._malloc(64),hn=un._malloc(64),fn=un._malloc(1024)}function gn(){un&&(dn&&(un._free(dn),dn=0),hn&&(un._free(hn),hn=0),fn&&(un._free(fn),fn=0)),un=null}function yn(){if(!un)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return un}const _n={r:1,g:1,b:1,a:1},wn={begin(e){const t=yn();t.HEAPF32.set(e,dn/4),t.draw_begin(dn)},end(){yn().draw_end()},line(e,t,n,s=1){yn().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rect(e,t,n,s=!0){yn().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rectOutline(e,t,n,s=1){yn().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},circle(e,t,n,s=!0,r=32){yn().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},circleOutline(e,t,n,s=1,r=32){yn().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=_n){yn().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)},textureRotated(e,t,n,s,r=_n){yn().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){yn().draw_setLayer(e)},setDepth(e){yn().draw_setDepth(e)},getDrawCallCount:()=>un?un.draw_getDrawCallCount():0,getPrimitiveCount:()=>un?un.draw_getPrimitiveCount():0,setBlendMode(e){yn().draw_setBlendMode(e)},setDepthTest(e){yn().draw_setDepthTest(e)},drawMesh(e,t,n){const s=yn();s.HEAPF32.set(n,hn/4),s.draw_mesh(e,t,hn)},drawMeshWithMaterial(e,t,n){const s=yn(),r=kt.get(t);if(!r)return;if(wn.setBlendMode(r.blendMode),wn.setDepthTest(r.depthTest),0===r.uniforms.size)return void wn.drawMesh(e,r.shader,n);s.HEAPF32.set(n,hn/4);let o=0,i=0;for(const[e,t]of r.uniforms){const n=bn(e);if(!(n<0)){if(Tt(t))pn[o++]=10,pn[o++]=n,pn[o++]=t.slot??i++,pn[o++]=t.textureId;else if("number"==typeof t)pn[o++]=1,pn[o++]=n,pn[o++]=t;else if(Array.isArray(t)){pn[o++]=t.length,pn[o++]=n;for(let e=0;e<t.length;e++)pn[o++]=t[e]}else"w"in t?(pn[o++]=4,pn[o++]=n,pn[o++]=t.x,pn[o++]=t.y,pn[o++]=t.z,pn[o++]=t.w):"z"in t?(pn[o++]=3,pn[o++]=n,pn[o++]=t.x,pn[o++]=t.y,pn[o++]=t.z):(pn[o++]=2,pn[o++]=n,pn[o++]=t.x,pn[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(pn.subarray(0,o),fn/4),s.draw_meshWithUniforms(e,r.shader,hn,fn,o)):s.draw_mesh(e,r.shader,hn)}},xn={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function bn(e){return xn[e]??-1}var vn;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(vn||(vn={}));let Sn=null,Pn=0,Cn=0,En=0;function Tn(e){Sn=e,Pn=Sn._malloc(262144),Cn=Sn._malloc(65536),En=Sn._malloc(256)}function Mn(){Sn&&(Pn&&Sn._free(Pn),Cn&&Sn._free(Cn),En&&Sn._free(En),Pn=0,Cn=0,En=0),Sn=null}function An(){if(!Sn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Sn}const Rn={create(e){const t=An(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,Pn/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,En,r).set(o),t.geometry_init(n,Pn,s,En,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,Cn,s).set(e.indices),t.geometry_setIndices16(n,Cn,s)}else{new Uint32Array(t.HEAPU8.buffer,Cn,s).set(e.indices),t.geometry_setIndices32(n,Cn,s)}}return n},updateVertices(e,t,n=0){const s=An(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,Pn/4),s.geometry_updateVertices(e,Pn,r,n)},release(e){e>0&&An().geometry_release(e)},isValid:e=>!(!Sn||e<=0)&&Sn.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Rn.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:vn.Float2},{name:"a_texCoord",type:vn.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 Rn.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:vn.Float2},{name:"a_texCoord",type:vn.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 Rn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:vn.Float2},{name:"a_texCoord",type:vn.Float2}],indices:new Uint16Array(i)})}};let Fn=null;function Un(e){Fn=e}function Bn(){Fn&&kn.isInitialized()&&kn.shutdown(),Fn=null}function In(){if(!Fn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Fn}const kn={init:(e,t)=>In().postprocess_init(e,t),shutdown(){In().postprocess_shutdown()},resize(e,t){In().postprocess_resize(e,t)},addPass:(e,t)=>In().postprocess_addPass(e,t),removePass(e){In().postprocess_removePass(e)},setEnabled(e,t){In().postprocess_setPassEnabled(e,t)},isEnabled:e=>In().postprocess_isPassEnabled(e),setUniform(e,t,n){In().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){In().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){In().postprocess_begin()},end(){In().postprocess_end()},getPassCount:()=>In().postprocess_getPassCount(),isInitialized:()=>!!Fn&&Fn.postprocess_isInitialized(),setBypass(e){In().postprocess_setBypass(e)},isBypassed:()=>!Fn||Fn.postprocess_isBypassed(),createBlur:()=>kt.createShader(Wn,"#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:()=>kt.createShader(Wn,"#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:()=>kt.createShader(Wn,"#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:()=>kt.createShader(Wn,"#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")},Wn="#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 $n;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}($n||($n={}));let zn=null,Dn=0;function Hn(e){zn=e,Dn=zn._malloc(64)}function Ln(){zn&&Dn&&(zn._free(Dn),Dn=0),zn=null}const On={init(e,t){zn?.renderer_init(e,t)},resize(e,t){zn?.renderer_resize(e,t)},begin(e,t){zn&&Dn&&(zn.HEAPF32.set(e,Dn/4),zn.renderer_begin(Dn,t??0))},flush(){zn?.renderer_flush()},end(){zn?.renderer_end()},submitSprites(e){zn&&zn.renderer_submitSprites(e._cpp)},submitBitmapText(e){zn&&zn.renderer_submitBitmapText(e._cpp)},submitSpine(e){zn&&zn.renderer_submitSpine?.(e._cpp)},setStage(e){zn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>zn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){zn?.renderer_releaseTarget(e)},getTargetTexture:e=>zn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>zn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){zn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){zn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){zn?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){zn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>zn?zn.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>zn?{drawCalls:zn.renderer_getDrawCalls(),triangles:zn.renderer_getTriangles(),sprites:zn.renderer_getSprites(),text:zn.renderer_getText(),spine:zn.renderer_getSpine?.()??0,meshes:zn.renderer_getMeshes(),culled:zn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Nn=null;function jn(e){Nn=e}function Xn(){Nn=null}const Vn={enable(){Nn?.gl_enableErrorCheck(!0)},disable(){Nn?.gl_enableErrorCheck(!1)},check:e=>Nn?.gl_checkErrors(e)??0,diagnose(){Nn?.renderer_diagnose()}},Gn=new Map;function Yn(e,t){Gn.set(e,t)}function qn(e){Gn.delete(e)}function Jn(){Gn.clear()}class Kn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(On.resize(s,r),kn.isInitialized()&&kn.getPassCount()>0&&kn.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),On.setViewport(0,0,s,r),On.clearBuffers(3),On.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),On.submitSprites(t),On.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):On.submitSpine(t),On.flush(),this.executeDrawCallbacks(n,o),On.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;On.setViewport(s.x,s.y,s.w,s.h),On.setScissor(s.x,s.y,s.w,s.h,!0),On.clearBuffers(r),On.setScissor(0,0,0,0,!1),On.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),On.submitSprites(t),On.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):On.submitSpine(t),On.flush(),this.executeDrawCallbacks(n,o),On.end()}executeDrawCallbacks(e,t){const n=Gn;if(n.size>0){wn.begin(e);const s=[];for(const[e,r]of n.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}wn.end();for(const e of s)qn(e)}}}class Qn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=h(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.runSchedule(Ee.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Ee.FixedPreUpdate),this.runSchedule(Ee.FixedUpdate),this.runSchedule(Ee.FixedPostUpdate);this.runSchedule(Ee.PreUpdate),this.runSchedule(Ee.Update),this.runSchedule(Ee.PostUpdate),this.runSchedule(Ee.Last),requestAnimationFrame(this.mainLoop)},this.world_=new De,this.resources_=new ye;for(const e of Object.values(Ee))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Qn}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(Ee.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Ee.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new Be(this.world_,this.resources_),this.resources_.insert(_e,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Ee.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1,Xn(),Ln(),Bn(),Mn(),Bt(),gn()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(_e);t.delta=e,t.elapsed+=e,t.frameCount++}}function Zn(e,t){const n=Qn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),mn(e),Ut(e),Tn(e),Un(e),Hn(e),jn(e);const r=new Kn;n.pipeline_=r;let o=h();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r){const o=ss(e,s,t,r),i=n.getResource(ht);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(ht,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=i();if(0===t||0===n)return;const l=e.registry_getCanvasEntity(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;On.setClearColor(e.x,e.y,e.z,e.w)}const c=(h()-o)/1e3;On.resize(t,n),kn.isInitialized()&&kn.getPassCount()>0&&!kn.isBypassed()&&kn.resize(t,n);const u=ss(e,s,t,n);if(a(t,n),0===u.length)r.render({registry:{_cpp:s},viewProjection:ts,width:t,height:n,elapsed:c});else{for(const e of u){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*n),l=Math.round(o.w*t),u=Math.round(o.h*n);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}On.setViewport(0,0,t,n)}}};return n.addSystemToSchedule(Ee.First,l),n.addSystemToSchedule(Ee.Last,c),n.addPlugin(en),n.addPlugin(cn),n.addPlugin($e),n.addPlugin(qe),n.addPlugin(ot),n.addPlugin(xt),n.addPlugin(mt),n.addPlugin(Ct),n}function es(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 ts=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ns(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}}}function ss(e,t,n,s){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*n/(l.h*s);let u,d=0,h=0;if(1===r.projectionType){if(h=r.orthoSize,o){h=ns(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=os(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=as(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=cs(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:us(u,f),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const rs=new Float32Array(16);function os(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 as(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 ls=new Float32Array(16);function cs(e,t,n){const s=ls;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}function us(e,t){const n=new Float32Array(16);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}async function ds(e,t){if(t)return t();return(0,(await import(e)).default)()}const hs=fe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),fs=fe(null,"PhysicsAPI");function ps(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function ms(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class gs{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(hs,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=ds(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([se]);for(const n of t){const t=e.world.get(n,se);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(Ee.PostUpdate,Me([pe(_e)],a=>{const l=i.getEntitiesWithComponents([z,Z,ee]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,z),l=i.get(r,ee);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=ps(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),ys(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===O.Kinematic){const e=ps(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,Z);if(!u)continue;let d=a,h=l,f=c;if(e.world.has(i,oe)){const t=e.world.get(i,oe);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ee)){const n=e.world.get(t.entity,ee),s=ps(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=ms(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,Z,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(hs,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.__physicsModule=s,e.insertResource(fs,_s._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=s}}function ys(e,t,n){const s=e.world;if(s.has(n,D)){const e=s.get(n,D);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,H)){const e=s.get(n,H);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,L)){const e=s.get(n,L);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 _s{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(_s.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 ws(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 xs(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 bs(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,f=c+c,p=a*d,m=a*h,g=a*f,y=l*h,_=l*f,w=c*f,x=u*d,b=u*h,v=u*f;return new Float32Array([(1-(y+w))*r,(m+v)*r,(g-b)*r,0,(m-v)*o,(1-(p+w))*o,(_+x)*o,0,(g+b)*i,(_-x)*i,(1-(p+y))*i,0,e.position.x,e.position.y,e.position.z,1])}async function vs(e,t,n,s,r,o,i,a){const l=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=ws(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,l);let c={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),c=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=r.readText(a),u=l.endsWith(".skel");let d,h;if(u){const e=r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=r.readText(i),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const f=n.loadSkeleton(d,h,s,s.length,u);if(t._free(d),f<0)continue;o[i]=f;const p=xs(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=ws(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,n,s)),o){new gs("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;if(r.endsWith(".bmfont")){const e=JSON.parse(n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const i=t.match(/file="([^"]+)"/);if(!i){s[r]=0;continue}const a=o?`${o}/${i[1]}`:i[1],l=n.loadPixelsRaw?await n.loadPixelsRaw(a):await n.loadPixels(a),c=ws(e,l,!1),u=e.getResourceManager();s[r]=u.loadBitmapFont(t,c,l.width,l.height)}catch{s[r]=0}}return s}(t,n,s),h=function(e,t){const n={},s={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===n[r])try{const e=JSON.parse(t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=kt.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=kt.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),f=Xt(e.world,n);if(function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const r=e.get(t,te);r&&(r.texture=n[s.data.texture]||0,e.insert(t,te,r))}}}(e.world,n,l,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if("BitmapText"!==s.type||!s.data.font||"string"!=typeof s.data.font)continue;const r=n[s.data.font]||0;if(!r)continue;const o=e.get(t,ae);o&&(o.font=r,e.insert(t,ae,o))}}}(e.world,n,d,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const r=n[s.data.material]||0;if(r)if("Sprite"===s.type){const n=e.get(t,te);n&&(n.material=r,e.insert(t,te,n))}else if("SpineAnimation"===s.type){const n=e.get(t,le);n&&(n.material=r,e.insert(t,le,n))}}}}(e.world,n,h,f),r&&u){const s=function(e,t,n,s){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,n,c,f);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,le)?c.get(o,le):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(i,l*d);let h=0;if(c.has(o,ee)){const e=bs(c.get(o,ee),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,d,f);const p=n.HEAPU32[d>>2],m=n.HEAPU32[f>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*r),y=new Uint16Array(n.HEAPU8.buffer,u,o),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,_>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(y),t.renderer_submitTriangles(_,r,w,o,p,m,h),t._free(_),t._free(w),n._free(c),n._free(u),n._free(d),n._free(f)}h&&t._free(h)}})}(e,t,r,u,s)}if(a){const t=e.getResource(Qt);t&&t.setAddressableManifest(a)}}class Ss{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&(s.endsWith(".skel")?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));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(()=>{}));await Promise.all(r);const o=[];for(const e of s){if(!e.endsWith(".bmfont"))continue;const t=this.textCache_.get(e);if(t)try{const n=JSON.parse(t),s="label-atlas"===n.type?n.generatedFnt:n.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(()=>{}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class Ps{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(!this.app_)return;let e="fetch scene";try{const t=await i(this.sceneUrl_);if(!t.ok)throw new Error(`Failed to fetch scene: ${t.status}`);e="parse scene JSON";const n=await t.json();e="prefetch assets";const s=new Ss(this.baseUrl_);await s.prefetch(n);let r=null;const o=this.app_.__spineInitPromise;if(o){e="init spine";r=(await o).controller.raw}e="loadRuntimeScene",await vs(this.app_,this.app_.wasmModule,n,s,r),e="ensureCamera",this.ensureCamera()}catch(t){const n=t instanceof Error?t.message:String(t),s=t instanceof Error?t.stack:"";throw console.error(`[PreviewPlugin] Failed at step "${e}": ${n}\n${s}`),new Error(`[PreviewPlugin:${e}] ${n}`)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([ne]);for(const s of n){if(e.get(s,ne).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const s=e.getEntitiesWithComponents([se]);for(const r of s){const s=e.get(r,se);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,Z,o);const i={isActive:!0,projectionType:1,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3};e.insert(r,ne,i)}}}const Cs={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=On.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:On.getTargetTexture(n),width:e.width,height:e.height}},release(e){On.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(On.releaseRenderTarget(e._handle),Cs.create({width:t,height:n,depth:!0})),begin(e,t){On.begin(t,e._handle)},end(){On.end()},getDepthTexture:e=>On.getTargetDepthTexture(e._handle)};let Es=!1;function Ts(e){Es=e}function Ms(){return Es}function As(){return!Es}T||(T=!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=M;export{Qn as App,Zt as AssetPlugin,Kt as AssetServer,Qt as Assets,Jt as AsyncCache,ae as BitmapText,Et as BlendMode,O as BodyType,D as BoxCollider,ct as Button,lt as ButtonState,ne as Camera,se as Canvas,L as CapsuleCollider,ie as Children,H as CircleCollider,Se as Commands,Ce as CommandsInstance,vn as DataType,wn as Draw,Pe as EntityCommands,Vn as GLDebug,Rn as Geometry,A as INVALID_ENTITY,F as INVALID_FONT,R as INVALID_TEXTURE,ke as Input,We as InputPlugin,Ie as InputState,it as Interactable,Z as LocalTransform,kt as Material,jt as MaterialLoader,we as Mut,ce as Name,oe as Parent,_s as Physics,hs as PhysicsEvents,gs as PhysicsPlugin,kn as PostProcess,on as PrefabServer,an as Prefabs,ln as PrefabsPlugin,Ps as PreviewPlugin,be as Query,ve as QueryInstance,Kn as RenderPipeline,$n as RenderStage,Cs as RenderTexture,On as Renderer,pe as Res,me as ResMut,z as RigidBody,Ee as Schedule,gt as ScreenSpace,Nt as ShaderSources,le as SpineAnimation,te as Sprite,Be as SystemRunner,Ne as Text,He as TextAlign,bt as TextInput,vt as TextInputPlugin,Oe as TextOverflow,Ye as TextPlugin,je as TextRenderer,Le as TextVerticalAlign,_e as Time,ht as UICameraInfo,ut as UIEventQueue,dt as UIEvents,at as UIInteraction,pt as UIInteractionPlugin,wt as UILayoutPlugin,Je as UIMask,rt as UIMaskPlugin,Xe as UIRect,re as Velocity,Ss as WebAssetProvider,De as World,ee as WorldTransform,Fe as addStartupSystem,Re as addSystem,Ue as addSystemToSchedule,en as assetPlugin,Jn as clearDrawCallbacks,q as clearUserComponents,k as color,yt as computeUIRectLayout,st as createMaskProcessor,Zn as createWebApp,V as defineComponent,fe as defineResource,Me as defineSystem,G as defineTag,qt as findEntityByName,es as flushPendingSystems,de as getComponentDefaults,t as getPlatform,s as getPlatformType,Y as getUserComponent,mn as initDrawAPI,jn as initGLDebugAPI,Tn as initGeometryAPI,Ut as initMaterialAPI,Un as initPostProcessAPI,Hn as initRendererAPI,$e as inputPlugin,nn as instantiatePrefab,Ke as intersectRects,Ze as invertMatrix4,Q as isBuiltinComponent,Ms as isEditor,n as isPlatformInitialized,As as isRuntime,Tt as isTextureRef,r as isWeChat,o as isWeb,Gt as loadComponent,ds as loadPhysicsModule,vs as loadRuntimeScene,Xt as loadSceneData,Vt as loadSceneWithAssets,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,tt as pointInWorldRect,cn as prefabsPlugin,W as quat,Yn as registerDrawCallback,tn as registerEmbeddedAssets,Ot as registerMaterialCallback,et as screenToWorld,Ts as setEditorMode,gn as shutdownDrawAPI,Xn as shutdownGLDebugAPI,Mn as shutdownGeometryAPI,Bt as shutdownMaterialAPI,Bn as shutdownPostProcessAPI,Ln as shutdownRendererAPI,Ct as textInputPlugin,qe as textPlugin,mt as uiInteractionPlugin,xt as uiLayoutPlugin,ot as uiMaskPlugin,qn as unregisterDrawCallback,Yt as updateCameraAspectRatio,U as vec2,B as vec3,I as vec4,Qe as worldRectToScreen,w as wxFileExists,x as wxFileExistsSync,C as wxGetImagePixels,P as wxLoadImage,E as wxLoadImagePixels,y as wxReadFile,_ as wxReadTextFile,b 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 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}`)}}let m=null;function g(){return m||(m=wx.getFileSystemManager()),m}function y(e){return new Promise((t,n)=>{g().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function _(e,t="utf-8"){return new Promise((n,s)=>{g().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function w(e){return new Promise(t=>{g().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function x(e){const t=g();try{return t.accessSync(e),!0}catch{return!1}}function b(e,t){return new Promise((n,s)=>{g().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}let v=null,S=null;function P(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 C(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){return v||(v=wx.createCanvas(),v.width=e,v.height=t,S=v.getContext("2d")),(v.width<e||v.height<t)&&(v.width=Math.max(v.width,e),v.height=Math.max(v.height,t)),{canvas:v,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 E(e){return C(await P(e))}let T=!1;const M=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return y(e)}async readTextFile(e){return _(e)}async fileExists(e){return w(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return p(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const n=wx.createCanvas();return n.width=e,n.height=t,n}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{const n=t.touches[0];n&&e.onPointerDown(0,n.clientX,n.clientY)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX,n.clientY)}),wx.onTouchEnd(()=>{e.onPointerUp(0)})}},A=0,R=4294967295,F=4294967295,U=(e=0,t=0)=>({x:e,y:t}),B=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),I=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),k=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),W=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function $(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const z=$("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),D=$("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),H=$("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),L=$("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),O={Static:0,Kinematic:1,Dynamic:2};let N=0;function j(e,t){const n=++N;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function X(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function V(e,t){const n=X(),s=n.get(e);if(s)return s;const r=j(e,t);return n.set(e,r),J(e,t,!1),r}function G(e){const t=X(),n=t.get(e);if(n)return n;const s=j(e,{});return t.set(e,s),J(e,{},!0),s}function Y(e){return X().get(e)}function q(){X().clear()}function J(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function K(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function Q(e){return!0===e._builtin}const Z=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}}),ee=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}}),te=K("Sprite",{texture:R,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}),ne=K("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),se=K("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),re=K("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),oe=K("Parent",{entity:0}),ie=K("Children",{entities:[]}),ae=K("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:F}),le=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}),ce={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},ue={LocalTransform:Z,WorldTransform:ee,Sprite:te,Camera:ne,Canvas:se,Velocity:re,Parent:oe,Children:ie,BitmapText:ae,SpineAnimation:le,RigidBody:z,BoxCollider:D,CircleCollider:H,CapsuleCollider:L};function de(e){const t=ue[e];if(t)return{...t._default};const n=Y(e);return n?{...n._default}:null}let he=0;function fe(e,t){const n=++he;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function pe(e){return{_type:"res",_resource:e}}function me(e){return{_type:"res_mut",_resource:e}}class ge{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}}class ye{constructor(){this.resources_=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)}getResMut(e){return new ge(this.get(e),t=>this.set(e,t))}}const _e=fe({delta:0,elapsed:0,frameCount:0},"Time");function we(e){return{_type:"mut",_component:e}}function xe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function be(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{xe(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class ve{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>xe(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with)}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),r=n.length,o=e.length>0,i=t.length>0,a=new Array(r+1);let l=null,c=[];try{for(const u of s){if(null!==l&&o){for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}c.length=0}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(u,t[n])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,n[e]);if(o){for(let t=0;t<e.length;t++){const s=e[t];c.push({component:n[s],data:a[s+1]})}l=u}yield a}}finally{if(null!==l&&o)for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,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 Se(){return{_type:"commands"}}class Pe{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 Ce{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Pe(this,null);return this.spawned_.push(e),e}entity(e){return new Pe(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_=[];for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}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":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Ee;!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"}(Ee||(Ee={}));let Te=0;function Me(e,t,n){const s=++Te;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Ae(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Re(e){Ae().push({schedule:Ee.Update,system:e})}function Fe(e){Ae().push({schedule:Ee.Startup,system:e})}function Ue(e,t){Ae().push({schedule:e,system:t})}class Be{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Ce&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new ve(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Ce(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ie{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const ke=fe(new Ie,"Input");class We{constructor(e){this.target_=e??null}build(e){const n=new Ie;e.insertResource(ke,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(Ee.Last,Me([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const $e=new We;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 De{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return 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)}remove(e,t){Q(t)?this.removeBuiltin(e,t):this.removeScript(e,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 r={...t._default,...s};if(this.cppRegistry_){const n=`add${t._cppName}`,s=this.cppRegistry_[n];s?.call(this.cppRegistry_,e,ze(r))}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const n=`get${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const n=`has${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const n=`remove${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e)}insertScript(e,t,n){const s=t.create(n);return this.getStorage(t).set(e,s),s}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)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();let t=null,n=1/0;for(const s of e)if(!Q(s)){const e=this.tsStorage_.get(s._id),r=e?e.size:0;r<n&&(n=r,t=e??null)}const s=[],r=t?t.keys():this.entities_;for(const t of r){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&s.push(t)}return s}}var He,Le,Oe;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(He||(He={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Le||(Le={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Oe||(Oe={}));const Ne=V("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:He.Left,verticalAlign:Le.Top,wordWrap:!0,overflow:Oe.Visible,lineHeight:1.2});class je{constructor(e){this.cache=new Map,this.module=e,this.canvas=d(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=r?Math.ceil(o):d+2*u,p=r?Math.ceil(i):h+2*u;if(r&&e.overflow===Oe.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${g}, ${y}, ${_})`,r&&e.overflow===Oe.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 Le.Top:x=u;break;case Le.Middle:x=(p-w)/2;break;case Le.Bottom:x=p-w-u;break;default:x=u}else x=u;let b=x;for(const t of l){let s;switch(e.align){case He.Left:s=u;break;case He.Center:s=f/2;break;case He.Right:s=f-u;break;default:s=u}n.fillText(t,s,b),b+=c}r&&e.overflow===Oe.Clip&&n.restore();const v=n.getImageData(0,0,f,p),S=new Uint8Array(v.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const E=P.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{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()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case He.Left:return"left";case He.Center:return"center";case He.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const Xe=V("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}});function Ve(e){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight}}function Ge(e,t){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight}class Ye{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new je(t),s=e.world,r=new Map;e.addSystemToSchedule(Ee.PreUpdate,Me([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Ne));for(const e of r.keys())s.valid(e)&&s.has(e,Ne)||r.delete(e);const e=s.getEntitiesWithComponents([Ne]);for(const t of e){const e=s.get(t,Ne),o=r.get(t);if(o&&!Ge(o,e))continue;s.has(t,te)||s.insert(t,te,{texture:R,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const i=s.has(t,Xe)?s.get(t,Xe):null,a=n.renderForEntity(t,e,i),l=s.get(t,te);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,te,l),r.set(t,Ve(e))}}))}}const qe=new Ye,Je=V("UIMask",{enabled:!0});function Ke(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 Qe(e,t,n,s,r,o,i,a,l,c,u){const d=e-n*r,h=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function m(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*u]}const[g,y]=m(d,f),[_,w]=m(h,p),x=Math.min(g,_),b=Math.max(g,_),v=Math.min(y,w),S=Math.max(y,w);return{x:Math.round(x),y:Math.round(v),w:Math.round(b-x),h:Math.round(S-v)}}function Ze(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],f=e[10],p=e[11],m=e[12],g=e[13],y=e[14],_=e[15],w=s*l-r*a,x=s*c-o*a,b=s*u-i*a,v=r*c-o*l,S=r*u-i*l,P=o*u-i*c,C=d*g-h*m,E=d*y-f*m,T=d*_-p*m,M=h*y-f*g,A=h*_-p*g,R=f*_-p*y;let F=w*R-x*A+b*M+v*T-S*E+P*C;return 0===F||(F=1/F,n[0]=(l*R-c*A+u*M)*F,n[1]=(o*A-r*R-i*M)*F,n[2]=(g*P-y*S+_*v)*F,n[3]=(f*S-h*P-p*v)*F,n[4]=(c*T-a*R-u*E)*F,n[5]=(s*R-o*T+i*E)*F,n[6]=(y*b-m*P-_*x)*F,n[7]=(d*P-f*b+p*x)*F,n[8]=(a*A-l*T+u*C)*F,n[9]=(r*T-s*A-i*C)*F,n[10]=(m*S-g*b+_*w)*F,n[11]=(h*b-d*S-p*w)*F,n[12]=(l*E-a*M-c*C)*F,n[13]=(s*M-r*E+o*C)*F,n[14]=(g*x-m*v-y*w)*F,n[15]=(d*v-h*x+f*w)*F),n}function et(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 tt(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 nt(e,t,n,s,r,o,i){if(!e.has(t,Xe)||!e.has(t,ee))return null;const a=e.get(t,Xe),l=e.get(t,ee),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return Qe(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function st(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Je]);if(0!==l.length)try{!function(e,t,n,s,r,o,i,a,l){const c=new Set;for(const e of s){t.get(e,Je).enabled&&c.add(e)}const u=[];for(const e of s){if(!c.has(e))continue;let n=!0,s=e;for(;t.has(s,oe);){const e=t.get(s,oe);if(c.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(c.has(n)){const e=nt(t,n,r,o,i,a,l);e&&(s=Ke(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=nt(t,e,r,o,i,a,l);n&&d(e,n)}}(e,t,n,l,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class rt{build(e){if(!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(st(e.wasmModule,e.world))}}const ot=new rt,it=V("Interactable",{enabled:!0}),at=V("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var lt;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(lt||(lt={}));const ct=V("Button",{state:lt.Normal,transition:null});class ut{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const dt=fe(new ut,"UIEvents"),ht=fe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo"),ft=new Float32Array(16);class pt{build(e){const t=e.world,n=new ut;e.insertResource(dt,n);let s=null,r=null;e.addSystemToSchedule(Ee.PreUpdate,Me([pe(ke),pe(ht)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([at]);for(const e of i){const n=t.get(e,at);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;Ze(o.viewProjection,ft);const u=et(l,c,ft,o.vpX,o.vpY,o.vpW,o.vpH),d=t.getEntitiesWithComponents([it,Xe,ee]);let h=null,f=-1/0;for(const e of d){t.has(e,at)||t.insert(e,at);if(!t.get(e,it).enabled)continue;const n=t.get(e,ee),s=t.get(e,Xe),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(tt(u.x,u.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y)){let n=0;t.has(e,te)&&(n=t.get(e,te).layer),n>=f&&(f=n,h=e)}}if(s!==h){if(null!==s&&t.valid(s)&&t.has(s,at)){t.get(s,at).hovered=!1,n.emit(s,"hover_exit")}if(null!==h){t.get(h,at).hovered=!0,n.emit(h,"hover_enter")}s=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,at);e.pressed=!0,e.justPressed=!0,r=h,n.emit(h,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,at)){const e=t.get(r,at);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Ee.Update,Me([],()=>{const e=t.getEntitiesWithComponents([ct]);for(const n of e){if(t.has(n,it)||t.insert(n,it,{enabled:!0}),!t.has(n,at))continue;const e=t.get(n,at),s=t.get(n,ct),r=t.get(n,it),o=s.state;if(r.enabled?e.pressed?s.state=lt.Pressed:e.hovered?s.state=lt.Hovered:s.state=lt.Normal:s.state=lt.Disabled,o!==s.state&&s.transition&&t.has(n,te)){const e=t.get(n,te),r=s.transition;switch(s.state){case lt.Normal:e.color={...r.normalColor};break;case lt.Hovered:e.color={...r.hoveredColor};break;case lt.Pressed:e.color={...r.pressedColor};break;case lt.Disabled:e.color={...r.disabledColor}}t.insert(n,te,e)}}},{name:"ButtonSystem"}))}}const mt=new pt,gt=G("ScreenSpace");function yt(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,f,p,m;if(l===c&&u===d){const e=l+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;h=e-s,f=t-o,p=e+s,m=t+o}else h=l+n.x,f=u+n.y,p=c+s.x,m=d+s.y;return{centerX:.5*(h+p),centerY:.5*(f+m),width:p-h,height:m-f,rect:{left:h,bottom:f,right:p,top:m}}}function _t(e,t,n,s,r,o){if(!e.has(t,Xe))return;const i=e.get(t,Xe),a=yt(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,Z);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,Z,l),!e.has(t,ie))return;const c=e.get(t,ie);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&_t(e,t,a.rect,a.centerX,a.centerY,!1)}class wt{build(e){const t=e.world;e.addSystemToSchedule(Ee.PreUpdate,Me([pe(ht)],e=>{if(!e.valid)return;const n={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(n.left+n.right),r=.5*(n.bottom+n.top),o=t.getEntitiesWithComponents([gt,Xe,Z]);for(const e of o)_t(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const xt=new wt,bt=V("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class vt{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=d(512,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,u=0;const h=function(){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}();function f(){if(null===i||!n.valid(i))return;const t=n.get(i,bt);if(t.readOnly)return;let s=h.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),h.value=s),s!==t.value){t.value=s;e.getResource(dt).emit(i,"change")}t.cursorPos=h.selectionStart??s.length,t.dirty=!0,g()}function p(e){if(i===e)return;m();const t=n.get(e,bt);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,h.value=t.value,h.selectionStart=t.cursorPos,h.selectionEnd=t.cursorPos,h.focus(),g())}function m(){if(null!==i&&n.valid(i)&&n.has(i,bt)){const e=n.get(i,bt);e.focused=!1,e.dirty=!0}i=null,h.blur()}function g(){l=!0,c=0}function y(e,i,a,c){(r.width<a||r.height<c)&&(r.width=Pt(Math.max(r.width,a)),r.height=Pt(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=St(o,h,a-2*m);let t=m;for(const n of e)o.fillText(n,m,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(h,m,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=St(o,i.value.substring(0,i.cursorPos),a-2*m),r=e.length>0?e[e.length-1]:"";t=m+o.measureText(r).width,n=m+(e.length-1)*p,s=p}else t=m+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const g=o.getImageData(0,0,a,c),y=new Uint8Array(g.data.buffer),_=t.getResourceManager(),w=t._malloc(y.length);t.HEAPU8.set(y,w);const x=s.get(e);void 0!==x&&_.releaseTexture(x);const b=_.createTexture(a,c,w,y.length,1,!0);s.set(e,b),t._free(w);const v=n.get(e,te);v.texture=b,v.size.x=a,v.size.y=c,v.uvOffset.x=0,v.uvOffset.y=0,v.uvScale.x=1,v.uvScale.y=1,v.color={r:1,g:1,b:1,a:1},n.insert(e,te,v)}h.addEventListener("input",()=>{a||null===i||f()}),h.addEventListener("compositionstart",()=>{a=!0}),h.addEventListener("compositionend",()=>{a=!1,f()}),h.addEventListener("keydown",t=>{if(null===i)return;if("Escape"===t.key)return void m();const s=n.get(i,bt);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(dt).emit(i,"submit"),void m()}let r=s.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?r=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=s.value.length),r!==s.cursorPos&&(s.cursorPos=r,h.selectionStart=r,h.selectionEnd=r,s.dirty=!0,g())}),h.addEventListener("blur",()=>{if(null!==i&&n.valid(i)&&n.has(i,bt)){const e=n.get(i,bt);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(Ee.PreUpdate,Me([pe(dt)],e=>{const t=n.getEntitiesWithComponents([bt,it]);for(const e of t){if(!n.has(e,at))continue;if(n.get(e,at).justPressed)return void p(e)}if(null!==i){const e=n.getEntitiesWithComponents([it]);for(const t of e){if(n.has(t,bt))continue;if(!n.has(t,at))continue;if(n.get(t,at).justPressed)return void m()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Ee.PreUpdate,Me([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,bt)))){n.get(i,bt).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,bt)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([bt,Xe]);for(const e of a){const t=n.get(e,bt);if(!t.dirty)continue;const s=n.get(e,Xe),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,te)||n.insert(e,te,{texture:R,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),y(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function St(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function Pt(e){let t=1;for(;t<e;)t*=2;return t}const Ct=new vt;var Et;function Tt(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"}(Et||(Et={}));let Mt=null,At=null,Rt=1;const Ft=new Map;function Ut(e){Mt=e,At=e.getResourceManager(),Ot()}function Bt(){0!==$t&&Mt&&(Mt._free($t),$t=0),Ft.clear(),Rt=1,Wt=!1,At=null,Mt=null}function It(){if(!At)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return At}const kt={createShader:(e,t)=>It().createShader(e,t),releaseShader(e){e>0&&It().releaseShader(e)},create(e){const t=Rt++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Et.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return Ft.set(t,n),t},get:e=>Ft.get(e),setUniform(e,t,n){const s=Ft.get(e);s&&s.uniforms.set(t,n)},getUniform(e,t){const n=Ft.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Ft.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Ft.get(e);return t?.blendMode??Et.Normal},setDepthTest(e,t){const n=Ft.get(e);n&&(n.depthTest=t)},getShader(e){const t=Ft.get(e);return t?.shader??0},release(e){Ft.delete(e)},isValid:e=>Ft.has(e),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??Et.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ft.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};return Ft.set(n,s),n},toAssetData(e,t){const n=Ft.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=Ft.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Wt=!1,$t=0;const zt=4096,Dt=new Map;let Ht=null;function Lt(e){const t=(0===$t&&Mt&&($t=Mt._malloc(zt)),$t);if(0===t||!Mt)return{ptr:0,count:0};let n=0,s=0;const r=Mt.HEAPU8,o=Mt.HEAPU32,i=Mt.HEAPF32;for(const[a,l]of e){if(n+128>zt)break;let e=Dt.get(a);e||(Ht||(Ht=new TextEncoder),e=Ht.encode(a),Dt.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 Ot(){if(!Mt||Wt)return;Mt.materialDataProvider=(e,t,n,s,r)=>{const o=Ft.get(e);if(!o)return Mt.HEAPU32[t>>2]=0,Mt.HEAPU32[n>>2]=0,Mt.HEAPU32[s>>2]=0,void(Mt.HEAPU32[r>>2]=0);Mt.HEAPU32[t>>2]=o.shader,Mt.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Lt(o.uniforms);Mt.HEAPU32[s>>2]=i,Mt.HEAPU32[r>>2]=a},Wt=!0}const Nt={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class jt{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const n=this.pending_.get(e);if(n)return n;const s=this.loadInternal(e);this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(kt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())kt.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:kt.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function Xt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,ce,{value:s.name}),!1!==s.visible)for(const n of s.components)Gt(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function Vt(e,t,n){const s=new Map,r=n?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();if(s.set(i.id,t),e.insert(t,ce,{value:i.name}),!1!==i.visible)for(const s of i.components){if("Sprite"===s.type&&r){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:n?.assetBaseUrl?`${n.assetBaseUrl}/${t}`:`/${t}`;try{const n=await r.loadTexture(s);e.texture=n.handle,o.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("BitmapText"===s.type&&r){const e=s.data;if("string"==typeof e.font&&e.font)try{const t=await r.loadBitmapFont(e.font,n?.assetBaseUrl);e.font=t}catch(t){console.warn(`Failed to load bitmap font: ${e.font}`,t),e.font=0}}if("SpineAnimation"===s.type&&r){const e=s.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await r.loadSpine(t,o,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Gt(e,t,s)}}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function Gt(e,t,n){const s=n.data;switch(n.type){case"LocalTransform":e.insert(t,Z,s);break;case"Sprite":e.insert(t,te,s);break;case"Camera":e.insert(t,ne,s);break;case"Canvas":e.insert(t,se,s);break;case"Text":e.insert(t,Ne,s);break;case"BitmapText":e.insert(t,ae,s);break;case"SpineAnimation":e.insert(t,le,s);break;case"UIRect":{const n=s;n.anchor&&!n.anchorMin&&(n.anchorMin={...n.anchor},n.anchorMax={...n.anchor},delete n.anchor),e.insert(t,Xe,n);break}case"UIMask":e.insert(t,Je,s);break;case"Interactable":e.insert(t,it,s);break;case"Button":e.insert(t,ct,s);break;case"RigidBody":e.insert(t,z,s);break;case"BoxCollider":e.insert(t,D,s);break;case"CircleCollider":e.insert(t,H,s);break;case"CapsuleCollider":e.insert(t,L,s);break;default:{const r=Y(n.type);r?e.insert(t,r,s):console.warn(`Unknown component type: ${n.type}`);break}}}function Yt(e,t){const n=e.getEntitiesWithComponents([ne]);for(const s of n){const n=e.get(s,ne);n&&(n.aspectRatio=t,e.insert(s,ne,n))}}function qt(e,t){const n=e.getEntitiesWithComponents([ce]);for(const s of n){const n=e.get(s,ce);if(n&&n.value===t)return s}return null}class Jt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const n=this.cache_.get(e);if(void 0!==n)return n;const s=this.pending_.get(e);if(s)return s;const r=t();this.pending_.set(e,r);try{const t=await r;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}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()}values(){return this.cache_.values()}}class Kt{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.module_=e,this.canvas_=d(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new jt(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);this.textureCache_.clear(),this.fontCache_.clear(),this.prefabCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.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)}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);for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,n),c=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);return this.writeToVirtualFS(e,c)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}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()=>e.endsWith(".bmfont")?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 Vt(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)}))}}return await Promise.all(n),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??n;return new Promise((n,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return kt.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 kt.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 Qt=fe(null,"Assets");class Zt{build(e){const t=e.wasmModule;t?e.insertResource(Qt,new Kt(t)):console.warn("AssetPlugin: No WASM module available")}}const en=new Zt;function tn(e,t){const n=e.getResource(Qt);n&&n.registerEmbeddedAssets(t)}async function nn(e,t,n){const{entities:s,rootId:r}=await sn(t,n?.overrides??[],n),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 Vt(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}async function sn(e,t,n,s){const r=new Map;let o;if(void 0===s){o=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),o=Math.max(o,t.prefabEntityId+1))}else{o=s;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,o++)}const i=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await sn(e,s.nestedPrefab.overrides,n,o);r.set(s.prefabEntityId,t.rootId),o=t.nextId;const a=t.entities.find(e=>e.id===t.rootId);a&&(a.parent=null!==s.parent?r.get(s.parent)??null:null),i.push(...t.entities);continue}const a=r.get(s.prefabEntityId),l=s.prefabEntityId===e.rootEntityId,c={id:a,prefabEntityId:s.prefabEntityId,name:s.name,parent:l?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};rn(c,t),i.push(c)}const a=r.get(e.rootEntityId);if(void 0===a)throw new Error("Failed to resolve prefab root entity");return{entities:i,rootId:a,nextId:o}}function rn(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 on{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,r=await this.assetServer_.loadPrefab(s,t?.baseUrl);return nn(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const an=fe(null,"Prefabs");class ln{build(e){const t=e.getResource(Qt);t?e.insertResource(an,new on(e.world,t)):console.warn("PrefabsPlugin: Assets resource not available")}}const cn=new ln;let un=null,dn=0,hn=0,fn=0;const pn=new Float32Array(256);function mn(e){un=e,dn=un._malloc(64),hn=un._malloc(64),fn=un._malloc(1024)}function gn(){un&&(dn&&(un._free(dn),dn=0),hn&&(un._free(hn),hn=0),fn&&(un._free(fn),fn=0)),un=null}function yn(){if(!un)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return un}const _n={r:1,g:1,b:1,a:1},wn={begin(e){const t=yn();t.HEAPF32.set(e,dn/4),t.draw_begin(dn)},end(){yn().draw_end()},line(e,t,n,s=1){yn().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rect(e,t,n,s=!0){yn().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rectOutline(e,t,n,s=1){yn().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},circle(e,t,n,s=!0,r=32){yn().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},circleOutline(e,t,n,s=1,r=32){yn().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=_n){yn().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)},textureRotated(e,t,n,s,r=_n){yn().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){yn().draw_setLayer(e)},setDepth(e){yn().draw_setDepth(e)},getDrawCallCount:()=>un?un.draw_getDrawCallCount():0,getPrimitiveCount:()=>un?un.draw_getPrimitiveCount():0,setBlendMode(e){yn().draw_setBlendMode(e)},setDepthTest(e){yn().draw_setDepthTest(e)},drawMesh(e,t,n){const s=yn();s.HEAPF32.set(n,hn/4),s.draw_mesh(e,t,hn)},drawMeshWithMaterial(e,t,n){const s=yn(),r=kt.get(t);if(!r)return;if(wn.setBlendMode(r.blendMode),wn.setDepthTest(r.depthTest),0===r.uniforms.size)return void wn.drawMesh(e,r.shader,n);s.HEAPF32.set(n,hn/4);let o=0,i=0;for(const[e,t]of r.uniforms){const n=bn(e);if(!(n<0)){if(Tt(t))pn[o++]=10,pn[o++]=n,pn[o++]=t.slot??i++,pn[o++]=t.textureId;else if("number"==typeof t)pn[o++]=1,pn[o++]=n,pn[o++]=t;else if(Array.isArray(t)){pn[o++]=t.length,pn[o++]=n;for(let e=0;e<t.length;e++)pn[o++]=t[e]}else"w"in t?(pn[o++]=4,pn[o++]=n,pn[o++]=t.x,pn[o++]=t.y,pn[o++]=t.z,pn[o++]=t.w):"z"in t?(pn[o++]=3,pn[o++]=n,pn[o++]=t.x,pn[o++]=t.y,pn[o++]=t.z):(pn[o++]=2,pn[o++]=n,pn[o++]=t.x,pn[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(pn.subarray(0,o),fn/4),s.draw_meshWithUniforms(e,r.shader,hn,fn,o)):s.draw_mesh(e,r.shader,hn)}},xn={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function bn(e){return xn[e]??-1}var vn;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(vn||(vn={}));let Sn=null,Pn=0,Cn=0,En=0;function Tn(e){Sn=e,Pn=Sn._malloc(262144),Cn=Sn._malloc(65536),En=Sn._malloc(256)}function Mn(){Sn&&(Pn&&Sn._free(Pn),Cn&&Sn._free(Cn),En&&Sn._free(En),Pn=0,Cn=0,En=0),Sn=null}function An(){if(!Sn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Sn}const Rn={create(e){const t=An(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,Pn/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,En,r).set(o),t.geometry_init(n,Pn,s,En,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,Cn,s).set(e.indices),t.geometry_setIndices16(n,Cn,s)}else{new Uint32Array(t.HEAPU8.buffer,Cn,s).set(e.indices),t.geometry_setIndices32(n,Cn,s)}}return n},updateVertices(e,t,n=0){const s=An(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,Pn/4),s.geometry_updateVertices(e,Pn,r,n)},release(e){e>0&&An().geometry_release(e)},isValid:e=>!(!Sn||e<=0)&&Sn.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Rn.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:vn.Float2},{name:"a_texCoord",type:vn.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 Rn.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:vn.Float2},{name:"a_texCoord",type:vn.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 Rn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:vn.Float2},{name:"a_texCoord",type:vn.Float2}],indices:new Uint16Array(i)})}};let Fn=null;function Un(e){Fn=e}function Bn(){Fn&&kn.isInitialized()&&kn.shutdown(),Fn=null}function In(){if(!Fn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Fn}const kn={init:(e,t)=>In().postprocess_init(e,t),shutdown(){In().postprocess_shutdown()},resize(e,t){In().postprocess_resize(e,t)},addPass:(e,t)=>In().postprocess_addPass(e,t),removePass(e){In().postprocess_removePass(e)},setEnabled(e,t){In().postprocess_setPassEnabled(e,t)},isEnabled:e=>In().postprocess_isPassEnabled(e),setUniform(e,t,n){In().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){In().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){In().postprocess_begin()},end(){In().postprocess_end()},getPassCount:()=>In().postprocess_getPassCount(),isInitialized:()=>!!Fn&&Fn.postprocess_isInitialized(),setBypass(e){In().postprocess_setBypass(e)},isBypassed:()=>!Fn||Fn.postprocess_isBypassed(),createBlur:()=>kt.createShader(Wn,"#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:()=>kt.createShader(Wn,"#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:()=>kt.createShader(Wn,"#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:()=>kt.createShader(Wn,"#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")},Wn="#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 $n;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}($n||($n={}));let zn=null,Dn=0;function Hn(e){zn=e,Dn=zn._malloc(64)}function Ln(){zn&&Dn&&(zn._free(Dn),Dn=0),zn=null}const On={init(e,t){zn?.renderer_init(e,t)},resize(e,t){zn?.renderer_resize(e,t)},begin(e,t){zn&&Dn&&(zn.HEAPF32.set(e,Dn/4),zn.renderer_begin(Dn,t??0))},flush(){zn?.renderer_flush()},end(){zn?.renderer_end()},submitSprites(e){zn&&zn.renderer_submitSprites(e._cpp)},submitBitmapText(e){zn&&zn.renderer_submitBitmapText(e._cpp)},submitSpine(e){zn&&zn.renderer_submitSpine?.(e._cpp)},setStage(e){zn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>zn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){zn?.renderer_releaseTarget(e)},getTargetTexture:e=>zn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>zn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){zn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){zn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){zn?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){zn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>zn?zn.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>zn?{drawCalls:zn.renderer_getDrawCalls(),triangles:zn.renderer_getTriangles(),sprites:zn.renderer_getSprites(),text:zn.renderer_getText(),spine:zn.renderer_getSpine?.()??0,meshes:zn.renderer_getMeshes(),culled:zn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Nn=null;function jn(e){Nn=e}function Xn(){Nn=null}const Vn={enable(){Nn?.gl_enableErrorCheck(!0)},disable(){Nn?.gl_enableErrorCheck(!1)},check:e=>Nn?.gl_checkErrors(e)??0,diagnose(){Nn?.renderer_diagnose()}},Gn=new Map;function Yn(e,t){Gn.set(e,t)}function qn(e){Gn.delete(e)}function Jn(){Gn.clear()}class Kn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(On.resize(s,r),kn.isInitialized()&&kn.getPassCount()>0&&kn.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),On.setViewport(0,0,s,r),On.clearBuffers(3),On.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),On.submitSprites(t),On.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):On.submitSpine(t),On.flush(),this.executeDrawCallbacks(n,o),On.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;On.setViewport(s.x,s.y,s.w,s.h),On.setScissor(s.x,s.y,s.w,s.h,!0),On.clearBuffers(r),On.setScissor(0,0,0,0,!1),On.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),On.submitSprites(t),On.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):On.submitSpine(t),On.flush(),this.executeDrawCallbacks(n,o),On.end()}executeDrawCallbacks(e,t){const n=Gn;if(n.size>0){wn.begin(e);const s=[];for(const[e,r]of n.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}wn.end();for(const e of s)qn(e)}}}class Qn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=h(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.runSchedule(Ee.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Ee.FixedPreUpdate),this.runSchedule(Ee.FixedUpdate),this.runSchedule(Ee.FixedPostUpdate);this.runSchedule(Ee.PreUpdate),this.runSchedule(Ee.Update),this.runSchedule(Ee.PostUpdate),this.runSchedule(Ee.Last),requestAnimationFrame(this.mainLoop)},this.world_=new De,this.resources_=new ye;for(const e of Object.values(Ee))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Qn}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(Ee.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Ee.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new Be(this.world_,this.resources_),this.resources_.insert(_e,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Ee.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1,Xn(),Ln(),Bn(),Mn(),Bt(),gn()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(_e);t.delta=e,t.elapsed+=e,t.frameCount++}}function Zn(e,t){const n=Qn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),mn(e),Ut(e),Tn(e),Un(e),Hn(e),jn(e);const r=new Kn;n.pipeline_=r;let o=h();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r){const o=ss(e,s,t,r),i=n.getResource(ht);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(ht,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=i();if(0===t||0===n)return;const l=e.registry_getCanvasEntity(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;On.setClearColor(e.x,e.y,e.z,e.w)}const c=(h()-o)/1e3;On.resize(t,n),kn.isInitialized()&&kn.getPassCount()>0&&!kn.isBypassed()&&kn.resize(t,n);const u=ss(e,s,t,n);if(a(t,n),0===u.length)r.render({registry:{_cpp:s},viewProjection:ts,width:t,height:n,elapsed:c});else{for(const e of u){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*n),l=Math.round(o.w*t),u=Math.round(o.h*n);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}On.setViewport(0,0,t,n)}}};return n.addSystemToSchedule(Ee.First,l),n.addSystemToSchedule(Ee.Last,c),n.addPlugin(en),n.addPlugin(cn),n.addPlugin($e),n.addPlugin(qe),n.addPlugin(ot),n.addPlugin(xt),n.addPlugin(mt),n.addPlugin(Ct),n}function es(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 ts=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ns(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}}}function ss(e,t,n,s){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*n/(l.h*s);let u,d=0,h=0;if(1===r.projectionType){if(h=r.orthoSize,o){h=ns(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=os(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=as(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=cs(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:us(u,f),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const rs=new Float32Array(16);function os(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 as(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 ls=new Float32Array(16);function cs(e,t,n){const s=ls;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}function us(e,t){const n=new Float32Array(16);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}async function ds(e,t){if(t)return t();return(0,(await import(e)).default)()}const hs=fe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),fs=fe(null,"PhysicsAPI");function ps(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function ms(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class gs{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(hs,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=ds(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([se]);for(const n of t){const t=e.world.get(n,se);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(Ee.PostUpdate,Me([pe(_e)],a=>{const l=i.getEntitiesWithComponents([z,Z,ee]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,z),l=i.get(r,ee);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=ps(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),ys(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===O.Kinematic){const e=ps(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,Z);if(!u)continue;let d=a,h=l,f=c;if(e.world.has(i,oe)){const t=e.world.get(i,oe);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ee)){const n=e.world.get(t.entity,ee),s=ps(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=ms(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,Z,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(hs,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.__physicsModule=s,e.insertResource(fs,_s._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=s}}function ys(e,t,n){const s=e.world;if(s.has(n,D)){const e=s.get(n,D);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,H)){const e=s.get(n,H);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,L)){const e=s.get(n,L);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 _s{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(_s.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 ws(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 xs(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 bs(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,f=c+c,p=a*d,m=a*h,g=a*f,y=l*h,_=l*f,w=c*f,x=u*d,b=u*h,v=u*f;return new Float32Array([(1-(y+w))*r,(m+v)*r,(g-b)*r,0,(m-v)*o,(1-(p+w))*o,(_+x)*o,0,(g+b)*i,(_-x)*i,(1-(p+y))*i,0,e.position.x,e.position.y,e.position.z,1])}async function vs(e,t,n,s,r,o,i,a){const l=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=ws(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,l);let c={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),c=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=r.readText(a),u=l.endsWith(".skel");let d,h;if(u){const e=r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=r.readText(i),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const f=n.loadSkeleton(d,h,s,s.length,u);if(t._free(d),f<0)continue;o[i]=f;const p=xs(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=ws(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,n,s)),o){new gs("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;if(r.endsWith(".bmfont")){const e=JSON.parse(n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const i=t.match(/file="([^"]+)"/);if(!i){s[r]=0;continue}const a=o?`${o}/${i[1]}`:i[1],l=n.loadPixelsRaw?await n.loadPixelsRaw(a):await n.loadPixels(a),c=ws(e,l,!1),u=e.getResourceManager();s[r]=u.loadBitmapFont(t,c,l.width,l.height)}catch{s[r]=0}}return s}(t,n,s),h=function(e,t){const n={},s={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===n[r])try{const e=JSON.parse(t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=kt.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=kt.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),f=Xt(e.world,n);if(function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const r=e.get(t,te);r&&(r.texture=n[s.data.texture]||0,e.insert(t,te,r))}}}(e.world,n,l,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if("BitmapText"!==s.type||!s.data.font||"string"!=typeof s.data.font)continue;const r=n[s.data.font]||0;if(!r)continue;const o=e.get(t,ae);o&&(o.font=r,e.insert(t,ae,o))}}}(e.world,n,d,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const r=n[s.data.material]||0;if(r)if("Sprite"===s.type){const n=e.get(t,te);n&&(n.material=r,e.insert(t,te,n))}else if("SpineAnimation"===s.type){const n=e.get(t,le);n&&(n.material=r,e.insert(t,le,n))}}}}(e.world,n,h,f),r&&u){const s=function(e,t,n,s){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,n,c,f);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,le)?c.get(o,le):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(i,l*d);let h=0;if(c.has(o,ee)){const e=bs(c.get(o,ee),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,d,f);const p=n.HEAPU32[d>>2],m=n.HEAPU32[f>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*r),y=new Uint16Array(n.HEAPU8.buffer,u,o),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,_>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(y),t.renderer_submitTriangles(_,r,w,o,p,m,h),t._free(_),t._free(w),n._free(c),n._free(u),n._free(d),n._free(f)}h&&t._free(h)}})}(e,t,r,u,s)}if(a){const t=e.getResource(Qt);t&&t.setAddressableManifest(a)}}class Ss{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&(s.endsWith(".skel")?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));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(()=>{}));await Promise.all(r);const o=[];for(const e of s){if(!e.endsWith(".bmfont"))continue;const t=this.textCache_.get(e);if(t)try{const n=JSON.parse(t),s="label-atlas"===n.type?n.generatedFnt:n.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(()=>{}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class Ps{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(!this.app_)return;let e="fetch scene";try{const t=await i(this.sceneUrl_);if(!t.ok)throw new Error(`Failed to fetch scene: ${t.status}`);e="parse scene JSON";const n=await t.json();e="prefetch assets";const s=new Ss(this.baseUrl_);await s.prefetch(n);let r=null;const o=this.app_.__spineInitPromise;if(o){e="init spine";r=(await o).controller.raw}e="loadRuntimeScene",await vs(this.app_,this.app_.wasmModule,n,s,r),e="ensureCamera",this.ensureCamera()}catch(t){const n=t instanceof Error?t.message:String(t),s=t instanceof Error?t.stack:"";throw console.error(`[PreviewPlugin] Failed at step "${e}": ${n}\n${s}`),new Error(`[PreviewPlugin:${e}] ${n}`)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([ne]);for(const s of n){if(e.get(s,ne).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const s=e.getEntitiesWithComponents([se]);for(const r of s){const s=e.get(r,se);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,Z,o);const i={isActive:!0,projectionType:1,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3};e.insert(r,ne,i)}}}const Cs={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=On.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:On.getTargetTexture(n),width:e.width,height:e.height}},release(e){On.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(On.releaseRenderTarget(e._handle),Cs.create({width:t,height:n,depth:!0})),begin(e,t){On.begin(t,e._handle)},end(){On.end()},getDepthTexture:e=>On.getTargetDepthTexture(e._handle)};let Es=!1;function Ts(e){Es=e}function Ms(){return Es}function As(){return!Es}T||(T=!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=M;export{Qn as App,Zt as AssetPlugin,Kt as AssetServer,Qt as Assets,Jt as AsyncCache,ae as BitmapText,Et as BlendMode,O as BodyType,D as BoxCollider,ct as Button,lt as ButtonState,ne as Camera,se as Canvas,L as CapsuleCollider,ie as Children,H as CircleCollider,Se as Commands,Ce as CommandsInstance,vn as DataType,wn as Draw,Pe as EntityCommands,Vn as GLDebug,Rn as Geometry,A as INVALID_ENTITY,F as INVALID_FONT,R as INVALID_TEXTURE,ke as Input,We as InputPlugin,Ie as InputState,it as Interactable,Z as LocalTransform,kt as Material,jt as MaterialLoader,we as Mut,ce as Name,oe as Parent,_s as Physics,hs as PhysicsEvents,gs as PhysicsPlugin,kn as PostProcess,on as PrefabServer,an as Prefabs,ln as PrefabsPlugin,Ps as PreviewPlugin,be as Query,ve as QueryInstance,Kn as RenderPipeline,$n as RenderStage,Cs as RenderTexture,On as Renderer,pe as Res,me as ResMut,z as RigidBody,Ee as Schedule,gt as ScreenSpace,Nt as ShaderSources,le as SpineAnimation,te as Sprite,Be as SystemRunner,Ne as Text,He as TextAlign,bt as TextInput,vt as TextInputPlugin,Oe as TextOverflow,Ye as TextPlugin,je as TextRenderer,Le as TextVerticalAlign,_e as Time,ht as UICameraInfo,ut as UIEventQueue,dt as UIEvents,at as UIInteraction,pt as UIInteractionPlugin,wt as UILayoutPlugin,Je as UIMask,rt as UIMaskPlugin,Xe as UIRect,re as Velocity,Ss as WebAssetProvider,De as World,ee as WorldTransform,Fe as addStartupSystem,Re as addSystem,Ue as addSystemToSchedule,en as assetPlugin,Jn as clearDrawCallbacks,q as clearUserComponents,k as color,yt as computeUIRectLayout,st as createMaskProcessor,Zn as createWebApp,V as defineComponent,fe as defineResource,Me as defineSystem,G as defineTag,qt as findEntityByName,es as flushPendingSystems,de as getComponentDefaults,t as getPlatform,s as getPlatformType,Y as getUserComponent,mn as initDrawAPI,jn as initGLDebugAPI,Tn as initGeometryAPI,Ut as initMaterialAPI,Un as initPostProcessAPI,Hn as initRendererAPI,$e as inputPlugin,nn as instantiatePrefab,Ke as intersectRects,Ze as invertMatrix4,Q as isBuiltinComponent,Ms as isEditor,n as isPlatformInitialized,As as isRuntime,Tt as isTextureRef,r as isWeChat,o as isWeb,Gt as loadComponent,ds as loadPhysicsModule,vs as loadRuntimeScene,Xt as loadSceneData,Vt as loadSceneWithAssets,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,tt as pointInWorldRect,cn as prefabsPlugin,W as quat,Yn as registerDrawCallback,tn as registerEmbeddedAssets,Ot as registerMaterialCallback,et as screenToWorld,Ts as setEditorMode,gn as shutdownDrawAPI,Xn as shutdownGLDebugAPI,Mn as shutdownGeometryAPI,Bt as shutdownMaterialAPI,Bn as shutdownPostProcessAPI,Ln as shutdownRendererAPI,Ct as textInputPlugin,qe as textPlugin,mt as uiInteractionPlugin,xt as uiLayoutPlugin,ot as uiMaskPlugin,qn as unregisterDrawCallback,Yt as updateCameraAspectRatio,U as vec2,B as vec3,I as vec4,Qe as worldRectToScreen,w as wxFileExists,x as wxFileExistsSync,C as wxGetImagePixels,P as wxLoadImage,E as wxLoadImagePixels,y as wxReadFile,_ as wxReadTextFile,b as wxWriteFile};
//# sourceMappingURL=index.wechat.js.map
diff --git a/desktop/public/sdk/esm/esengine.d.ts b/desktop/public/sdk/esm/esengine.d.ts
index 13cec59b1..4bfa30ffe 100644
--- a/desktop/public/sdk/esm/esengine.d.ts
+++ b/desktop/public/sdk/esm/esengine.d.ts
@@ -1541,6 +1541,7 @@ declare class AssetServer {
loadScene(world: World, sceneData: SceneData): Promise<Map<number, Entity>>;
loadAll(manifest: AddressableManifest): Promise<AssetBundle>;
setAddressableManifest(manifest: AddressableManifest): void;
+ resolveAddress(address: string): AddressableManifestAsset | undefined;
load<T extends AddressableAssetType = AddressableAssetType>(address: string): Promise<AddressableResultMap[T]>;
loadByLabel(label: string): Promise<AssetBundle>;
loadGroup(groupName: string): Promise<AssetBundle>;
@@ -1600,7 +1601,7 @@ declare class PrefabServer {
private readonly world_;
private readonly assetServer_;
constructor(world: World, assetServer: AssetServer);
- instantiate(path: string, options?: {
+ instantiate(pathOrAddress: string, options?: {
baseUrl?: string;
parent?: Entity;
overrides?: PrefabOverride[];
diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.js
index 7b1dca3e8..cb88cc417 100644
--- a/desktop/public/sdk/esm/esengine.js
+++ b/desktop/public/sdk/esm/esengine.js
@@ -1,2 +1,2 @@
-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function d(e,n){return t().createCanvas(e,n)}function h(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.module}}createImage(){return new Image}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),r=t=>e.onKeyUp(t.code),o=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},i=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},u=()=>{e.onPointerUp(0)},d=t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)};document.addEventListener("keydown",s),document.addEventListener("keyup",r),n.addEventListener("mousemove",o),n.addEventListener("mousedown",i),n.addEventListener("mouseup",a),n.addEventListener("touchstart",l),n.addEventListener("touchmove",c),n.addEventListener("touchend",u),n.addEventListener("wheel",d),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",r),n.removeEventListener("mousemove",o),n.removeEventListener("mousedown",i),n.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",u),n.removeEventListener("wheel",d)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=0,m=4294967295,g=4294967295,_=(e=0,t=0)=>({x:e,y:t}),y=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),w=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),x=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),v=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function b(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const S=b("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),P=b("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),C=b("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),E=b("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),M={Static:0,Kinematic:1,Dynamic:2};let T=0;function A(e,t){const n=++T;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function R(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function F(e,t){const n=R(),s=n.get(e);if(s)return s;const r=A(e,t);return n.set(e,r),k(e,t,!1),r}function U(e){const t=R(),n=t.get(e);if(n)return n;const s=A(e,{});return t.set(e,s),k(e,{},!0),s}function B(e){return R().get(e)}function I(){R().clear()}function k(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function $(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function z(e){return!0===e._builtin}const L=$("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),D=$("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),H=$("Sprite",{texture:m,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}),W=$("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),O=$("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),N=$("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),j=$("Parent",{entity:0}),X=$("Children",{entities:[]}),V=$("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:g}),Y=$("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}),G={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},q={LocalTransform:L,WorldTransform:D,Sprite:H,Camera:W,Canvas:O,Velocity:N,Parent:j,Children:X,BitmapText:V,SpineAnimation:Y,RigidBody:S,BoxCollider:P,CircleCollider:C,CapsuleCollider:E};function J(e){const t=q[e];if(t)return{...t._default};const n=B(e);return n?{...n._default}:null}let K=0;function Q(e,t){const n=++K;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function Z(e){return{_type:"res",_resource:e}}function ee(e){return{_type:"res_mut",_resource:e}}class te{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}}class ne{constructor(){this.resources_=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)}getResMut(e){return new te(this.get(e),t=>this.set(e,t))}}const se=Q({delta:0,elapsed:0,frameCount:0},"Time");function re(e){return{_type:"mut",_component:e}}function oe(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)=>{oe(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class ae{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>oe(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with)}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),r=n.length,o=e.length>0,i=t.length>0,a=new Array(r+1);let l=null,c=[];try{for(const u of s){if(null!==l&&o){for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}c.length=0}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(u,t[n])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,n[e]);if(o){for(let t=0;t<e.length;t++){const s=e[t];c.push({component:n[s],data:a[s+1]})}l=u}yield a}}finally{if(null!==l&&o)for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,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 le(){return{_type:"commands"}}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 n;return n=z(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class ue{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,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_=[];for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}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":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var de;!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"}(de||(de={}));let he=0;function fe(e,t,n){const s=++he;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function pe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function me(e){pe().push({schedule:de.Update,system:e})}function ge(e){pe().push({schedule:de.Startup,system:e})}function _e(e,t){pe().push({schedule:e,system:t})}class ye{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof ue&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new ae(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new ue(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class we{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=Q(new we,"Input");class ve{constructor(e){this.target_=e??null}build(e){const n=new we;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(de.Last,fe([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const be=new ve;function Se(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}:Se(e)}}return t}class Pe{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return z(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return z(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return z(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){z(t)?this.removeBuiltin(e,t):this.removeScript(e,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 r={...t._default,...s};if(this.cppRegistry_){const n=`add${t._cppName}`,s=this.cppRegistry_[n];s?.call(this.cppRegistry_,e,Se(r))}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const n=`get${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const n=`has${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const n=`remove${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e)}insertScript(e,t,n){const s=t.create(n);return this.getStorage(t).set(e,s),s}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)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();let t=null,n=1/0;for(const s of e)if(!z(s)){const e=this.tsStorage_.get(s._id),r=e?e.size:0;r<n&&(n=r,t=e??null)}const s=[],r=t?t.keys():this.entities_;for(const t of r){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&s.push(t)}return s}}var Ce,Ee,Me;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Ce||(Ce={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Ee||(Ee={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Me||(Me={}));const Te=F("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Ce.Left,verticalAlign:Ee.Top,wordWrap:!0,overflow:Me.Visible,lineHeight:1.2});class Ae{constructor(e){this.cache=new Map,this.module=e,this.canvas=d(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=r?Math.ceil(o):d+2*u,p=r?Math.ceil(i):h+2*u;if(r&&e.overflow===Me.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),_=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${g}, ${_}, ${y})`,r&&e.overflow===Me.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 Ee.Top:x=u;break;case Ee.Middle:x=(p-w)/2;break;case Ee.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 Ce.Left:s=u;break;case Ce.Center:s=f/2;break;case Ce.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=c}r&&e.overflow===Me.Clip&&n.restore();const b=n.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const E=P.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{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()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case Ce.Left:return"left";case Ce.Center:return"center";case Ce.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const Re=F("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}});function Fe(e){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight}}function Ue(e,t){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight}class Be{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Ae(t),s=e.world,r=new Map;e.addSystemToSchedule(de.PreUpdate,fe([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Te));for(const e of r.keys())s.valid(e)&&s.has(e,Te)||r.delete(e);const e=s.getEntitiesWithComponents([Te]);for(const t of e){const e=s.get(t,Te),o=r.get(t);if(o&&!Ue(o,e))continue;s.has(t,H)||s.insert(t,H,{texture:m,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const i=s.has(t,Re)?s.get(t,Re):null,a=n.renderForEntity(t,e,i),l=s.get(t,H);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,H,l),r.set(t,Fe(e))}}))}}const Ie=new Be,ke=F("UIMask",{enabled:!0});function $e(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 ze(e,t,n,s,r,o,i,a,l,c,u){const d=e-n*r,h=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function m(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*u]}const[g,_]=m(d,f),[y,w]=m(h,p),x=Math.min(g,y),v=Math.max(g,y),b=Math.min(_,w),S=Math.max(_,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function Le(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],f=e[10],p=e[11],m=e[12],g=e[13],_=e[14],y=e[15],w=s*l-r*a,x=s*c-o*a,v=s*u-i*a,b=r*c-o*l,S=r*u-i*l,P=o*u-i*c,C=d*g-h*m,E=d*_-f*m,M=d*y-p*m,T=h*_-f*g,A=h*y-p*g,R=f*y-p*_;let F=w*R-x*A+v*T+b*M-S*E+P*C;return 0===F||(F=1/F,n[0]=(l*R-c*A+u*T)*F,n[1]=(o*A-r*R-i*T)*F,n[2]=(g*P-_*S+y*b)*F,n[3]=(f*S-h*P-p*b)*F,n[4]=(c*M-a*R-u*E)*F,n[5]=(s*R-o*M+i*E)*F,n[6]=(_*v-m*P-y*x)*F,n[7]=(d*P-f*v+p*x)*F,n[8]=(a*A-l*M+u*C)*F,n[9]=(r*M-s*A-i*C)*F,n[10]=(m*S-g*v+y*w)*F,n[11]=(h*v-d*S-p*w)*F,n[12]=(l*E-a*T-c*C)*F,n[13]=(s*T-r*E+o*C)*F,n[14]=(g*x-m*b-_*w)*F,n[15]=(d*b-h*x+f*w)*F),n}function De(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 He(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 We(e,t,n,s,r,o,i){if(!e.has(t,Re)||!e.has(t,D))return null;const a=e.get(t,Re),l=e.get(t,D),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return ze(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function Oe(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([ke]);if(0!==l.length)try{!function(e,t,n,s,r,o,i,a,l){const c=new Set;for(const e of s){t.get(e,ke).enabled&&c.add(e)}const u=[];for(const e of s){if(!c.has(e))continue;let n=!0,s=e;for(;t.has(s,j);){const e=t.get(s,j);if(c.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(c.has(n)){const e=We(t,n,r,o,i,a,l);e&&(s=$e(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=We(t,e,r,o,i,a,l);n&&d(e,n)}}(e,t,n,l,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class Ne{build(e){if(!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Oe(e.wasmModule,e.world))}}const je=new Ne,Xe=F("Interactable",{enabled:!0}),Ve=F("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Ye;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Ye||(Ye={}));const Ge=F("Button",{state:Ye.Normal,transition:null});class qe{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const Je=Q(new qe,"UIEvents"),Ke=Q({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo"),Qe=new Float32Array(16);class Ze{build(e){const t=e.world,n=new qe;e.insertResource(Je,n);let s=null,r=null;e.addSystemToSchedule(de.PreUpdate,fe([Z(xe),Z(Ke)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([Ve]);for(const e of i){const n=t.get(e,Ve);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;Le(o.viewProjection,Qe);const u=De(l,c,Qe,o.vpX,o.vpY,o.vpW,o.vpH),d=t.getEntitiesWithComponents([Xe,Re,D]);let h=null,f=-1/0;for(const e of d){t.has(e,Ve)||t.insert(e,Ve);if(!t.get(e,Xe).enabled)continue;const n=t.get(e,D),s=t.get(e,Re),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(He(u.x,u.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y)){let n=0;t.has(e,H)&&(n=t.get(e,H).layer),n>=f&&(f=n,h=e)}}if(s!==h){if(null!==s&&t.valid(s)&&t.has(s,Ve)){t.get(s,Ve).hovered=!1,n.emit(s,"hover_exit")}if(null!==h){t.get(h,Ve).hovered=!0,n.emit(h,"hover_enter")}s=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,Ve);e.pressed=!0,e.justPressed=!0,r=h,n.emit(h,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Ve)){const e=t.get(r,Ve);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(de.Update,fe([],()=>{const e=t.getEntitiesWithComponents([Ge]);for(const n of e){if(t.has(n,Xe)||t.insert(n,Xe,{enabled:!0}),!t.has(n,Ve))continue;const e=t.get(n,Ve),s=t.get(n,Ge),r=t.get(n,Xe),o=s.state;if(r.enabled?e.pressed?s.state=Ye.Pressed:e.hovered?s.state=Ye.Hovered:s.state=Ye.Normal:s.state=Ye.Disabled,o!==s.state&&s.transition&&t.has(n,H)){const e=t.get(n,H),r=s.transition;switch(s.state){case Ye.Normal:e.color={...r.normalColor};break;case Ye.Hovered:e.color={...r.hoveredColor};break;case Ye.Pressed:e.color={...r.pressedColor};break;case Ye.Disabled:e.color={...r.disabledColor}}t.insert(n,H,e)}}},{name:"ButtonSystem"}))}}const et=new Ze,tt=U("ScreenSpace");function nt(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,f,p,m;if(l===c&&u===d){const e=l+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;h=e-s,f=t-o,p=e+s,m=t+o}else h=l+n.x,f=u+n.y,p=c+s.x,m=d+s.y;return{centerX:.5*(h+p),centerY:.5*(f+m),width:p-h,height:m-f,rect:{left:h,bottom:f,right:p,top:m}}}function st(e,t,n,s,r,o){if(!e.has(t,Re))return;const i=e.get(t,Re),a=nt(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,L);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,L,l),!e.has(t,X))return;const c=e.get(t,X);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&st(e,t,a.rect,a.centerX,a.centerY,!1)}class rt{build(e){const t=e.world;e.addSystemToSchedule(de.PreUpdate,fe([Z(Ke)],e=>{if(!e.valid)return;const n={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(n.left+n.right),r=.5*(n.bottom+n.top),o=t.getEntitiesWithComponents([tt,Re,L]);for(const e of o)st(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const ot=new rt,it=F("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class at{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=d(512,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,u=0;const h=function(){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}();function f(){if(null===i||!n.valid(i))return;const t=n.get(i,it);if(t.readOnly)return;let s=h.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),h.value=s),s!==t.value){t.value=s;e.getResource(Je).emit(i,"change")}t.cursorPos=h.selectionStart??s.length,t.dirty=!0,_()}function p(e){if(i===e)return;g();const t=n.get(e,it);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,h.value=t.value,h.selectionStart=t.cursorPos,h.selectionEnd=t.cursorPos,h.focus(),_())}function g(){if(null!==i&&n.valid(i)&&n.has(i,it)){const e=n.get(i,it);e.focused=!1,e.dirty=!0}i=null,h.blur()}function _(){l=!0,c=0}function y(e,i,a,c){(r.width<a||r.height<c)&&(r.width=ct(Math.max(r.width,a)),r.height=ct(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=lt(o,h,a-2*m);let t=m;for(const n of e)o.fillText(n,m,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(h,m,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=lt(o,i.value.substring(0,i.cursorPos),a-2*m),r=e.length>0?e[e.length-1]:"";t=m+o.measureText(r).width,n=m+(e.length-1)*p,s=p}else t=m+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const g=o.getImageData(0,0,a,c),_=new Uint8Array(g.data.buffer),y=t.getResourceManager(),w=t._malloc(_.length);t.HEAPU8.set(_,w);const x=s.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,c,w,_.length,1,!0);s.set(e,v),t._free(w);const b=n.get(e,H);b.texture=v,b.size.x=a,b.size.y=c,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},n.insert(e,H,b)}h.addEventListener("input",()=>{a||null===i||f()}),h.addEventListener("compositionstart",()=>{a=!0}),h.addEventListener("compositionend",()=>{a=!1,f()}),h.addEventListener("keydown",t=>{if(null===i)return;if("Escape"===t.key)return void g();const s=n.get(i,it);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(Je).emit(i,"submit"),void g()}let r=s.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?r=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=s.value.length),r!==s.cursorPos&&(s.cursorPos=r,h.selectionStart=r,h.selectionEnd=r,s.dirty=!0,_())}),h.addEventListener("blur",()=>{if(null!==i&&n.valid(i)&&n.has(i,it)){const e=n.get(i,it);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(de.PreUpdate,fe([Z(Je)],e=>{const t=n.getEntitiesWithComponents([it,Xe]);for(const e of t){if(!n.has(e,Ve))continue;if(n.get(e,Ve).justPressed)return void p(e)}if(null!==i){const e=n.getEntitiesWithComponents([Xe]);for(const t of e){if(n.has(t,it))continue;if(!n.has(t,Ve))continue;if(n.get(t,Ve).justPressed)return void g()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(de.PreUpdate,fe([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,it)))){n.get(i,it).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,it)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([it,Re]);for(const e of a){const t=n.get(e,it);if(!t.dirty)continue;const s=n.get(e,Re),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,H)||n.insert(e,H,{texture:m,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),y(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function lt(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function ct(e){let t=1;for(;t<e;)t*=2;return t}const ut=new at;var dt;function ht(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"}(dt||(dt={}));let ft=null,pt=null,mt=1;const gt=new Map;function _t(e){ft=e,pt=e.getResourceManager(),Mt()}function yt(){0!==bt&&ft&&(ft._free(bt),bt=0),gt.clear(),mt=1,vt=!1,pt=null,ft=null}function wt(){if(!pt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return pt}const xt={createShader:(e,t)=>wt().createShader(e,t),releaseShader(e){e>0&&wt().releaseShader(e)},create(e){const t=mt++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??dt.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return gt.set(t,n),t},get:e=>gt.get(e),setUniform(e,t,n){const s=gt.get(e);s&&s.uniforms.set(t,n)},getUniform(e,t){const n=gt.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=gt.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=gt.get(e);return t?.blendMode??dt.Normal},setDepthTest(e,t){const n=gt.get(e);n&&(n.depthTest=t)},getShader(e){const t=gt.get(e);return t?.shader??0},release(e){gt.delete(e)},isValid:e=>gt.has(e),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??dt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=gt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=mt++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return gt.set(n,s),n},toAssetData(e,t){const n=gt.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=gt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let vt=!1,bt=0;const St=4096,Pt=new Map;let Ct=null;function Et(e){const t=(0===bt&&ft&&(bt=ft._malloc(St)),bt);if(0===t||!ft)return{ptr:0,count:0};let n=0,s=0;const r=ft.HEAPU8,o=ft.HEAPU32,i=ft.HEAPF32;for(const[a,l]of e){if(n+128>St)break;let e=Pt.get(a);e||(Ct||(Ct=new TextEncoder),e=Ct.encode(a),Pt.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 Mt(){if(!ft||vt)return;ft.materialDataProvider=(e,t,n,s,r)=>{const o=gt.get(e);if(!o)return ft.HEAPU32[t>>2]=0,ft.HEAPU32[n>>2]=0,ft.HEAPU32[s>>2]=0,void(ft.HEAPU32[r>>2]=0);ft.HEAPU32[t>>2]=o.shader,ft.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Et(o.uniforms);ft.HEAPU32[s>>2]=i,ft.HEAPU32[r>>2]=a},vt=!0}const Tt={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class At{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const n=this.pending_.get(e);if(n)return n;const s=this.loadInternal(e);this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(xt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())xt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const 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:xt.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function Rt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,G,{value:s.name}),!1!==s.visible)for(const n of s.components)Ut(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function Ft(e,t,n){const s=new Map,r=n?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();if(s.set(i.id,t),e.insert(t,G,{value:i.name}),!1!==i.visible)for(const s of i.components){if("Sprite"===s.type&&r){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:n?.assetBaseUrl?`${n.assetBaseUrl}/${t}`:`/${t}`;try{const n=await r.loadTexture(s);e.texture=n.handle,o.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("BitmapText"===s.type&&r){const e=s.data;if("string"==typeof e.font&&e.font)try{const t=await r.loadBitmapFont(e.font,n?.assetBaseUrl);e.font=t}catch(t){console.warn(`Failed to load bitmap font: ${e.font}`,t),e.font=0}}if("SpineAnimation"===s.type&&r){const e=s.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await r.loadSpine(t,o,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Ut(e,t,s)}}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function Ut(e,t,n){const s=n.data;switch(n.type){case"LocalTransform":e.insert(t,L,s);break;case"Sprite":e.insert(t,H,s);break;case"Camera":e.insert(t,W,s);break;case"Canvas":e.insert(t,O,s);break;case"Text":e.insert(t,Te,s);break;case"BitmapText":e.insert(t,V,s);break;case"SpineAnimation":e.insert(t,Y,s);break;case"UIRect":{const n=s;n.anchor&&!n.anchorMin&&(n.anchorMin={...n.anchor},n.anchorMax={...n.anchor},delete n.anchor),e.insert(t,Re,n);break}case"UIMask":e.insert(t,ke,s);break;case"Interactable":e.insert(t,Xe,s);break;case"Button":e.insert(t,Ge,s);break;case"RigidBody":e.insert(t,S,s);break;case"BoxCollider":e.insert(t,P,s);break;case"CircleCollider":e.insert(t,C,s);break;case"CapsuleCollider":e.insert(t,E,s);break;default:{const r=B(n.type);r?e.insert(t,r,s):console.warn(`Unknown component type: ${n.type}`);break}}}function Bt(e,t){const n=e.getEntitiesWithComponents([W]);for(const s of n){const n=e.get(s,W);n&&(n.aspectRatio=t,e.insert(s,W,n))}}function It(e,t){const n=e.getEntitiesWithComponents([G]);for(const s of n){const n=e.get(s,G);if(n&&n.value===t)return s}return null}class kt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const n=this.cache_.get(e);if(void 0!==n)return n;const s=this.pending_.get(e);if(s)return s;const r=t();this.pending_.set(e,r);try{const t=await r;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}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()}values(){return this.cache_.values()}}class $t{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.module_=e,this.canvas_=d(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new At(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);this.textureCache_.clear(),this.fontCache_.clear(),this.prefabCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.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)}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);for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,n),c=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);return this.writeToVirtualFS(e,c)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}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()=>e.endsWith(".bmfont")?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 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)}}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)}))}}return await Promise.all(n),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??n;return new Promise((n,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return xt.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 xt.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 zt=Q(null,"Assets");class Lt{build(e){const t=e.wasmModule;t?e.insertResource(zt,new $t(t)):console.warn("AssetPlugin: No WASM module available")}}const Dt=new Lt;function Ht(e,t){const n=e.getResource(zt);n&&n.registerEmbeddedAssets(t)}async function Wt(e,t,n){const{entities:s,rootId:r}=await Ot(t,n?.overrides??[],n),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 Ft(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}async function Ot(e,t,n,s){const r=new Map;let o;if(void 0===s){o=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),o=Math.max(o,t.prefabEntityId+1))}else{o=s;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,o++)}const i=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await Ot(e,s.nestedPrefab.overrides,n,o);r.set(s.prefabEntityId,t.rootId),o=t.nextId;const a=t.entities.find(e=>e.id===t.rootId);a&&(a.parent=null!==s.parent?r.get(s.parent)??null:null),i.push(...t.entities);continue}const a=r.get(s.prefabEntityId),l=s.prefabEntityId===e.rootEntityId,c={id:a,prefabEntityId:s.prefabEntityId,name:s.name,parent:l?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};Nt(c,t),i.push(c)}const a=r.get(e.rootEntityId);if(void 0===a)throw new Error("Failed to resolve prefab root entity");return{entities:i,rootId:a,nextId:o}}function Nt(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 jt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=await this.assetServer_.loadPrefab(e,t?.baseUrl);return Wt(this.world_,n,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Xt=Q(null,"Prefabs");class Vt{build(e){const t=e.getResource(zt);t?e.insertResource(Xt,new jt(e.world,t)):console.warn("PrefabsPlugin: Assets resource not available")}}const Yt=new Vt;let Gt=null,qt=0,Jt=0,Kt=0;const Qt=new Float32Array(256);function Zt(e){Gt=e,qt=Gt._malloc(64),Jt=Gt._malloc(64),Kt=Gt._malloc(1024)}function en(){Gt&&(qt&&(Gt._free(qt),qt=0),Jt&&(Gt._free(Jt),Jt=0),Kt&&(Gt._free(Kt),Kt=0)),Gt=null}function tn(){if(!Gt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Gt}const nn={r:1,g:1,b:1,a:1},sn={begin(e){const t=tn();t.HEAPF32.set(e,qt/4),t.draw_begin(qt)},end(){tn().draw_end()},line(e,t,n,s=1){tn().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rect(e,t,n,s=!0){tn().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rectOutline(e,t,n,s=1){tn().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},circle(e,t,n,s=!0,r=32){tn().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},circleOutline(e,t,n,s=1,r=32){tn().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=nn){tn().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)},textureRotated(e,t,n,s,r=nn){tn().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){tn().draw_setLayer(e)},setDepth(e){tn().draw_setDepth(e)},getDrawCallCount:()=>Gt?Gt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Gt?Gt.draw_getPrimitiveCount():0,setBlendMode(e){tn().draw_setBlendMode(e)},setDepthTest(e){tn().draw_setDepthTest(e)},drawMesh(e,t,n){const s=tn();s.HEAPF32.set(n,Jt/4),s.draw_mesh(e,t,Jt)},drawMeshWithMaterial(e,t,n){const s=tn(),r=xt.get(t);if(!r)return;if(sn.setBlendMode(r.blendMode),sn.setDepthTest(r.depthTest),0===r.uniforms.size)return void sn.drawMesh(e,r.shader,n);s.HEAPF32.set(n,Jt/4);let o=0,i=0;for(const[e,t]of r.uniforms){const n=on(e);if(!(n<0)){if(ht(t))Qt[o++]=10,Qt[o++]=n,Qt[o++]=t.slot??i++,Qt[o++]=t.textureId;else if("number"==typeof t)Qt[o++]=1,Qt[o++]=n,Qt[o++]=t;else if(Array.isArray(t)){Qt[o++]=t.length,Qt[o++]=n;for(let e=0;e<t.length;e++)Qt[o++]=t[e]}else"w"in t?(Qt[o++]=4,Qt[o++]=n,Qt[o++]=t.x,Qt[o++]=t.y,Qt[o++]=t.z,Qt[o++]=t.w):"z"in t?(Qt[o++]=3,Qt[o++]=n,Qt[o++]=t.x,Qt[o++]=t.y,Qt[o++]=t.z):(Qt[o++]=2,Qt[o++]=n,Qt[o++]=t.x,Qt[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(Qt.subarray(0,o),Kt/4),s.draw_meshWithUniforms(e,r.shader,Jt,Kt,o)):s.draw_mesh(e,r.shader,Jt)}},rn={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function on(e){return rn[e]??-1}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 ln=null,cn=0,un=0,dn=0;function hn(e){ln=e,cn=ln._malloc(262144),un=ln._malloc(65536),dn=ln._malloc(256)}function fn(){ln&&(cn&&ln._free(cn),un&&ln._free(un),dn&&ln._free(dn),cn=0,un=0,dn=0),ln=null}function pn(){if(!ln)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ln}const mn={create(e){const t=pn(),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,cn/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,dn,r).set(o),t.geometry_init(n,cn,s,dn,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,un,s).set(e.indices),t.geometry_setIndices16(n,un,s)}else{new Uint32Array(t.HEAPU8.buffer,un,s).set(e.indices),t.geometry_setIndices32(n,un,s)}}return n},updateVertices(e,t,n=0){const s=pn(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,cn/4),s.geometry_updateVertices(e,cn,r,n)},release(e){e>0&&pn().geometry_release(e)},isValid:e=>!(!ln||e<=0)&&ln.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return mn.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 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 mn.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,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 mn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:an.Float2},{name:"a_texCoord",type:an.Float2}],indices:new Uint16Array(i)})}};let gn=null;function _n(e){gn=e}function yn(){gn&&xn.isInitialized()&&xn.shutdown(),gn=null}function wn(){if(!gn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return gn}const xn={init:(e,t)=>wn().postprocess_init(e,t),shutdown(){wn().postprocess_shutdown()},resize(e,t){wn().postprocess_resize(e,t)},addPass:(e,t)=>wn().postprocess_addPass(e,t),removePass(e){wn().postprocess_removePass(e)},setEnabled(e,t){wn().postprocess_setPassEnabled(e,t)},isEnabled:e=>wn().postprocess_isPassEnabled(e),setUniform(e,t,n){wn().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){wn().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){wn().postprocess_begin()},end(){wn().postprocess_end()},getPassCount:()=>wn().postprocess_getPassCount(),isInitialized:()=>!!gn&&gn.postprocess_isInitialized(),setBypass(e){wn().postprocess_setBypass(e)},isBypassed:()=>!gn||gn.postprocess_isBypassed(),createBlur:()=>xt.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:()=>xt.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:()=>xt.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:()=>xt.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 bn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(bn||(bn={}));let Sn=null,Pn=0;function Cn(e){Sn=e,Pn=Sn._malloc(64)}function En(){Sn&&Pn&&(Sn._free(Pn),Pn=0),Sn=null}const Mn={init(e,t){Sn?.renderer_init(e,t)},resize(e,t){Sn?.renderer_resize(e,t)},begin(e,t){Sn&&Pn&&(Sn.HEAPF32.set(e,Pn/4),Sn.renderer_begin(Pn,t??0))},flush(){Sn?.renderer_flush()},end(){Sn?.renderer_end()},submitSprites(e){Sn&&Sn.renderer_submitSprites(e._cpp)},submitBitmapText(e){Sn&&Sn.renderer_submitBitmapText(e._cpp)},submitSpine(e){Sn&&Sn.renderer_submitSpine?.(e._cpp)},setStage(e){Sn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Sn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Sn?.renderer_releaseTarget(e)},getTargetTexture:e=>Sn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Sn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Sn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Sn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){Sn?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){Sn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Sn?Sn.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Sn?{drawCalls:Sn.renderer_getDrawCalls(),triangles:Sn.renderer_getTriangles(),sprites:Sn.renderer_getSprites(),text:Sn.renderer_getText(),spine:Sn.renderer_getSpine?.()??0,meshes:Sn.renderer_getMeshes(),culled:Sn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Tn=null;function An(e){Tn=e}function Rn(){Tn=null}const Fn={enable(){Tn?.gl_enableErrorCheck(!0)},disable(){Tn?.gl_enableErrorCheck(!1)},check:e=>Tn?.gl_checkErrors(e)??0,diagnose(){Tn?.renderer_diagnose()}},Un=new Map;function Bn(e,t){Un.set(e,t)}function In(e){Un.delete(e)}function kn(){Un.clear()}class $n{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(Mn.resize(s,r),xn.isInitialized()&&xn.getPassCount()>0&&xn.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),Mn.setViewport(0,0,s,r),Mn.clearBuffers(3),Mn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),Mn.submitSprites(t),Mn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Mn.submitSpine(t),Mn.flush(),this.executeDrawCallbacks(n,o),Mn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;Mn.setViewport(s.x,s.y,s.w,s.h),Mn.setScissor(s.x,s.y,s.w,s.h,!0),Mn.clearBuffers(r),Mn.setScissor(0,0,0,0,!1),Mn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Mn.submitSprites(t),Mn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Mn.submitSpine(t),Mn.flush(),this.executeDrawCallbacks(n,o),Mn.end()}executeDrawCallbacks(e,t){const n=Un;if(n.size>0){sn.begin(e);const s=[];for(const[e,r]of n.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}sn.end();for(const e of s)In(e)}}}class zn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=h(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.runSchedule(de.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(de.FixedPreUpdate),this.runSchedule(de.FixedUpdate),this.runSchedule(de.FixedPostUpdate);this.runSchedule(de.PreUpdate),this.runSchedule(de.Update),this.runSchedule(de.PostUpdate),this.runSchedule(de.Last),requestAnimationFrame(this.mainLoop)},this.world_=new Pe,this.resources_=new ne;for(const e of Object.values(de))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new zn}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(de.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(de.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new ye(this.world_,this.resources_),this.resources_.insert(se,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(de.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1,Rn(),En(),yn(),fn(),yt(),en()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(se);t.delta=e,t.elapsed+=e,t.frameCount++}}function Ln(e,t){const n=zn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Zt(e),_t(e),hn(e),_n(e),Cn(e),An(e);const r=new $n;n.pipeline_=r;let o=h();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r){const o=On(e,s,t,r),i=n.getResource(Ke);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(Ke,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=i();if(0===t||0===n)return;const l=e.registry_getCanvasEntity(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;Mn.setClearColor(e.x,e.y,e.z,e.w)}const c=(h()-o)/1e3;Mn.resize(t,n),xn.isInitialized()&&xn.getPassCount()>0&&!xn.isBypassed()&&xn.resize(t,n);const u=On(e,s,t,n);if(a(t,n),0===u.length)r.render({registry:{_cpp:s},viewProjection:Hn,width:t,height:n,elapsed:c});else{for(const e of u){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*n),l=Math.round(o.w*t),u=Math.round(o.h*n);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}Mn.setViewport(0,0,t,n)}}};return n.addSystemToSchedule(de.First,l),n.addSystemToSchedule(de.Last,c),n.addPlugin(Dt),n.addPlugin(Yt),n.addPlugin(be),n.addPlugin(Ie),n.addPlugin(je),n.addPlugin(ot),n.addPlugin(et),n.addPlugin(ut),n}function Dn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Hn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Wn(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}}}function On(e,t,n,s){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*n/(l.h*s);let u,d=0,h=0;if(1===r.projectionType){if(h=r.orthoSize,o){h=Wn(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=jn(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=Vn(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=Gn(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:qn(u,f),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const Nn=new Float32Array(16);function jn(e,t,n,s,r,o){const i=Nn;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 Xn=new Float32Array(16);function Vn(e,t,n,s){const r=Xn;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 Yn=new Float32Array(16);function Gn(e,t,n){const s=Yn;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}function qn(e,t){const n=new Float32Array(16);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}async function Jn(e,t){if(t)return t();return(0,(await import(e)).default)()}const Kn=Q({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Qn=Q(null,"PhysicsAPI");function Zn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function es(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class ts{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(Kn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Jn(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([O]);for(const n of t){const t=e.world.get(n,O);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(de.PostUpdate,fe([Z(se)],a=>{const l=i.getEntitiesWithComponents([S,L,D]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,S),l=i.get(r,D);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=Zn(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),ns(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===M.Kinematic){const e=Zn(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,L);if(!u)continue;let d=a,h=l,f=c;if(e.world.has(i,j)){const t=e.world.get(i,j);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,D)){const n=e.world.get(t.entity,D),s=Zn(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=es(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,L,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(Kn,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.__physicsModule=s,e.insertResource(Qn,ss._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=s}}function ns(e,t,n){const s=e.world;if(s.has(n,P)){const e=s.get(n,P);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,C)){const e=s.get(n,C);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,E)){const e=s.get(n,E);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class ss{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(ss.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 rs(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 os(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 is(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,f=c+c,p=a*d,m=a*h,g=a*f,_=l*h,y=l*f,w=c*f,x=u*d,v=u*h,b=u*f;return new Float32Array([(1-(_+w))*r,(m+b)*r,(g-v)*r,0,(m-b)*o,(1-(p+w))*o,(y+x)*o,0,(g+v)*i,(y-x)*i,(1-(p+_))*i,0,e.position.x,e.position.y,e.position.z,1])}async function as(e,t,n,s,r,o,i,a){const l=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=rs(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,l);let c={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),c=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=r.readText(a),u=l.endsWith(".skel");let d,h;if(u){const e=r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=r.readText(i),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const f=n.loadSkeleton(d,h,s,s.length,u);if(t._free(d),f<0)continue;o[i]=f;const p=os(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=rs(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,n,s)),o){new ts("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;if(r.endsWith(".bmfont")){const e=JSON.parse(n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const i=t.match(/file="([^"]+)"/);if(!i){s[r]=0;continue}const a=o?`${o}/${i[1]}`:i[1],l=n.loadPixelsRaw?await n.loadPixelsRaw(a):await n.loadPixels(a),c=rs(e,l,!1),u=e.getResourceManager();s[r]=u.loadBitmapFont(t,c,l.width,l.height)}catch{s[r]=0}}return s}(t,n,s),h=function(e,t){const n={},s={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===n[r])try{const e=JSON.parse(t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=xt.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=xt.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),f=Rt(e.world,n);if(function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const r=e.get(t,H);r&&(r.texture=n[s.data.texture]||0,e.insert(t,H,r))}}}(e.world,n,l,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if("BitmapText"!==s.type||!s.data.font||"string"!=typeof s.data.font)continue;const r=n[s.data.font]||0;if(!r)continue;const o=e.get(t,V);o&&(o.font=r,e.insert(t,V,o))}}}(e.world,n,d,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const r=n[s.data.material]||0;if(r)if("Sprite"===s.type){const n=e.get(t,H);n&&(n.material=r,e.insert(t,H,n))}else if("SpineAnimation"===s.type){const n=e.get(t,Y);n&&(n.material=r,e.insert(t,Y,n))}}}}(e.world,n,h,f),r&&u){const s=function(e,t,n,s){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,n,c,f);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,Y)?c.get(o,Y):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(i,l*d);let h=0;if(c.has(o,D)){const e=is(c.get(o,D),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,d,f);const p=n.HEAPU32[d>>2],m=n.HEAPU32[f>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*r),_=new Uint16Array(n.HEAPU8.buffer,u,o),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(_),t.renderer_submitTriangles(y,r,w,o,p,m,h),t._free(y),t._free(w),n._free(c),n._free(u),n._free(d),n._free(f)}h&&t._free(h)}})}(e,t,r,u,s)}if(a){const t=e.getResource(zt);t&&t.setAddressableManifest(a)}}class ls{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&(s.endsWith(".skel")?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));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(()=>{}));await Promise.all(r);const o=[];for(const e of s){if(!e.endsWith(".bmfont"))continue;const t=this.textCache_.get(e);if(t)try{const n=JSON.parse(t),s="label-atlas"===n.type?n.generatedFnt:n.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(()=>{}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class cs{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(!this.app_)return;let e="fetch scene";try{const t=await i(this.sceneUrl_);if(!t.ok)throw new Error(`Failed to fetch scene: ${t.status}`);e="parse scene JSON";const n=await t.json();e="prefetch assets";const s=new ls(this.baseUrl_);await s.prefetch(n);let r=null;const o=this.app_.__spineInitPromise;if(o){e="init spine";r=(await o).controller.raw}e="loadRuntimeScene",await as(this.app_,this.app_.wasmModule,n,s,r),e="ensureCamera",this.ensureCamera()}catch(t){const n=t instanceof Error?t.message:String(t),s=t instanceof Error?t.stack:"";throw console.error(`[PreviewPlugin] Failed at step "${e}": ${n}\n${s}`),new Error(`[PreviewPlugin:${e}] ${n}`)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([W]);for(const s of n){if(e.get(s,W).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const s=e.getEntitiesWithComponents([O]);for(const r of s){const s=e.get(r,O);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,L,o);const i={isActive:!0,projectionType:1,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3};e.insert(r,W,i)}}}const us={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Mn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Mn.getTargetTexture(n),width:e.width,height:e.height}},release(e){Mn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Mn.releaseRenderTarget(e._handle),us.create({width:t,height:n,depth:!0})),begin(e,t){Mn.begin(t,e._handle)},end(){Mn.end()},getDepthTexture:e=>Mn.getTargetDepthTexture(e._handle)};let ds=!1;function hs(e){ds=e}function fs(){return ds}function ps(){return!ds}e=f;export{zn as App,Lt as AssetPlugin,$t as AssetServer,zt as Assets,kt as AsyncCache,V as BitmapText,dt as BlendMode,M as BodyType,P as BoxCollider,Ge as Button,Ye as ButtonState,W as Camera,O as Canvas,E as CapsuleCollider,X as Children,C as CircleCollider,le as Commands,ue as CommandsInstance,an as DataType,sn as Draw,ce as EntityCommands,Fn as GLDebug,mn as Geometry,p as INVALID_ENTITY,g as INVALID_FONT,m as INVALID_TEXTURE,xe as Input,ve as InputPlugin,we as InputState,Xe as Interactable,L as LocalTransform,xt as Material,At as MaterialLoader,re as Mut,G as Name,j as Parent,ss as Physics,Kn as PhysicsEvents,ts as PhysicsPlugin,xn as PostProcess,jt as PrefabServer,Xt as Prefabs,Vt as PrefabsPlugin,cs as PreviewPlugin,ie as Query,ae as QueryInstance,$n as RenderPipeline,bn as RenderStage,us as RenderTexture,Mn as Renderer,Z as Res,ee as ResMut,S as RigidBody,de as Schedule,tt as ScreenSpace,Tt as ShaderSources,Y as SpineAnimation,H as Sprite,ye as SystemRunner,Te as Text,Ce as TextAlign,it as TextInput,at as TextInputPlugin,Me as TextOverflow,Be as TextPlugin,Ae as TextRenderer,Ee as TextVerticalAlign,se as Time,Ke as UICameraInfo,qe as UIEventQueue,Je as UIEvents,Ve as UIInteraction,Ze as UIInteractionPlugin,rt as UILayoutPlugin,ke as UIMask,Ne as UIMaskPlugin,Re as UIRect,N as Velocity,ls as WebAssetProvider,Pe as World,D as WorldTransform,ge as addStartupSystem,me as addSystem,_e as addSystemToSchedule,Dt as assetPlugin,kn as clearDrawCallbacks,I as clearUserComponents,x as color,nt as computeUIRectLayout,Oe as createMaskProcessor,Ln as createWebApp,F as defineComponent,Q as defineResource,fe as defineSystem,U as defineTag,It as findEntityByName,Dn as flushPendingSystems,J as getComponentDefaults,t as getPlatform,s as getPlatformType,B as getUserComponent,Zt as initDrawAPI,An as initGLDebugAPI,hn as initGeometryAPI,_t as initMaterialAPI,_n as initPostProcessAPI,Cn as initRendererAPI,be as inputPlugin,Wt as instantiatePrefab,$e as intersectRects,Le as invertMatrix4,z as isBuiltinComponent,fs as isEditor,n as isPlatformInitialized,ps as isRuntime,ht as isTextureRef,r as isWeChat,o as isWeb,Ut as loadComponent,Jn as loadPhysicsModule,as as loadRuntimeScene,Rt as loadSceneData,Ft as loadSceneWithAssets,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,He as pointInWorldRect,Yt as prefabsPlugin,v as quat,Bn as registerDrawCallback,Ht as registerEmbeddedAssets,Mt as registerMaterialCallback,De as screenToWorld,hs as setEditorMode,en as shutdownDrawAPI,Rn as shutdownGLDebugAPI,fn as shutdownGeometryAPI,yt as shutdownMaterialAPI,yn as shutdownPostProcessAPI,En as shutdownRendererAPI,ut as textInputPlugin,Ie as textPlugin,et as uiInteractionPlugin,ot as uiLayoutPlugin,je as uiMaskPlugin,In as unregisterDrawCallback,Bt as updateCameraAspectRatio,_ as vec2,y as vec3,w as vec4,ze as worldRectToScreen};
+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function d(e,n){return t().createCanvas(e,n)}function h(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.module}}createImage(){return new Image}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),r=t=>e.onKeyUp(t.code),o=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},i=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},u=()=>{e.onPointerUp(0)},d=t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)};document.addEventListener("keydown",s),document.addEventListener("keyup",r),n.addEventListener("mousemove",o),n.addEventListener("mousedown",i),n.addEventListener("mouseup",a),n.addEventListener("touchstart",l),n.addEventListener("touchmove",c),n.addEventListener("touchend",u),n.addEventListener("wheel",d),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",r),n.removeEventListener("mousemove",o),n.removeEventListener("mousedown",i),n.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",u),n.removeEventListener("wheel",d)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=0,m=4294967295,g=4294967295,_=(e=0,t=0)=>({x:e,y:t}),y=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),w=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),x=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),v=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function b(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const S=b("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),P=b("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),C=b("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),E=b("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),M={Static:0,Kinematic:1,Dynamic:2};let T=0;function A(e,t){const n=++T;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function R(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function F(e,t){const n=R(),s=n.get(e);if(s)return s;const r=A(e,t);return n.set(e,r),k(e,t,!1),r}function U(e){const t=R(),n=t.get(e);if(n)return n;const s=A(e,{});return t.set(e,s),k(e,{},!0),s}function B(e){return R().get(e)}function I(){R().clear()}function k(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function $(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function z(e){return!0===e._builtin}const L=$("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),D=$("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),H=$("Sprite",{texture:m,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}),W=$("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),O=$("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),N=$("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),j=$("Parent",{entity:0}),X=$("Children",{entities:[]}),V=$("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:g}),Y=$("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}),G={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},q={LocalTransform:L,WorldTransform:D,Sprite:H,Camera:W,Canvas:O,Velocity:N,Parent:j,Children:X,BitmapText:V,SpineAnimation:Y,RigidBody:S,BoxCollider:P,CircleCollider:C,CapsuleCollider:E};function J(e){const t=q[e];if(t)return{...t._default};const n=B(e);return n?{...n._default}:null}let K=0;function Q(e,t){const n=++K;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function Z(e){return{_type:"res",_resource:e}}function ee(e){return{_type:"res_mut",_resource:e}}class te{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}}class ne{constructor(){this.resources_=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)}getResMut(e){return new te(this.get(e),t=>this.set(e,t))}}const se=Q({delta:0,elapsed:0,frameCount:0},"Time");function re(e){return{_type:"mut",_component:e}}function oe(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)=>{oe(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class ae{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>oe(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with)}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),r=n.length,o=e.length>0,i=t.length>0,a=new Array(r+1);let l=null,c=[];try{for(const u of s){if(null!==l&&o){for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}c.length=0}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(u,t[n])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,n[e]);if(o){for(let t=0;t<e.length;t++){const s=e[t];c.push({component:n[s],data:a[s+1]})}l=u}yield a}}finally{if(null!==l&&o)for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,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 le(){return{_type:"commands"}}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 n;return n=z(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class ue{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,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_=[];for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}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":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var de;!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"}(de||(de={}));let he=0;function fe(e,t,n){const s=++he;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function pe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function me(e){pe().push({schedule:de.Update,system:e})}function ge(e){pe().push({schedule:de.Startup,system:e})}function _e(e,t){pe().push({schedule:e,system:t})}class ye{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof ue&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new ae(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new ue(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class we{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=Q(new we,"Input");class ve{constructor(e){this.target_=e??null}build(e){const n=new we;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(de.Last,fe([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const be=new ve;function Se(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}:Se(e)}}return t}class Pe{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return z(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return z(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return z(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){z(t)?this.removeBuiltin(e,t):this.removeScript(e,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 r={...t._default,...s};if(this.cppRegistry_){const n=`add${t._cppName}`,s=this.cppRegistry_[n];s?.call(this.cppRegistry_,e,Se(r))}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const n=`get${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const n=`has${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const n=`remove${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e)}insertScript(e,t,n){const s=t.create(n);return this.getStorage(t).set(e,s),s}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)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();let t=null,n=1/0;for(const s of e)if(!z(s)){const e=this.tsStorage_.get(s._id),r=e?e.size:0;r<n&&(n=r,t=e??null)}const s=[],r=t?t.keys():this.entities_;for(const t of r){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&s.push(t)}return s}}var Ce,Ee,Me;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Ce||(Ce={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Ee||(Ee={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Me||(Me={}));const Te=F("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Ce.Left,verticalAlign:Ee.Top,wordWrap:!0,overflow:Me.Visible,lineHeight:1.2});class Ae{constructor(e){this.cache=new Map,this.module=e,this.canvas=d(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=r?Math.ceil(o):d+2*u,p=r?Math.ceil(i):h+2*u;if(r&&e.overflow===Me.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),_=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${g}, ${_}, ${y})`,r&&e.overflow===Me.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 Ee.Top:x=u;break;case Ee.Middle:x=(p-w)/2;break;case Ee.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 Ce.Left:s=u;break;case Ce.Center:s=f/2;break;case Ce.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=c}r&&e.overflow===Me.Clip&&n.restore();const b=n.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const E=P.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{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()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case Ce.Left:return"left";case Ce.Center:return"center";case Ce.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const Re=F("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}});function Fe(e){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight}}function Ue(e,t){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight}class Be{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Ae(t),s=e.world,r=new Map;e.addSystemToSchedule(de.PreUpdate,fe([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Te));for(const e of r.keys())s.valid(e)&&s.has(e,Te)||r.delete(e);const e=s.getEntitiesWithComponents([Te]);for(const t of e){const e=s.get(t,Te),o=r.get(t);if(o&&!Ue(o,e))continue;s.has(t,H)||s.insert(t,H,{texture:m,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const i=s.has(t,Re)?s.get(t,Re):null,a=n.renderForEntity(t,e,i),l=s.get(t,H);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,H,l),r.set(t,Fe(e))}}))}}const Ie=new Be,ke=F("UIMask",{enabled:!0});function $e(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 ze(e,t,n,s,r,o,i,a,l,c,u){const d=e-n*r,h=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function m(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*u]}const[g,_]=m(d,f),[y,w]=m(h,p),x=Math.min(g,y),v=Math.max(g,y),b=Math.min(_,w),S=Math.max(_,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function Le(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],f=e[10],p=e[11],m=e[12],g=e[13],_=e[14],y=e[15],w=s*l-r*a,x=s*c-o*a,v=s*u-i*a,b=r*c-o*l,S=r*u-i*l,P=o*u-i*c,C=d*g-h*m,E=d*_-f*m,M=d*y-p*m,T=h*_-f*g,A=h*y-p*g,R=f*y-p*_;let F=w*R-x*A+v*T+b*M-S*E+P*C;return 0===F||(F=1/F,n[0]=(l*R-c*A+u*T)*F,n[1]=(o*A-r*R-i*T)*F,n[2]=(g*P-_*S+y*b)*F,n[3]=(f*S-h*P-p*b)*F,n[4]=(c*M-a*R-u*E)*F,n[5]=(s*R-o*M+i*E)*F,n[6]=(_*v-m*P-y*x)*F,n[7]=(d*P-f*v+p*x)*F,n[8]=(a*A-l*M+u*C)*F,n[9]=(r*M-s*A-i*C)*F,n[10]=(m*S-g*v+y*w)*F,n[11]=(h*v-d*S-p*w)*F,n[12]=(l*E-a*T-c*C)*F,n[13]=(s*T-r*E+o*C)*F,n[14]=(g*x-m*b-_*w)*F,n[15]=(d*b-h*x+f*w)*F),n}function De(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 He(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 We(e,t,n,s,r,o,i){if(!e.has(t,Re)||!e.has(t,D))return null;const a=e.get(t,Re),l=e.get(t,D),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return ze(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function Oe(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([ke]);if(0!==l.length)try{!function(e,t,n,s,r,o,i,a,l){const c=new Set;for(const e of s){t.get(e,ke).enabled&&c.add(e)}const u=[];for(const e of s){if(!c.has(e))continue;let n=!0,s=e;for(;t.has(s,j);){const e=t.get(s,j);if(c.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(c.has(n)){const e=We(t,n,r,o,i,a,l);e&&(s=$e(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=We(t,e,r,o,i,a,l);n&&d(e,n)}}(e,t,n,l,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class Ne{build(e){if(!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Oe(e.wasmModule,e.world))}}const je=new Ne,Xe=F("Interactable",{enabled:!0}),Ve=F("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Ye;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Ye||(Ye={}));const Ge=F("Button",{state:Ye.Normal,transition:null});class qe{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const Je=Q(new qe,"UIEvents"),Ke=Q({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo"),Qe=new Float32Array(16);class Ze{build(e){const t=e.world,n=new qe;e.insertResource(Je,n);let s=null,r=null;e.addSystemToSchedule(de.PreUpdate,fe([Z(xe),Z(Ke)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([Ve]);for(const e of i){const n=t.get(e,Ve);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;Le(o.viewProjection,Qe);const u=De(l,c,Qe,o.vpX,o.vpY,o.vpW,o.vpH),d=t.getEntitiesWithComponents([Xe,Re,D]);let h=null,f=-1/0;for(const e of d){t.has(e,Ve)||t.insert(e,Ve);if(!t.get(e,Xe).enabled)continue;const n=t.get(e,D),s=t.get(e,Re),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(He(u.x,u.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y)){let n=0;t.has(e,H)&&(n=t.get(e,H).layer),n>=f&&(f=n,h=e)}}if(s!==h){if(null!==s&&t.valid(s)&&t.has(s,Ve)){t.get(s,Ve).hovered=!1,n.emit(s,"hover_exit")}if(null!==h){t.get(h,Ve).hovered=!0,n.emit(h,"hover_enter")}s=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,Ve);e.pressed=!0,e.justPressed=!0,r=h,n.emit(h,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Ve)){const e=t.get(r,Ve);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(de.Update,fe([],()=>{const e=t.getEntitiesWithComponents([Ge]);for(const n of e){if(t.has(n,Xe)||t.insert(n,Xe,{enabled:!0}),!t.has(n,Ve))continue;const e=t.get(n,Ve),s=t.get(n,Ge),r=t.get(n,Xe),o=s.state;if(r.enabled?e.pressed?s.state=Ye.Pressed:e.hovered?s.state=Ye.Hovered:s.state=Ye.Normal:s.state=Ye.Disabled,o!==s.state&&s.transition&&t.has(n,H)){const e=t.get(n,H),r=s.transition;switch(s.state){case Ye.Normal:e.color={...r.normalColor};break;case Ye.Hovered:e.color={...r.hoveredColor};break;case Ye.Pressed:e.color={...r.pressedColor};break;case Ye.Disabled:e.color={...r.disabledColor}}t.insert(n,H,e)}}},{name:"ButtonSystem"}))}}const et=new Ze,tt=U("ScreenSpace");function nt(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,f,p,m;if(l===c&&u===d){const e=l+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;h=e-s,f=t-o,p=e+s,m=t+o}else h=l+n.x,f=u+n.y,p=c+s.x,m=d+s.y;return{centerX:.5*(h+p),centerY:.5*(f+m),width:p-h,height:m-f,rect:{left:h,bottom:f,right:p,top:m}}}function st(e,t,n,s,r,o){if(!e.has(t,Re))return;const i=e.get(t,Re),a=nt(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,L);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,L,l),!e.has(t,X))return;const c=e.get(t,X);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&st(e,t,a.rect,a.centerX,a.centerY,!1)}class rt{build(e){const t=e.world;e.addSystemToSchedule(de.PreUpdate,fe([Z(Ke)],e=>{if(!e.valid)return;const n={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(n.left+n.right),r=.5*(n.bottom+n.top),o=t.getEntitiesWithComponents([tt,Re,L]);for(const e of o)st(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const ot=new rt,it=F("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class at{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=d(512,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,u=0;const h=function(){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}();function f(){if(null===i||!n.valid(i))return;const t=n.get(i,it);if(t.readOnly)return;let s=h.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),h.value=s),s!==t.value){t.value=s;e.getResource(Je).emit(i,"change")}t.cursorPos=h.selectionStart??s.length,t.dirty=!0,_()}function p(e){if(i===e)return;g();const t=n.get(e,it);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,h.value=t.value,h.selectionStart=t.cursorPos,h.selectionEnd=t.cursorPos,h.focus(),_())}function g(){if(null!==i&&n.valid(i)&&n.has(i,it)){const e=n.get(i,it);e.focused=!1,e.dirty=!0}i=null,h.blur()}function _(){l=!0,c=0}function y(e,i,a,c){(r.width<a||r.height<c)&&(r.width=ct(Math.max(r.width,a)),r.height=ct(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=lt(o,h,a-2*m);let t=m;for(const n of e)o.fillText(n,m,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(h,m,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=lt(o,i.value.substring(0,i.cursorPos),a-2*m),r=e.length>0?e[e.length-1]:"";t=m+o.measureText(r).width,n=m+(e.length-1)*p,s=p}else t=m+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const g=o.getImageData(0,0,a,c),_=new Uint8Array(g.data.buffer),y=t.getResourceManager(),w=t._malloc(_.length);t.HEAPU8.set(_,w);const x=s.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,c,w,_.length,1,!0);s.set(e,v),t._free(w);const b=n.get(e,H);b.texture=v,b.size.x=a,b.size.y=c,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},n.insert(e,H,b)}h.addEventListener("input",()=>{a||null===i||f()}),h.addEventListener("compositionstart",()=>{a=!0}),h.addEventListener("compositionend",()=>{a=!1,f()}),h.addEventListener("keydown",t=>{if(null===i)return;if("Escape"===t.key)return void g();const s=n.get(i,it);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(Je).emit(i,"submit"),void g()}let r=s.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?r=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=s.value.length),r!==s.cursorPos&&(s.cursorPos=r,h.selectionStart=r,h.selectionEnd=r,s.dirty=!0,_())}),h.addEventListener("blur",()=>{if(null!==i&&n.valid(i)&&n.has(i,it)){const e=n.get(i,it);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(de.PreUpdate,fe([Z(Je)],e=>{const t=n.getEntitiesWithComponents([it,Xe]);for(const e of t){if(!n.has(e,Ve))continue;if(n.get(e,Ve).justPressed)return void p(e)}if(null!==i){const e=n.getEntitiesWithComponents([Xe]);for(const t of e){if(n.has(t,it))continue;if(!n.has(t,Ve))continue;if(n.get(t,Ve).justPressed)return void g()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(de.PreUpdate,fe([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,it)))){n.get(i,it).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,it)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([it,Re]);for(const e of a){const t=n.get(e,it);if(!t.dirty)continue;const s=n.get(e,Re),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,H)||n.insert(e,H,{texture:m,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),y(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function lt(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function ct(e){let t=1;for(;t<e;)t*=2;return t}const ut=new at;var dt;function ht(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"}(dt||(dt={}));let ft=null,pt=null,mt=1;const gt=new Map;function _t(e){ft=e,pt=e.getResourceManager(),Mt()}function yt(){0!==bt&&ft&&(ft._free(bt),bt=0),gt.clear(),mt=1,vt=!1,pt=null,ft=null}function wt(){if(!pt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return pt}const xt={createShader:(e,t)=>wt().createShader(e,t),releaseShader(e){e>0&&wt().releaseShader(e)},create(e){const t=mt++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??dt.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return gt.set(t,n),t},get:e=>gt.get(e),setUniform(e,t,n){const s=gt.get(e);s&&s.uniforms.set(t,n)},getUniform(e,t){const n=gt.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=gt.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=gt.get(e);return t?.blendMode??dt.Normal},setDepthTest(e,t){const n=gt.get(e);n&&(n.depthTest=t)},getShader(e){const t=gt.get(e);return t?.shader??0},release(e){gt.delete(e)},isValid:e=>gt.has(e),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??dt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=gt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=mt++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return gt.set(n,s),n},toAssetData(e,t){const n=gt.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=gt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let vt=!1,bt=0;const St=4096,Pt=new Map;let Ct=null;function Et(e){const t=(0===bt&&ft&&(bt=ft._malloc(St)),bt);if(0===t||!ft)return{ptr:0,count:0};let n=0,s=0;const r=ft.HEAPU8,o=ft.HEAPU32,i=ft.HEAPF32;for(const[a,l]of e){if(n+128>St)break;let e=Pt.get(a);e||(Ct||(Ct=new TextEncoder),e=Ct.encode(a),Pt.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 Mt(){if(!ft||vt)return;ft.materialDataProvider=(e,t,n,s,r)=>{const o=gt.get(e);if(!o)return ft.HEAPU32[t>>2]=0,ft.HEAPU32[n>>2]=0,ft.HEAPU32[s>>2]=0,void(ft.HEAPU32[r>>2]=0);ft.HEAPU32[t>>2]=o.shader,ft.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Et(o.uniforms);ft.HEAPU32[s>>2]=i,ft.HEAPU32[r>>2]=a},vt=!0}const Tt={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class At{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const n=this.pending_.get(e);if(n)return n;const s=this.loadInternal(e);this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(xt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())xt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const 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:xt.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function Rt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,G,{value:s.name}),!1!==s.visible)for(const n of s.components)Ut(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function Ft(e,t,n){const s=new Map,r=n?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();if(s.set(i.id,t),e.insert(t,G,{value:i.name}),!1!==i.visible)for(const s of i.components){if("Sprite"===s.type&&r){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:n?.assetBaseUrl?`${n.assetBaseUrl}/${t}`:`/${t}`;try{const n=await r.loadTexture(s);e.texture=n.handle,o.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("BitmapText"===s.type&&r){const e=s.data;if("string"==typeof e.font&&e.font)try{const t=await r.loadBitmapFont(e.font,n?.assetBaseUrl);e.font=t}catch(t){console.warn(`Failed to load bitmap font: ${e.font}`,t),e.font=0}}if("SpineAnimation"===s.type&&r){const e=s.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await r.loadSpine(t,o,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Ut(e,t,s)}}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function Ut(e,t,n){const s=n.data;switch(n.type){case"LocalTransform":e.insert(t,L,s);break;case"Sprite":e.insert(t,H,s);break;case"Camera":e.insert(t,W,s);break;case"Canvas":e.insert(t,O,s);break;case"Text":e.insert(t,Te,s);break;case"BitmapText":e.insert(t,V,s);break;case"SpineAnimation":e.insert(t,Y,s);break;case"UIRect":{const n=s;n.anchor&&!n.anchorMin&&(n.anchorMin={...n.anchor},n.anchorMax={...n.anchor},delete n.anchor),e.insert(t,Re,n);break}case"UIMask":e.insert(t,ke,s);break;case"Interactable":e.insert(t,Xe,s);break;case"Button":e.insert(t,Ge,s);break;case"RigidBody":e.insert(t,S,s);break;case"BoxCollider":e.insert(t,P,s);break;case"CircleCollider":e.insert(t,C,s);break;case"CapsuleCollider":e.insert(t,E,s);break;default:{const r=B(n.type);r?e.insert(t,r,s):console.warn(`Unknown component type: ${n.type}`);break}}}function Bt(e,t){const n=e.getEntitiesWithComponents([W]);for(const s of n){const n=e.get(s,W);n&&(n.aspectRatio=t,e.insert(s,W,n))}}function It(e,t){const n=e.getEntitiesWithComponents([G]);for(const s of n){const n=e.get(s,G);if(n&&n.value===t)return s}return null}class kt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const n=this.cache_.get(e);if(void 0!==n)return n;const s=this.pending_.get(e);if(s)return s;const r=t();this.pending_.set(e,r);try{const t=await r;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}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()}values(){return this.cache_.values()}}class $t{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.module_=e,this.canvas_=d(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new At(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);this.textureCache_.clear(),this.fontCache_.clear(),this.prefabCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.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)}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);for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,n),c=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);return this.writeToVirtualFS(e,c)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}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()=>e.endsWith(".bmfont")?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 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 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)}))}}return await Promise.all(n),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??n;return new Promise((n,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return xt.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 xt.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 zt=Q(null,"Assets");class Lt{build(e){const t=e.wasmModule;t?e.insertResource(zt,new $t(t)):console.warn("AssetPlugin: No WASM module available")}}const Dt=new Lt;function Ht(e,t){const n=e.getResource(zt);n&&n.registerEmbeddedAssets(t)}async function Wt(e,t,n){const{entities:s,rootId:r}=await Ot(t,n?.overrides??[],n),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 Ft(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}async function Ot(e,t,n,s){const r=new Map;let o;if(void 0===s){o=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),o=Math.max(o,t.prefabEntityId+1))}else{o=s;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,o++)}const i=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await Ot(e,s.nestedPrefab.overrides,n,o);r.set(s.prefabEntityId,t.rootId),o=t.nextId;const a=t.entities.find(e=>e.id===t.rootId);a&&(a.parent=null!==s.parent?r.get(s.parent)??null:null),i.push(...t.entities);continue}const a=r.get(s.prefabEntityId),l=s.prefabEntityId===e.rootEntityId,c={id:a,prefabEntityId:s.prefabEntityId,name:s.name,parent:l?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};Nt(c,t),i.push(c)}const a=r.get(e.rootEntityId);if(void 0===a)throw new Error("Failed to resolve prefab root entity");return{entities:i,rootId:a,nextId:o}}function Nt(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 jt{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 Wt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Xt=Q(null,"Prefabs");class Vt{build(e){const t=e.getResource(zt);t?e.insertResource(Xt,new jt(e.world,t)):console.warn("PrefabsPlugin: Assets resource not available")}}const Yt=new Vt;let Gt=null,qt=0,Jt=0,Kt=0;const Qt=new Float32Array(256);function Zt(e){Gt=e,qt=Gt._malloc(64),Jt=Gt._malloc(64),Kt=Gt._malloc(1024)}function en(){Gt&&(qt&&(Gt._free(qt),qt=0),Jt&&(Gt._free(Jt),Jt=0),Kt&&(Gt._free(Kt),Kt=0)),Gt=null}function tn(){if(!Gt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Gt}const nn={r:1,g:1,b:1,a:1},sn={begin(e){const t=tn();t.HEAPF32.set(e,qt/4),t.draw_begin(qt)},end(){tn().draw_end()},line(e,t,n,s=1){tn().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rect(e,t,n,s=!0){tn().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rectOutline(e,t,n,s=1){tn().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},circle(e,t,n,s=!0,r=32){tn().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},circleOutline(e,t,n,s=1,r=32){tn().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=nn){tn().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)},textureRotated(e,t,n,s,r=nn){tn().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){tn().draw_setLayer(e)},setDepth(e){tn().draw_setDepth(e)},getDrawCallCount:()=>Gt?Gt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Gt?Gt.draw_getPrimitiveCount():0,setBlendMode(e){tn().draw_setBlendMode(e)},setDepthTest(e){tn().draw_setDepthTest(e)},drawMesh(e,t,n){const s=tn();s.HEAPF32.set(n,Jt/4),s.draw_mesh(e,t,Jt)},drawMeshWithMaterial(e,t,n){const s=tn(),r=xt.get(t);if(!r)return;if(sn.setBlendMode(r.blendMode),sn.setDepthTest(r.depthTest),0===r.uniforms.size)return void sn.drawMesh(e,r.shader,n);s.HEAPF32.set(n,Jt/4);let o=0,i=0;for(const[e,t]of r.uniforms){const n=on(e);if(!(n<0)){if(ht(t))Qt[o++]=10,Qt[o++]=n,Qt[o++]=t.slot??i++,Qt[o++]=t.textureId;else if("number"==typeof t)Qt[o++]=1,Qt[o++]=n,Qt[o++]=t;else if(Array.isArray(t)){Qt[o++]=t.length,Qt[o++]=n;for(let e=0;e<t.length;e++)Qt[o++]=t[e]}else"w"in t?(Qt[o++]=4,Qt[o++]=n,Qt[o++]=t.x,Qt[o++]=t.y,Qt[o++]=t.z,Qt[o++]=t.w):"z"in t?(Qt[o++]=3,Qt[o++]=n,Qt[o++]=t.x,Qt[o++]=t.y,Qt[o++]=t.z):(Qt[o++]=2,Qt[o++]=n,Qt[o++]=t.x,Qt[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(Qt.subarray(0,o),Kt/4),s.draw_meshWithUniforms(e,r.shader,Jt,Kt,o)):s.draw_mesh(e,r.shader,Jt)}},rn={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function on(e){return rn[e]??-1}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 ln=null,cn=0,un=0,dn=0;function hn(e){ln=e,cn=ln._malloc(262144),un=ln._malloc(65536),dn=ln._malloc(256)}function fn(){ln&&(cn&&ln._free(cn),un&&ln._free(un),dn&&ln._free(dn),cn=0,un=0,dn=0),ln=null}function pn(){if(!ln)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ln}const mn={create(e){const t=pn(),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,cn/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,dn,r).set(o),t.geometry_init(n,cn,s,dn,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,un,s).set(e.indices),t.geometry_setIndices16(n,un,s)}else{new Uint32Array(t.HEAPU8.buffer,un,s).set(e.indices),t.geometry_setIndices32(n,un,s)}}return n},updateVertices(e,t,n=0){const s=pn(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,cn/4),s.geometry_updateVertices(e,cn,r,n)},release(e){e>0&&pn().geometry_release(e)},isValid:e=>!(!ln||e<=0)&&ln.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return mn.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 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 mn.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,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 mn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:an.Float2},{name:"a_texCoord",type:an.Float2}],indices:new Uint16Array(i)})}};let gn=null;function _n(e){gn=e}function yn(){gn&&xn.isInitialized()&&xn.shutdown(),gn=null}function wn(){if(!gn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return gn}const xn={init:(e,t)=>wn().postprocess_init(e,t),shutdown(){wn().postprocess_shutdown()},resize(e,t){wn().postprocess_resize(e,t)},addPass:(e,t)=>wn().postprocess_addPass(e,t),removePass(e){wn().postprocess_removePass(e)},setEnabled(e,t){wn().postprocess_setPassEnabled(e,t)},isEnabled:e=>wn().postprocess_isPassEnabled(e),setUniform(e,t,n){wn().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){wn().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){wn().postprocess_begin()},end(){wn().postprocess_end()},getPassCount:()=>wn().postprocess_getPassCount(),isInitialized:()=>!!gn&&gn.postprocess_isInitialized(),setBypass(e){wn().postprocess_setBypass(e)},isBypassed:()=>!gn||gn.postprocess_isBypassed(),createBlur:()=>xt.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:()=>xt.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:()=>xt.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:()=>xt.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 bn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(bn||(bn={}));let Sn=null,Pn=0;function Cn(e){Sn=e,Pn=Sn._malloc(64)}function En(){Sn&&Pn&&(Sn._free(Pn),Pn=0),Sn=null}const Mn={init(e,t){Sn?.renderer_init(e,t)},resize(e,t){Sn?.renderer_resize(e,t)},begin(e,t){Sn&&Pn&&(Sn.HEAPF32.set(e,Pn/4),Sn.renderer_begin(Pn,t??0))},flush(){Sn?.renderer_flush()},end(){Sn?.renderer_end()},submitSprites(e){Sn&&Sn.renderer_submitSprites(e._cpp)},submitBitmapText(e){Sn&&Sn.renderer_submitBitmapText(e._cpp)},submitSpine(e){Sn&&Sn.renderer_submitSpine?.(e._cpp)},setStage(e){Sn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Sn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Sn?.renderer_releaseTarget(e)},getTargetTexture:e=>Sn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Sn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Sn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Sn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){Sn?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){Sn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Sn?Sn.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Sn?{drawCalls:Sn.renderer_getDrawCalls(),triangles:Sn.renderer_getTriangles(),sprites:Sn.renderer_getSprites(),text:Sn.renderer_getText(),spine:Sn.renderer_getSpine?.()??0,meshes:Sn.renderer_getMeshes(),culled:Sn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Tn=null;function An(e){Tn=e}function Rn(){Tn=null}const Fn={enable(){Tn?.gl_enableErrorCheck(!0)},disable(){Tn?.gl_enableErrorCheck(!1)},check:e=>Tn?.gl_checkErrors(e)??0,diagnose(){Tn?.renderer_diagnose()}},Un=new Map;function Bn(e,t){Un.set(e,t)}function In(e){Un.delete(e)}function kn(){Un.clear()}class $n{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(Mn.resize(s,r),xn.isInitialized()&&xn.getPassCount()>0&&xn.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),Mn.setViewport(0,0,s,r),Mn.clearBuffers(3),Mn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),Mn.submitSprites(t),Mn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Mn.submitSpine(t),Mn.flush(),this.executeDrawCallbacks(n,o),Mn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;Mn.setViewport(s.x,s.y,s.w,s.h),Mn.setScissor(s.x,s.y,s.w,s.h,!0),Mn.clearBuffers(r),Mn.setScissor(0,0,0,0,!1),Mn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Mn.submitSprites(t),Mn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Mn.submitSpine(t),Mn.flush(),this.executeDrawCallbacks(n,o),Mn.end()}executeDrawCallbacks(e,t){const n=Un;if(n.size>0){sn.begin(e);const s=[];for(const[e,r]of n.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}sn.end();for(const e of s)In(e)}}}class zn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=h(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.runSchedule(de.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(de.FixedPreUpdate),this.runSchedule(de.FixedUpdate),this.runSchedule(de.FixedPostUpdate);this.runSchedule(de.PreUpdate),this.runSchedule(de.Update),this.runSchedule(de.PostUpdate),this.runSchedule(de.Last),requestAnimationFrame(this.mainLoop)},this.world_=new Pe,this.resources_=new ne;for(const e of Object.values(de))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new zn}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(de.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(de.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new ye(this.world_,this.resources_),this.resources_.insert(se,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(de.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1,Rn(),En(),yn(),fn(),yt(),en()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(se);t.delta=e,t.elapsed+=e,t.frameCount++}}function Ln(e,t){const n=zn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Zt(e),_t(e),hn(e),_n(e),Cn(e),An(e);const r=new $n;n.pipeline_=r;let o=h();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r){const o=On(e,s,t,r),i=n.getResource(Ke);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(Ke,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=i();if(0===t||0===n)return;const l=e.registry_getCanvasEntity(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;Mn.setClearColor(e.x,e.y,e.z,e.w)}const c=(h()-o)/1e3;Mn.resize(t,n),xn.isInitialized()&&xn.getPassCount()>0&&!xn.isBypassed()&&xn.resize(t,n);const u=On(e,s,t,n);if(a(t,n),0===u.length)r.render({registry:{_cpp:s},viewProjection:Hn,width:t,height:n,elapsed:c});else{for(const e of u){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*n),l=Math.round(o.w*t),u=Math.round(o.h*n);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}Mn.setViewport(0,0,t,n)}}};return n.addSystemToSchedule(de.First,l),n.addSystemToSchedule(de.Last,c),n.addPlugin(Dt),n.addPlugin(Yt),n.addPlugin(be),n.addPlugin(Ie),n.addPlugin(je),n.addPlugin(ot),n.addPlugin(et),n.addPlugin(ut),n}function Dn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Hn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Wn(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}}}function On(e,t,n,s){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*n/(l.h*s);let u,d=0,h=0;if(1===r.projectionType){if(h=r.orthoSize,o){h=Wn(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=jn(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=Vn(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=Gn(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:qn(u,f),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const Nn=new Float32Array(16);function jn(e,t,n,s,r,o){const i=Nn;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 Xn=new Float32Array(16);function Vn(e,t,n,s){const r=Xn;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 Yn=new Float32Array(16);function Gn(e,t,n){const s=Yn;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}function qn(e,t){const n=new Float32Array(16);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}async function Jn(e,t){if(t)return t();return(0,(await import(e)).default)()}const Kn=Q({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Qn=Q(null,"PhysicsAPI");function Zn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function es(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class ts{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(Kn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Jn(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([O]);for(const n of t){const t=e.world.get(n,O);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(de.PostUpdate,fe([Z(se)],a=>{const l=i.getEntitiesWithComponents([S,L,D]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,S),l=i.get(r,D);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=Zn(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),ns(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===M.Kinematic){const e=Zn(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,L);if(!u)continue;let d=a,h=l,f=c;if(e.world.has(i,j)){const t=e.world.get(i,j);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,D)){const n=e.world.get(t.entity,D),s=Zn(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=es(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,L,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(Kn,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.__physicsModule=s,e.insertResource(Qn,ss._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=s}}function ns(e,t,n){const s=e.world;if(s.has(n,P)){const e=s.get(n,P);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,C)){const e=s.get(n,C);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,E)){const e=s.get(n,E);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class ss{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(ss.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 rs(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 os(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 is(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,f=c+c,p=a*d,m=a*h,g=a*f,_=l*h,y=l*f,w=c*f,x=u*d,v=u*h,b=u*f;return new Float32Array([(1-(_+w))*r,(m+b)*r,(g-v)*r,0,(m-b)*o,(1-(p+w))*o,(y+x)*o,0,(g+v)*i,(y-x)*i,(1-(p+_))*i,0,e.position.x,e.position.y,e.position.z,1])}async function as(e,t,n,s,r,o,i,a){const l=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=rs(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,l);let c={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),c=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=r.readText(a),u=l.endsWith(".skel");let d,h;if(u){const e=r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=r.readText(i),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const f=n.loadSkeleton(d,h,s,s.length,u);if(t._free(d),f<0)continue;o[i]=f;const p=os(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=rs(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,n,s)),o){new ts("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;if(r.endsWith(".bmfont")){const e=JSON.parse(n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const i=t.match(/file="([^"]+)"/);if(!i){s[r]=0;continue}const a=o?`${o}/${i[1]}`:i[1],l=n.loadPixelsRaw?await n.loadPixelsRaw(a):await n.loadPixels(a),c=rs(e,l,!1),u=e.getResourceManager();s[r]=u.loadBitmapFont(t,c,l.width,l.height)}catch{s[r]=0}}return s}(t,n,s),h=function(e,t){const n={},s={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===n[r])try{const e=JSON.parse(t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=xt.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=xt.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),f=Rt(e.world,n);if(function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const r=e.get(t,H);r&&(r.texture=n[s.data.texture]||0,e.insert(t,H,r))}}}(e.world,n,l,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if("BitmapText"!==s.type||!s.data.font||"string"!=typeof s.data.font)continue;const r=n[s.data.font]||0;if(!r)continue;const o=e.get(t,V);o&&(o.font=r,e.insert(t,V,o))}}}(e.world,n,d,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const r=n[s.data.material]||0;if(r)if("Sprite"===s.type){const n=e.get(t,H);n&&(n.material=r,e.insert(t,H,n))}else if("SpineAnimation"===s.type){const n=e.get(t,Y);n&&(n.material=r,e.insert(t,Y,n))}}}}(e.world,n,h,f),r&&u){const s=function(e,t,n,s){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,n,c,f);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,Y)?c.get(o,Y):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(i,l*d);let h=0;if(c.has(o,D)){const e=is(c.get(o,D),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,d,f);const p=n.HEAPU32[d>>2],m=n.HEAPU32[f>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*r),_=new Uint16Array(n.HEAPU8.buffer,u,o),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(_),t.renderer_submitTriangles(y,r,w,o,p,m,h),t._free(y),t._free(w),n._free(c),n._free(u),n._free(d),n._free(f)}h&&t._free(h)}})}(e,t,r,u,s)}if(a){const t=e.getResource(zt);t&&t.setAddressableManifest(a)}}class ls{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&(s.endsWith(".skel")?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));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(()=>{}));await Promise.all(r);const o=[];for(const e of s){if(!e.endsWith(".bmfont"))continue;const t=this.textCache_.get(e);if(t)try{const n=JSON.parse(t),s="label-atlas"===n.type?n.generatedFnt:n.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(()=>{}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class cs{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(!this.app_)return;let e="fetch scene";try{const t=await i(this.sceneUrl_);if(!t.ok)throw new Error(`Failed to fetch scene: ${t.status}`);e="parse scene JSON";const n=await t.json();e="prefetch assets";const s=new ls(this.baseUrl_);await s.prefetch(n);let r=null;const o=this.app_.__spineInitPromise;if(o){e="init spine";r=(await o).controller.raw}e="loadRuntimeScene",await as(this.app_,this.app_.wasmModule,n,s,r),e="ensureCamera",this.ensureCamera()}catch(t){const n=t instanceof Error?t.message:String(t),s=t instanceof Error?t.stack:"";throw console.error(`[PreviewPlugin] Failed at step "${e}": ${n}\n${s}`),new Error(`[PreviewPlugin:${e}] ${n}`)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([W]);for(const s of n){if(e.get(s,W).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const s=e.getEntitiesWithComponents([O]);for(const r of s){const s=e.get(r,O);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,L,o);const i={isActive:!0,projectionType:1,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3};e.insert(r,W,i)}}}const us={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Mn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Mn.getTargetTexture(n),width:e.width,height:e.height}},release(e){Mn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Mn.releaseRenderTarget(e._handle),us.create({width:t,height:n,depth:!0})),begin(e,t){Mn.begin(t,e._handle)},end(){Mn.end()},getDepthTexture:e=>Mn.getTargetDepthTexture(e._handle)};let ds=!1;function hs(e){ds=e}function fs(){return ds}function ps(){return!ds}e=f;export{zn as App,Lt as AssetPlugin,$t as AssetServer,zt as Assets,kt as AsyncCache,V as BitmapText,dt as BlendMode,M as BodyType,P as BoxCollider,Ge as Button,Ye as ButtonState,W as Camera,O as Canvas,E as CapsuleCollider,X as Children,C as CircleCollider,le as Commands,ue as CommandsInstance,an as DataType,sn as Draw,ce as EntityCommands,Fn as GLDebug,mn as Geometry,p as INVALID_ENTITY,g as INVALID_FONT,m as INVALID_TEXTURE,xe as Input,ve as InputPlugin,we as InputState,Xe as Interactable,L as LocalTransform,xt as Material,At as MaterialLoader,re as Mut,G as Name,j as Parent,ss as Physics,Kn as PhysicsEvents,ts as PhysicsPlugin,xn as PostProcess,jt as PrefabServer,Xt as Prefabs,Vt as PrefabsPlugin,cs as PreviewPlugin,ie as Query,ae as QueryInstance,$n as RenderPipeline,bn as RenderStage,us as RenderTexture,Mn as Renderer,Z as Res,ee as ResMut,S as RigidBody,de as Schedule,tt as ScreenSpace,Tt as ShaderSources,Y as SpineAnimation,H as Sprite,ye as SystemRunner,Te as Text,Ce as TextAlign,it as TextInput,at as TextInputPlugin,Me as TextOverflow,Be as TextPlugin,Ae as TextRenderer,Ee as TextVerticalAlign,se as Time,Ke as UICameraInfo,qe as UIEventQueue,Je as UIEvents,Ve as UIInteraction,Ze as UIInteractionPlugin,rt as UILayoutPlugin,ke as UIMask,Ne as UIMaskPlugin,Re as UIRect,N as Velocity,ls as WebAssetProvider,Pe as World,D as WorldTransform,ge as addStartupSystem,me as addSystem,_e as addSystemToSchedule,Dt as assetPlugin,kn as clearDrawCallbacks,I as clearUserComponents,x as color,nt as computeUIRectLayout,Oe as createMaskProcessor,Ln as createWebApp,F as defineComponent,Q as defineResource,fe as defineSystem,U as defineTag,It as findEntityByName,Dn as flushPendingSystems,J as getComponentDefaults,t as getPlatform,s as getPlatformType,B as getUserComponent,Zt as initDrawAPI,An as initGLDebugAPI,hn as initGeometryAPI,_t as initMaterialAPI,_n as initPostProcessAPI,Cn as initRendererAPI,be as inputPlugin,Wt as instantiatePrefab,$e as intersectRects,Le as invertMatrix4,z as isBuiltinComponent,fs as isEditor,n as isPlatformInitialized,ps as isRuntime,ht as isTextureRef,r as isWeChat,o as isWeb,Ut as loadComponent,Jn as loadPhysicsModule,as as loadRuntimeScene,Rt as loadSceneData,Ft as loadSceneWithAssets,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,He as pointInWorldRect,Yt as prefabsPlugin,v as quat,Bn as registerDrawCallback,Ht as registerEmbeddedAssets,Mt as registerMaterialCallback,De as screenToWorld,hs as setEditorMode,en as shutdownDrawAPI,Rn as shutdownGLDebugAPI,fn as shutdownGeometryAPI,yt as shutdownMaterialAPI,yn as shutdownPostProcessAPI,En as shutdownRendererAPI,ut as textInputPlugin,Ie as textPlugin,et as uiInteractionPlugin,ot as uiLayoutPlugin,je as uiMaskPlugin,In as unregisterDrawCallback,Bt as updateCameraAspectRatio,_ as vec2,y as vec3,w as vec4,ze as worldRectToScreen};
//# sourceMappingURL=index.js.map
diff --git a/sdk/src/asset/AssetServer.ts b/sdk/src/asset/AssetServer.ts
index 678e12210..157e45baf 100644
--- a/sdk/src/asset/AssetServer.ts
+++ b/sdk/src/asset/AssetServer.ts
@@ -462,6 +462,10 @@ export class AssetServer {
}
}
+ resolveAddress(address: string): AddressableManifestAsset | undefined {
+ return this.addressIndex_.get(address);
+ }
+
async load<T extends AddressableAssetType = AddressableAssetType>(
address: string
): Promise<AddressableResultMap[T]> {
diff --git a/sdk/src/prefabServer.ts b/sdk/src/prefabServer.ts
index 74577b7f3..b6265250f 100644
--- a/sdk/src/prefabServer.ts
+++ b/sdk/src/prefabServer.ts
@@ -23,12 +23,14 @@ export class PrefabServer {
this.assetServer_ = assetServer;
}
- async instantiate(path: string, options?: {
+ async instantiate(pathOrAddress: string, options?: {
baseUrl?: string;
parent?: Entity;
overrides?: PrefabOverride[];
}): Promise<InstantiatePrefabResult> {
- const prefab = await this.assetServer_.loadPrefab(path, options?.baseUrl);
+ const resolved = this.assetServer_.resolveAddress(pathOrAddress);
+ const prefabPath = resolved ? resolved.path : pathOrAddress;
+ const prefab = await this.assetServer_.loadPrefab(prefabPath, options?.baseUrl);
return instantiatePrefab(this.world_, prefab, {
assetServer: this.assetServer_,
assetBaseUrl: options?.baseUrl,