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.

refactor: replace hand-written CppRegistry with generated types and eliminate type casts

esengine0b674748d440
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.js
index 2997eaf52..441185118 100644
--- a/desktop/public/sdk/cjs/esengine.wechat.js
+++ b/desktop/public/sdk/cjs/esengine.wechat.js
@@ -1,2 +1,2 @@
-"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function s(e,s){return t().fetch(e,s)}async function r(e){return t().readFile(e)}async function n(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,s){return t().createCanvas(e,s)}function a(){return t().now()}function l(e,t){return new Promise((s,r)=>{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,r={};if(e.header)for(const t of Object.keys(e.header))r[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:r,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{r(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function c(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const s=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(s,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${s}": ${t}`)}}let u=null;function h(){return u||(u=wx.getFileSystemManager()),u}function d(e){return new Promise((t,s)=>{h().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function p(e,t="utf-8"){return new Promise((s,r)=>{h().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function f(e){return new Promise(t=>{h().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}let m=null,g=null;function x(e){return new Promise((t,s)=>{const r=wx.createImage();r.onload=()=>t(r),r.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),r.src=e})}function y(e){const{width:t,height:s}=e,{ctx:r}=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,s);r.clearRect(0,0,t,s),r.drawImage(e,0,0);const n=r.getImageData(0,0,t,s);return{width:t,height:s,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 d(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 s=wx.createCanvas();return s.width=e,s.height=t,s}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{const s=t.touches[0];s&&e.onPointerDown(0,s.clientX,s.clientY)}),wx.onTouchMove(t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX,s.clientY)}),wx.onTouchEnd(()=>{e.onPointerUp(0)})}},v=4294967295,b=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}),M={Static:0,Kinematic:1,Dynamic:2};let E=0;function R(e,t){const s=++E;return{_id:Symbol(`Component_${s}_${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 s=I(),r=s.get(e);if(r)return r;const n=R(e,t);return s.set(e,n),k(e,t,!1),n}function F(e){const t=I(),s=t.get(e);if(s)return s;const r=R(e,{});return t.set(e,r),k(e,{},!0),r}function U(e){return I().get(e)}function k(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}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 z=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}}),L=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}}),$=W("Sprite",{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),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}}),j=W("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),N=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:b}),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:z,WorldTransform:L,Sprite:$,Camera:H,Canvas:O,Velocity:j,Parent:N,Children:X,BitmapText:V,SpineAnimation:G,RigidBody:P,BoxCollider:C,CircleCollider:T,CapsuleCollider:A};let K=0;function J(e,t){const s=++K;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_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=J({delta:0,elapsed:0,frameCount:0},"Time");function se(e){return"object"==typeof e&&null!==e&&"mut"===e._type}class re{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>se(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with)}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,r=this.world_.getEntitiesWithComponents(this.allRequired_),n=s.length,o=e.length>0,i=t.length>0,a=new Array(n+1);let l=null,c=[];try{for(const u of r){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 s=0;s<t.length;s++)if(this.world_.has(u,t[s])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<n;e++)a[e+1]=this.world_.get(u,s[e]);if(o){for(let t=0;t<e.length;t++){const r=e[t];c.push({component:s[r],data:a[r+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,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class 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 s;return s=D(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class 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,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];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 s of e.components)this.world_.insert(t,s.component,s.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,s){const r=++ae;return{_id:Symbol(`System_${r}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${r}`}}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 s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);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 re(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 he{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 de=J(new he,"Input");class pe{constructor(e){this.target_=e??null}build(e){const s=new he;e.insertResource(de,s),t().bindInputEvents({onKeyDown(e){s.keysDown.has(e)||s.keysPressed.add(e),s.keysDown.add(e)},onKeyUp(e){s.keysDown.delete(e),s.keysReleased.add(e)},onPointerMove(e,t){s.mouseX=e,s.mouseY=t},onPointerDown(e,t,r){s.mouseX=t,s.mouseY=r,s.mouseButtons.add(e),s.mouseButtonsPressed.add(e)},onPointerUp(e){s.mouseButtons.delete(e),s.mouseButtonsReleased.add(e)},onWheel(e,t){s.scrollDeltaX+=e,s.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.Last,le([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const fe=new pe;function me(e){if(null==e||"object"!=typeof e||Array.isArray(e))return e;const t=e;if("r"in t&&"g"in t&&"b"in t&&"a"in t&&!("x"in t))return{x:t.r,y:t.g,z:t.b,w:t.a};const s={};for(const e of Object.keys(t)){const r=t[e];s[e]=null==r||"object"!=typeof r||Array.isArray(r)?r:me(r)}return s}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,s){return D(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}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,s){const r={...t._default,...s};if(this.cppRegistry_){const s=`add${t._cppName}`;this.cppRegistry_[s].call(this.cppRegistry_,e,me(r))}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const s=`get${t._cppName}`;return this.cppRegistry_[s].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const s=`has${t._cppName}`;return this.cppRegistry_[s].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const s=`remove${t._cppName}`;this.cppRegistry_[s].call(this.cppRegistry_,e)}insertScript(e,t,s){const r=t.create(s);return this.getStorage(t).set(e,r),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e)}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,s=1/0;for(const r of e)if(!D(r)){const e=this.tsStorage_.get(r._id),n=e?e.size:0;n<s&&(s=n,t=e??null)}const r=[],n=t?t.keys():this.entities_;for(const t of n){let s=!0;for(const r of e)if(!this.has(t,r)){s=!1;break}s&&r.push(t)}return r}}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,dirty:!0});class ve{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 s=this.ctx,r=this.canvas;s.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),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),p=n?Math.ceil(o):h+2*u,f=n?Math.ceil(i):d+2*u;if(n&&e.overflow===exports.TextOverflow.Ellipsis&&d>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(r.width<p||r.height<f){const e=Math.max(r.width,this.nextPowerOf2(p)),t=Math.max(r.height,this.nextPowerOf2(f));r.width=e,r.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;s.clearRect(0,0,r.width,r.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${m}, ${g}, ${x}, ${y})`,n&&e.overflow===exports.TextOverflow.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.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 v=w;for(const t of l){let r;switch(e.align){case exports.TextAlign.Left:r=u;break;case exports.TextAlign.Center:r=p/2;break;case exports.TextAlign.Right:r=p-u;break;default:r=u}s.fillText(t,r,v),v+=c}n&&e.overflow===exports.TextOverflow.Clip&&s.restore();const b=s.getImageData(0,0,p,f),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),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 s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const r=this.cache.get(e);if(r){this.module.getResourceManager().releaseTexture(r.textureHandle)}const n=this.renderText(t,s);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[s,r]of this.cache)e(s)||(t.releaseTexture(r.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),r=[];for(const e of s){if(!e){r.push("");continue}let s="";for(const n of e){const e=s+n;this.ctx.measureText(e).width>t&&s?(r.push(s),s=n):s=e}s&&r.push(s)}return r.length>0?r:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),r=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,r)}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 be=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}});class Se{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new ve(t),r=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,le([],()=>{s.cleanupOrphaned(e=>r.valid(e)&&r.has(e,we));const e=r.getEntitiesWithComponents([we]);for(const t of e){const e=r.get(t,we);if(!e.dirty)continue;r.has(t,$)||r.insert(t,$,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const n=r.has(t,be)?r.get(t,be):null,o=s.renderForEntity(t,e,n),i=r.get(t,$);i.texture=o.textureHandle,i.size.x=o.width,i.size.y=o.height,i.uvOffset.x=0,i.uvOffset.y=0,i.uvScale.x=1,i.uvScale.y=1,r.insert(t,$,i),e.dirty=!1}}))}}const Pe=new Se,Ce=B("UIMask",{enabled:!0});function Te(e,t){const s=Math.max(e.x,t.x),r=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:s,y:r,w:Math.max(0,n-s),h:Math.max(0,o-r)}}function Ae(e,t,s,r,n,o,i,a,l,c,u){const h=e-s*n,d=e+s*(1-n),p=t-r*o,f=t+r*(1-o);function m(e,t){const s=i[0]*e+i[4]*t+i[12],r=i[1]*e+i[5]*t+i[13],n=i[3]*e+i[7]*t+i[15];return[a+(.5*(s/n)+.5)*c,l+(.5*(r/n)+.5)*u]}const[g,x]=m(h,p),[y,_]=m(d,f),w=Math.min(g,y),v=Math.max(g,y),b=Math.min(x,_),S=Math.max(x,_);return{x:Math.round(w),y:Math.round(b),w:Math.round(v-w),h:Math.round(S-b)}}function Me(e,t){const s=t??new Float32Array(16),r=e[0],n=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],h=e[8],d=e[9],p=e[10],f=e[11],m=e[12],g=e[13],x=e[14],y=e[15],_=r*l-n*a,w=r*c-o*a,v=r*u-i*a,b=n*c-o*l,S=n*u-i*l,P=o*u-i*c,C=h*g-d*m,T=h*x-p*m,A=h*y-f*m,M=d*x-p*g,E=d*y-f*g,R=p*y-f*x;let I=_*R-w*E+v*M+b*A-S*T+P*C;return 0===I||(I=1/I,s[0]=(l*R-c*E+u*M)*I,s[1]=(o*E-n*R-i*M)*I,s[2]=(g*P-x*S+y*b)*I,s[3]=(p*S-d*P-f*b)*I,s[4]=(c*A-a*R-u*T)*I,s[5]=(r*R-o*A+i*T)*I,s[6]=(x*v-m*P-y*w)*I,s[7]=(h*P-p*v+f*w)*I,s[8]=(a*E-l*A+u*C)*I,s[9]=(n*A-r*E-i*C)*I,s[10]=(m*S-g*v+y*_)*I,s[11]=(d*v-h*S-f*_)*I,s[12]=(l*T-a*M-c*C)*I,s[13]=(r*M-n*T+o*C)*I,s[14]=(g*w-m*b-x*_)*I,s[15]=(h*b-d*w+p*_)*I),s}function Ee(e,t,s,r,n,o,i){const a=(e-r)/o*2-1,l=(t-n)/i*2-1,c=s[0]*a+s[4]*l+s[12],u=s[1]*a+s[5]*l+s[13],h=s[3]*a+s[7]*l+s[15];return{x:c/h,y:u/h}}function Re(e,t,s,r,n,o,i,a){return e>=s-n*i&&e<=s+n*(1-i)&&t>=r-o*a&&t<=r+o*(1-a)}function Ie(e,t,s,r,n,o,i){if(!e.has(t,be)||!e.has(t,L))return null;const a=e.get(t,be),l=e.get(t,L),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return Ae(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,s,r,n,o,i)}function Be(e,t){return(s,r,n,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Ce]);if(0!==l.length)try{!function(e,t,s,r,n,o,i,a,l){const c=new Set;for(const e of r){t.get(e,Ce).enabled&&c.add(e)}const u=[];for(const e of r){if(!c.has(e))continue;let s=!0,r=e;for(;t.has(r,N);){const e=t.get(r,N);if(c.has(e.entity)){s=!1;break}r=e.entity}s&&u.push(e)}function h(r,u){const d=e.getChildEntities(s,r);for(const s of d){let r=u;if(c.has(s)){const e=Ie(t,s,n,o,i,a,l);e&&(r=Te(u,e))}e.renderer_setEntityClipRect(s,r.x,r.y,r.w,r.h),h(s,r)}}for(const e of u){const s=Ie(t,e,n,o,i,a,l);s&&h(e,s)}}(e,t,s,l,r,n,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class Fe{build(e){if(!e.wasmModule)return;const t=e.pipeline_;t&&t.setMaskProcessor(Be(e.wasmModule,e.world))}}const Ue=new Fe,ke=B("Interactable",{enabled:!0}),We=B("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var De;exports.ButtonState=void 0,(De=exports.ButtonState||(exports.ButtonState={}))[De.Normal=0]="Normal",De[De.Hovered=1]="Hovered",De[De.Pressed=2]="Pressed",De[De.Disabled=3]="Disabled";const ze=B("Button",{state:exports.ButtonState.Normal,transition:null});class Le{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(s=>s.entity===e&&s.type===t)}}const $e=J(new Le,"UIEvents"),He=J({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"),Oe=new Float32Array(16);class je{build(e){const t=e.world,s=new Le;e.insertResource($e,s);let r=null,n=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,le([Q(de),Q(He)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([We]);for(const e of i){const s=t.get(e,We);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a="undefined"!=typeof window&&window.devicePixelRatio||1,l=e.mouseX*a,c=o.screenH-e.mouseY*a;Me(o.viewProjection,Oe);const u=Ee(l,c,Oe,o.vpX,o.vpY,o.vpW,o.vpH),h=t.getEntitiesWithComponents([ke,be,L]);let d=null,p=-1/0;for(const e of h){t.has(e,We)||t.insert(e,We);if(!t.get(e,ke).enabled)continue;const s=t.get(e,L),r=t.get(e,be),n=r.size.x*s.scale.x,o=r.size.y*s.scale.y;if(Re(u.x,u.y,s.position.x,s.position.y,n,o,r.pivot.x,r.pivot.y)){let s=0;t.has(e,$)&&(s=t.get(e,$).layer),s>=p&&(p=s,d=e)}}if(r!==d){if(null!==r&&t.valid(r)&&t.has(r,We)){t.get(r,We).hovered=!1,s.emit(r,"hover_exit")}if(null!==d){t.get(d,We).hovered=!0,s.emit(d,"hover_enter")}r=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,We);e.pressed=!0,e.justPressed=!0,n=d,s.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==n){if(t.valid(n)&&t.has(n,We)){const e=t.get(n,We);e.pressed=!1,e.justReleased=!0,s.emit(n,"release"),n===r&&s.emit(n,"click")}n=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(exports.Schedule.Update,le([],()=>{const e=t.getEntitiesWithComponents([ze]);for(const s of e){if(t.has(s,ke)||t.insert(s,ke,{enabled:!0}),!t.has(s,We))continue;const e=t.get(s,We),r=t.get(s,ze),n=t.get(s,ke),o=r.state;if(n.enabled?e.pressed?r.state=exports.ButtonState.Pressed:e.hovered?r.state=exports.ButtonState.Hovered:r.state=exports.ButtonState.Normal:r.state=exports.ButtonState.Disabled,o!==r.state&&r.transition&&t.has(s,$)){const e=t.get(s,$),n=r.transition;switch(r.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(s,$,e)}}},{name:"ButtonSystem"}))}}const Ne=new je,Xe=F("ScreenSpace");function Ve(e,t,s,r,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,h=o.bottom+t.y*a;let d,p,f,m;if(l===c&&u===h){const e=l+s.x,t=u+s.y,r=.5*n.x,o=.5*n.y;d=e-r,p=t-o,f=e+r,m=t+o}else d=l+s.x,p=u+s.y,f=c+r.x,m=h+r.y;return{centerX:.5*(d+f),centerY:.5*(p+m),width:f-d,height:m-p,rect:{left:d,bottom:p,right:f,top:m}}}function Ge(e,t,s,r,n,o){if(!e.has(t,be))return;const i=e.get(t,be),a=Ve(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,s);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,z);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-r,l.position.y=a.centerY-n),e.insert(t,z,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)&&Ge(e,t,a.rect,a.centerX,a.centerY,!1)}class Ye{build(e){const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,le([Q(He)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},r=.5*(s.left+s.right),n=.5*(s.bottom+s.top),o=t.getEntitiesWithComponents([Xe,be,z]);for(const e of o)Ge(t,e,s,r,n,!0)},{name:"UILayoutSystem"}))}}const qe=new Ye,Ke=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 Je{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,r=new Map,n=i(512,64),o=n.getContext("2d",{willReadFrequently:!0});let a=null,l=!1,c=!0,u=0,h=0;const d=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||!s.valid(a))return;const t=s.get(a,Ke);if(t.readOnly)return;let r=d.value;if(t.maxLength>0&&r.length>t.maxLength&&(r=r.substring(0,t.maxLength),d.value=r),r!==t.value){t.value=r;e.getResource($e).emit(a,"change")}t.cursorPos=d.selectionStart??r.length,t.dirty=!0,g()}function f(e){if(a===e)return;m();const t=s.get(e,Ke);t.readOnly||(a=e,t.focused=!0,t.dirty=!0,d.value=t.value,d.selectionStart=t.cursorPos,d.selectionEnd=t.cursorPos,d.focus(),g())}function m(){if(null!==a&&s.valid(a)&&s.has(a,Ke)){const e=s.get(a,Ke);e.focused=!1,e.dirty=!0}a=null,d.blur()}function g(){c=!0,u=0}function x(e,i,a,l){(n.width<a||n.height<l)&&(n.width=Ze(Math.max(n.width,a)),n.height=Ze(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 h=0===i.value.length,d=h?i.placeholder:i.password?"●".repeat(i.value.length):i.value,p=h?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=Qe(o,d,a-2*m);let t=m;for(const s of e)o.fillText(s,m,t),t+=f}else{const e=(l-i.fontSize)/2;o.fillText(d,m,e)}if(i.focused&&c){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,s,r;if(i.multiline){const e=Qe(o,i.value.substring(0,i.cursorPos),a-2*m),n=e.length>0?e[e.length-1]:"";t=m+o.measureText(n).width,s=m+(e.length-1)*f,r=f}else t=m+o.measureText(e).width,s=(l-i.fontSize)/2,r=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,s,2,r)}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=r.get(e);void 0!==w&&y.releaseTexture(w);const v=y.createTexture(a,l,_,x.length,1,!0);r.set(e,v),t._free(_);const b=s.get(e,$);b.texture=v,b.size.x=a,b.size.y=l,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},s.insert(e,$,b)}d.addEventListener("input",()=>{l||null===a||p()}),d.addEventListener("compositionstart",()=>{l=!0}),d.addEventListener("compositionend",()=>{l=!1,p()}),d.addEventListener("keydown",t=>{if(null===a)return;if("Escape"===t.key)return void m();const r=s.get(a,Ke);if("Enter"===t.key&&!r.multiline){t.preventDefault();return e.getResource($e).emit(a,"submit"),void m()}}),d.addEventListener("blur",()=>{if(null!==a&&s.valid(a)&&s.has(a,Ke)){const e=s.get(a,Ke);e.focused=!1,e.dirty=!0}a=null}),e.addSystemToSchedule(exports.Schedule.PreUpdate,le([Q($e)],e=>{const t=s.getEntitiesWithComponents([Ke,ke]);for(const e of t){if(!s.has(e,We))continue;if(s.get(e,We).justPressed)return void f(e)}if(null!==a){const e=s.getEntitiesWithComponents([ke]);for(const t of e){if(s.has(t,Ke))continue;if(!s.has(t,We))continue;if(s.get(t,We).justPressed)return void m()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(exports.Schedule.PreUpdate,le([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),n=0===h?0:(e-h)/1e3;if(h=e,null!==a&&(u+=n,u>=.5&&(u-=.5,c=!c,null!==a&&s.valid(a)&&s.has(a,Ke)))){s.get(a,Ke).dirty=!0}const o=t.getResourceManager();for(const[e,t]of r)s.valid(e)&&s.has(e,Ke)||(o.releaseTexture(t),r.delete(e));const i=s.getEntitiesWithComponents([Ke,be]);for(const e of i){const t=s.get(e,Ke);if(!t.dirty)continue;const r=s.get(e,be),n=Math.ceil(r.size.x),o=Math.ceil(r.size.y);n<=0||o<=0||(s.has(e,$)||s.insert(e,$,{texture:v,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 Qe(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const r=t.split("\n"),n=[];for(const t of r){if(!t){n.push("");continue}let r="";for(const o of t){const t=r+o;e.measureText(t).width>s&&r?(n.push(r),r=o):r=t}r&&n.push(r)}return n.length>0?n:[""]}function Ze(e){let t=1;for(;t<e;)t*=2;return t}const et=new Je;var tt;function st(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(tt=exports.BlendMode||(exports.BlendMode={}))[tt.Normal=0]="Normal",tt[tt.Additive=1]="Additive",tt[tt.Multiply=2]="Multiply",tt[tt.Screen=3]="Screen",tt[tt.PremultipliedAlpha=4]="PremultipliedAlpha";let rt=null,nt=null,ot=1;const it=new Map;function at(e){rt=e,nt=e.getResourceManager(),xt()}function lt(){0!==dt&&rt&&(rt._free(dt),dt=0),it.clear(),ot=1,ht=!1,nt=null,rt=null}function ct(){if(!nt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return nt}const ut={createShader:(e,t)=>ct().createShader(e,t),releaseShader(e){e>0&&ct().releaseShader(e)},create(e){const t=ot++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,r]of Object.entries(e.uniforms))s.uniforms.set(t,r);return it.set(t,s),t},get:e=>it.get(e),setUniform(e,t,s){const r=it.get(e);r&&r.uniforms.set(t,s)},getUniform(e,t){const s=it.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=it.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=it.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=it.get(e);s&&(s.depthTest=t)},getShader(e){const t=it.get(e);return t?.shader??0},release(e){it.delete(e)},isValid:e=>it.has(e),createFromAsset(e,t){const s={};for(const[t,r]of Object.entries(e.properties))if("number"==typeof r)s[t]=r;else if("object"==typeof r&&null!==r){const e=r;"a"in e?s[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(s[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:s,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=it.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=ot++,r={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return it.set(s,r),s},toAssetData(e,t){const s=it.get(e);if(!s)return null;const r={};for(const[e,t]of s.uniforms)r[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:s.blendMode,depthTest:s.depthTest,properties:r}},getUniforms(e){const t=it.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let ht=!1,dt=0;const pt=4096,ft=new Map;let mt=null;function gt(e){const t=(0===dt&&rt&&(dt=rt._malloc(pt)),dt);if(0===t||!rt)return{ptr:0,count:0};let s=0,r=0;const n=rt.HEAPU8,o=rt.HEAPU32,i=rt.HEAPF32;for(const[a,l]of e){if(s+128>pt)break;let e=ft.get(a);e||(mt||(mt=new TextEncoder),e=mt.encode(a),ft.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+s>>2]=c,s+=4,n.set(e,t+s),s+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+s>>2]=h,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=d[e],s+=4;r++}return{ptr:t,count:r}}function xt(){if(!rt||ht)return;rt.materialDataProvider=(e,t,s,r,n)=>{const o=it.get(e);if(!o)return rt.HEAPU32[t>>2]=0,rt.HEAPU32[s>>2]=0,rt.HEAPU32[r>>2]=0,void(rt.HEAPU32[n>>2]=0);rt.HEAPU32[t>>2]=o.shader,rt.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=gt(o.uniforms);rt.HEAPU32[r>>2]=i,rt.HEAPU32[n>>2]=a},ht=!0}const yt={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 _t{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 s=this.pending_.get(e);if(s)return s;const r=this.loadInternal(e);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)}release(e){const t=this.cache_.get(e);t&&(ut.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())ut.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await o(t))throw new Error(`Material file not found: ${t}`);const s=await n(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const r=JSON.parse(s);if("material"!==r.type)throw new Error(`Invalid material file type: ${r.type}`);const i=this.resolveShaderPath(e,r.shader),a=await this.shaderLoader_.load(i);return{handle:ut.createFromAsset(r,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}function wt(e,t){const s=new Map;for(const r of t.entities){const t=e.spawn();s.set(r.id,t),e.insert(t,Y,{value:r.name});for(const s of r.components)bt(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)}return s}async function vt(e,t,s){const r=new Map,n=s?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();r.set(i.id,t),e.insert(t,Y,{value:i.name});for(const r of i.components){if("Sprite"===r.type&&n){const e=r.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,r=t.startsWith("data:")?t:s?.assetBaseUrl?`${s.assetBaseUrl}/${t}`:`/${t}`;try{const s=await n.loadTexture(r);e.texture=s.handle,o.set(t,r)}catch(t){console.warn(`Failed to load texture: ${r}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,s?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("BitmapText"===r.type&&n){const e=r.data;if("string"==typeof e.font&&e.font)try{const t=await n.loadBitmapFont(e.font,s?.assetBaseUrl);e.font=t}catch(t){console.warn(`Failed to load bitmap font: ${e.font}`,t),e.font=0}}if("SpineAnimation"===r.type&&n){const e=r.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await n.loadSpine(t,o,s?.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,s?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}bt(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)}if(n&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&n.setTextureMetadataByPath(t,s.sliceBorder)}return r}function bt(e,t,s){const r=s.data;switch(s.type){case"LocalTransform":e.insert(t,z,r);break;case"Sprite":e.insert(t,$,r);break;case"Camera":e.insert(t,H,r);break;case"Canvas":e.insert(t,O,r);break;case"Text":e.insert(t,we,r);break;case"BitmapText":e.insert(t,V,r);break;case"SpineAnimation":e.insert(t,G,r);break;case"UIRect":{const s=r;s.anchor&&!s.anchorMin&&(s.anchorMin={...s.anchor},s.anchorMax={...s.anchor},delete s.anchor),e.insert(t,be,s);break}case"UIMask":e.insert(t,Ce,r);break;case"Interactable":e.insert(t,ke,r);break;case"Button":e.insert(t,ze,r);break;case"RigidBody":e.insert(t,P,r);break;case"BoxCollider":e.insert(t,C,r);break;case"CircleCollider":e.insert(t,T,r);break;case"CapsuleCollider":e.insert(t,A,r);break;default:{const n=U(s.type);n?e.insert(t,n,r):console.warn(`Unknown component type: ${s.type}`);break}}}class St{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const s=this.cache_.get(e);if(void 0!==s)return s;const r=this.pending_.get(e);if(r)return r;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 Pt{constructor(e){this.textureCache_=new St,this.shaderCache_=new St,this.jsonCache_=new St,this.textCache_=new St,this.binaryCache_=new St,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new St,this.embedded_=new Map,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 _t(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s)}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 s of[!0,!1]){const r=this.textureCacheKey(e,s),n=this.textureCache_.get(r);n&&(t.releaseTexture(n.handle),this.textureCache_.delete(r))}}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.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 s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}async loadSpine(e,t,s){const r=`${e}:${t}`;if(this.loadedSpines_.has(r))return{success:!0};try{const n=this.resolveUrl(t,s),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,r=this.resolveUrl(t,s);try{const e=await this.loadTextureRaw(r);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,s),c=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);return this.writeToVirtualFS(e,c)?(this.loadedSpines_.add(r),{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 s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>e.endsWith(".bmfont")?this.loadBmfontAsset(s):this.loadFntFile(s))}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),r="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!r)throw new Error("Invalid bmfont asset: no fnt file specified");const n=s?`${s}/${r}`:r;return this.loadFntFile(n)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const r=s[1],n=e.substring(0,e.lastIndexOf("/")),o=n?`${n}/${r}`:r,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return vt(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},s=[];if(e.textures)for(const r of e.textures)s.push(this.loadTexture(r).then(e=>{t.textures.set(r,e)}));if(e.materials)for(const r of e.materials)s.push(this.loadMaterial(r).then(e=>{t.materials.set(r,e)}));if(e.spine)for(const r of e.spine){const e=`${r.skeleton}:${r.atlas}`;s.push(this.loadSpine(r.skeleton,r.atlas,r.baseUrl).then(s=>{t.spine.set(e,s)}))}if(e.json)for(const r of e.json)s.push(this.loadJson(r).then(e=>{t.json.set(r,e)}));if(e.text)for(const r of e.text)s.push(this.loadText(r).then(e=>{t.text.set(r,e)}));if(e.binary)for(const r of e.binary)s.push(this.loadBinary(r).then(e=>{t.binary.set(r,e)}));return await Promise.all(s),t}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups)){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}async loadByAddress(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"json":return this.loadJson(e.path);case"text":return this.loadText(e.path);default:return this.loadBinary(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const r of e)switch(r.type){case"texture":s.push(this.loadTexture(r.path).then(e=>{t.textures.set(r.path,e)}));break;case"material":s.push(this.loadMaterial(r.path).then(e=>{t.materials.set(r.path,e)}));break;case"json":s.push(this.loadJson(r.path).then(e=>{t.json.set(r.path,e)}));break;case"text":s.push(this.loadText(r.path).then(e=>{t.text.set(r.path,e)}));break;default:s.push(this.loadBinary(r.path).then(e=>{t.binary.set(r.path,e)}))}return await Promise.all(s),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,r=this.embedded_.get(s)??s;return new Promise((s,n)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:s,height:r}=e,n=this.getWebGL2Context();return n?this.createTextureWebGL2(n,e,s,r,t):this.createTextureFallback(e,s,r,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,r,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,s,r),width:s,height:r}}createTextureFallback(e,t,s,r){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const n=this.ctx_.getImageData(0,0,t,s),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,s,a,o.length,1,r);return this.module_._free(a),{handle:l,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const r=255/s;e[t]=Math.min(255,Math.round(e[t]*r)),e[t+1]=Math.min(255,Math.round(e[t+1]*r)),e[t+2]=Math.min(255,Math.round(e[t+2]*r))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):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:r,fragment:i}=this.parseEsShader(s);if(!r||!i)throw new Error(`Invalid shader format: ${e}`);return ut.createShader(r,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const s=await n(t);return JSON.parse(s)}const r=await s(e);if(!r.ok)throw new Error(`Failed to fetch JSON: ${e} (${r.status})`);return r.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):n(t)}const r=await s(e);if(!r.ok)throw new Error(`Failed to fetch text: ${e} (${r.status})`);return r.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):r(t)}const n=await s(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 s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const r=s.split("/").filter(e=>e);let n="";for(const e of r){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 s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Ct=J(null,"Assets");class Tt{build(e){const t=e.wasmModule;t?e.insertResource(Ct,new Pt(t)):console.warn("AssetPlugin: No WASM module available")}}const At=new Tt;let Mt=null,Et=0,Rt=0,It=0;const Bt=new Float32Array(256);function Ft(e){Mt=e,Et=Mt._malloc(64),Rt=Mt._malloc(64),It=Mt._malloc(1024)}function Ut(){Mt&&(Et&&(Mt._free(Et),Et=0),Rt&&(Mt._free(Rt),Rt=0),It&&(Mt._free(It),It=0)),Mt=null}function kt(){if(!Mt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Mt}const Wt={r:1,g:1,b:1,a:1},Dt={begin(e){const t=kt();t.HEAPF32.set(e,Et/4),t.draw_begin(Et)},end(){kt().draw_end()},line(e,t,s,r=1){kt().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,r)},rect(e,t,s,r=!0){kt().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,r)},rectOutline(e,t,s,r=1){kt().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,r)},circle(e,t,s,r=!0,n=32){kt().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,r,n)},circleOutline(e,t,s,r=1,n=32){kt().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,r,n)},texture(e,t,s,r=Wt){kt().draw_texture(e.x,e.y,t.x,t.y,s,r.r,r.g,r.b,r.a)},textureRotated(e,t,s,r,n=Wt){kt().draw_textureRotated(e.x,e.y,t.x,t.y,s,r,n.r,n.g,n.b,n.a)},setLayer(e){kt().draw_setLayer(e)},setDepth(e){kt().draw_setDepth(e)},getDrawCallCount:()=>Mt?Mt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Mt?Mt.draw_getPrimitiveCount():0,setBlendMode(e){kt().draw_setBlendMode(e)},setDepthTest(e){kt().draw_setDepthTest(e)},drawMesh(e,t,s){const r=kt();r.HEAPF32.set(s,Rt/4),r.draw_mesh(e,t,Rt)},drawMeshWithMaterial(e,t,s){const r=kt(),n=ut.get(t);if(!n)return;if(Dt.setBlendMode(n.blendMode),Dt.setDepthTest(n.depthTest),0===n.uniforms.size)return void Dt.drawMesh(e,n.shader,s);r.HEAPF32.set(s,Rt/4);let o=0,i=0;for(const[e,t]of n.uniforms){const s=Lt(e);if(!(s<0)){if(st(t))Bt[o++]=10,Bt[o++]=s,Bt[o++]=t.slot??i++,Bt[o++]=t.textureId;else if("number"==typeof t)Bt[o++]=1,Bt[o++]=s,Bt[o++]=t;else if(Array.isArray(t)){Bt[o++]=t.length,Bt[o++]=s;for(let e=0;e<t.length;e++)Bt[o++]=t[e]}else"w"in t?(Bt[o++]=4,Bt[o++]=s,Bt[o++]=t.x,Bt[o++]=t.y,Bt[o++]=t.z,Bt[o++]=t.w):"z"in t?(Bt[o++]=3,Bt[o++]=s,Bt[o++]=t.x,Bt[o++]=t.y,Bt[o++]=t.z):(Bt[o++]=2,Bt[o++]=s,Bt[o++]=t.x,Bt[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(r.HEAPF32.set(Bt.subarray(0,o),It/4),r.draw_meshWithUniforms(e,n.shader,Rt,It,o)):r.draw_mesh(e,n.shader,Rt)}},zt={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 Lt(e){return zt[e]??-1}var $t;exports.DataType=void 0,($t=exports.DataType||(exports.DataType={}))[$t.Float=1]="Float",$t[$t.Float2=2]="Float2",$t[$t.Float3=3]="Float3",$t[$t.Float4=4]="Float4",$t[$t.Int=5]="Int",$t[$t.Int2=6]="Int2",$t[$t.Int3=7]="Int3",$t[$t.Int4=8]="Int4";let Ht=null,Ot=0,jt=0,Nt=0;function Xt(e){Ht=e,Ot=Ht._malloc(262144),jt=Ht._malloc(65536),Nt=Ht._malloc(256)}function Vt(){Ht&&(Ot&&Ht._free(Ot),jt&&Ht._free(jt),Nt&&Ht._free(Nt),Ot=0,jt=0,Nt=0),Ht=null}function Gt(){if(!Ht)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Ht}const Yt={create(e){const t=Gt(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const r=e.vertices.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);t.HEAPF32.set(e.vertices,Ot/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,Nt,n).set(o),t.geometry_init(s,Ot,r,Nt,n,e.dynamic??!1),e.indices){const r=e.indices.length;if(4*r>65536)throw new Error(`Index data too large: ${r} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,jt,r).set(e.indices),t.geometry_setIndices16(s,jt,r)}else{new Uint32Array(t.HEAPU8.buffer,jt,r).set(e.indices),t.geometry_setIndices32(s,jt,r)}}return s},updateVertices(e,t,s=0){const r=Gt(),n=t.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);r.HEAPF32.set(t,Ot/4),r.geometry_updateVertices(e,Ot,n,s)},release(e){e>0&&Gt().geometry_release(e)},isValid:e=>!(!Ht||e<=0)&&Ht.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,r=t/2;return Yt.create({vertices:new Float32Array([-s,-r,0,0,s,-r,1,0,s,r,1,1,-s,r,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],r=[];s.push(0,0,.5,.5);for(let r=0;r<=t;r++){const n=r/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;s.push(o,i,a,l)}for(let e=1;e<=t;e++)r.push(0,e,e+1);return Yt.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(r)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,r=-1/0,n=-1/0;for(const o of e)t=Math.min(t,o.x),s=Math.min(s,o.y),r=Math.max(r,o.x),n=Math.max(n,o.y);const o=[];for(const i of e){const e=(i.x-t)/(r-t),a=(i.y-s)/(n-s);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return Yt.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 qt=null;function Kt(e){qt=e}function Jt(){qt&&Zt.isInitialized()&&Zt.shutdown(),qt=null}function Qt(){if(!qt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return qt}const Zt={init:(e,t)=>Qt().postprocess_init(e,t),shutdown(){Qt().postprocess_shutdown()},resize(e,t){Qt().postprocess_resize(e,t)},addPass:(e,t)=>Qt().postprocess_addPass(e,t),removePass(e){Qt().postprocess_removePass(e)},setEnabled(e,t){Qt().postprocess_setPassEnabled(e,t)},isEnabled:e=>Qt().postprocess_isPassEnabled(e),setUniform(e,t,s){Qt().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){Qt().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){Qt().postprocess_begin()},end(){Qt().postprocess_end()},getPassCount:()=>Qt().postprocess_getPassCount(),isInitialized:()=>!!qt&&qt.postprocess_isInitialized(),setBypass(e){Qt().postprocess_setBypass(e)},isBypassed:()=>!qt||qt.postprocess_isBypassed(),createBlur:()=>ut.createShader(es,"#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:()=>ut.createShader(es,"#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:()=>ut.createShader(es,"#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:()=>ut.createShader(es,"#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")},es="#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 ts;exports.RenderStage=void 0,(ts=exports.RenderStage||(exports.RenderStage={}))[ts.Background=0]="Background",ts[ts.Opaque=1]="Opaque",ts[ts.Transparent=2]="Transparent",ts[ts.Overlay=3]="Overlay";let ss=null,rs=0;function ns(e){ss=e,rs=ss._malloc(64)}function os(){ss&&rs&&(ss._free(rs),rs=0),ss=null}const is={init(e,t){ss?.renderer_init(e,t)},resize(e,t){ss?.renderer_resize(e,t)},begin(e,t){ss&&rs&&(ss.HEAPF32.set(e,rs/4),ss.renderer_begin(rs,t??0))},flush(){ss?.renderer_flush()},end(){ss?.renderer_end()},submitSprites(e){ss&&ss.renderer_submitSprites(e._cpp)},submitBitmapText(e){ss&&ss.renderer_submitBitmapText(e._cpp)},submitSpine(e){ss&&ss.renderer_submitSpine?.(e._cpp)},setStage(e){ss?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>ss?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){ss?.renderer_releaseTarget(e)},getTargetTexture:e=>ss?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>ss?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,r){ss?.renderer_setClearColor?.(e,t,s,r)},setViewport(e,t,s,r){ss?.renderer_setViewport(e,t,s,r)},setScissor(e,t,s,r,n){ss?.renderer_setScissor(e,t,s,r,n)},clearBuffers(e){ss?.renderer_clearBuffers(e)},getStats:()=>ss?{drawCalls:ss.renderer_getDrawCalls(),triangles:ss.renderer_getTriangles(),sprites:ss.renderer_getSprites(),text:ss.renderer_getText(),spine:ss.renderer_getSpine?.()??0,meshes:ss.renderer_getMeshes(),culled:ss.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let as=null;function ls(e){as=e}function cs(){as=null}const us={enable(){as?.gl_enableErrorCheck(!0)},disable(){as?.gl_enableErrorCheck(!1)},check:e=>as?.gl_checkErrors(e)??0,diagnose(){as?.renderer_diagnose()}},hs=new Map;function ds(e){hs.delete(e)}class ps{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}setSpineRenderer(e){this.spineRenderer_=e}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:s,width:r,height:n,elapsed:o}=e;r===this.lastWidth_&&n===this.lastHeight_||(is.resize(r,n),Zt.isInitialized()&&Zt.getPassCount()>0&&Zt.resize(r,n),this.lastWidth_=r,this.lastHeight_=n),is.setViewport(0,0,r,n),is.clearBuffers(3),is.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,r,n),is.submitSprites(t),is.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):is.submitSpine(t),is.flush(),this.executeDrawCallbacks(s,o),is.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:r,clearFlags:n,elapsed:o}=e;is.setViewport(r.x,r.y,r.w,r.h),is.setScissor(r.x,r.y,r.w,r.h,!0),is.clearBuffers(n),is.setScissor(0,0,0,0,!1),is.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,r.x,r.y,r.w,r.h),is.submitSprites(t),is.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):is.submitSpine(t),is.flush(),this.executeDrawCallbacks(s,o),is.end()}executeDrawCallbacks(e,t){const s=hs;if(s.size>0){Dt.begin(e);const r=[];for(const[e,n]of s.entries())try{n(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),r.push(e)}Dt.end();for(const e of r)ds(e)}}}class fs{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 s=t/1e3;for(this.updateTime(s),this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;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 fs}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_}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,cs(),os(),Jt(),Vt(),lt(),Ut()}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 ms=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function gs(e,t,s,r,n){const o=e*t/s,i=e;switch(r){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 xs(e,t,s,r){const n=e.registry_getCameraEntities(t);if(0===n.length)return[];const o=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(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*s/(l.h*r);let u,h=0,d=0;if(1===n.projectionType){if(d=n.orthoSize,o){d=gs(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}h=d*c,u=_s(-h,h,-d,d,-n.farPlane,n.farPlane)}else u=vs(n.fov*Math.PI/180,c,n.nearPlane,n.farPlane);const p=Ss(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:Ps(u,p),viewportRect:l,clearFlags:n.clearFlags,priority:n.priority,halfW:h,halfH:d,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const ys=new Float32Array(16);function _s(e,t,s,r,n,o){const i=ys;i.fill(0);const a=t-e,l=r-s,c=o-n;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(r+s)/l,i[14]=-(o+n)/c,i[15]=1,i}const ws=new Float32Array(16);function vs(e,t,s,r){const n=ws;n.fill(0);const o=1/Math.tan(e/2),i=s-r;return n[0]=o/t,n[5]=o,n[10]=(r+s)/i,n[11]=-1,n[14]=2*r*s/i,n}const bs=new Float32Array(16);function Ss(e,t,s){const r=bs;return r[0]=1,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=1,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=1,r[11]=0,r[12]=-e,r[13]=-t,r[14]=-s,r[15]=1,r}function Ps(e,t){const s=new Float32Array(16);for(let r=0;r<4;r++)for(let n=0;n<4;n++)s[4*n+r]=e[0+r]*t[4*n+0]+e[4+r]*t[4*n+1]+e[8+r]*t[4*n+2]+e[12+r]*t[4*n+3];return s}async function Cs(e,t){if(t)return t();return(0,(await import(e)).default)()}const Ts=J({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),As=J(null,"PhysicsAPI");function Ms(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 Rs{constructor(e,t={},s){this.wasmUrl_=e,this.factory_=s,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Ts,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,r=Cs(this.wasmUrl_,this.factory_).then(r=>{r._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 s of t){const t=e.world.get(s,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,L]),c=new Set;for(const n of l){c.add(n);const a=i.get(n,P),l=i.get(n,L);if(t.has(n)){const e=s.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||(r._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=Ms(l.rotation);r._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),Is(e,r,n),t.add(n),s.set(n,{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=Ms(l.rotation);r._physics_setBodyTransform(n,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(r._physics_destroyBody(e),t.delete(e),s.delete(e));r._physics_step(a.delta),function(e,t,s){const r=t._physics_getDynamicBodyCount();if(0===r)return;const n=t._physics_getDynamicBodyTransforms(),o=n>>2;for(let n=0;n<r;n++){const r=o+4*n,i=t.HEAPU32[r],a=t.HEAPF32[r+1]*s,l=t.HEAPF32[r+2]*s,c=t.HEAPF32[r+3];if(!e.world.valid(i))continue;const u=e.world.get(i,z);if(!u)continue;let h=a,d=l,p=c;if(e.world.has(i,N)){const t=e.world.get(i,N);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,L)){const s=e.world.get(t.entity,L),r=Ms(s.rotation),n=a-s.position.x,o=l-s.position.y,i=Math.cos(-r),u=Math.sin(-r);h=(n*i-o*u)/(0!==s.scale.x?s.scale.x:1),d=(n*u+o*i)/(0!==s.scale.y?s.scale.y:1),p=c-r}}u.position.x=h,u.position.y=d;const f=Es(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,z,u)}}(e,r,n),function(e,t,s){t._physics_collectEvents();const r=[],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;r.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]*s,contactY:t.HEAPF32[n+5]*s})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<i;s++){const r=e+2*s;o.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const r=e+2*s;a.push({sensorEntity:t.HEAPU32[r],visitorEntity:t.HEAPU32[r+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const r=e+2*s;c.push({sensorEntity:t.HEAPU32[r],visitorEntity:t.HEAPU32[r+1]})}}e.insertResource(Ts,{collisionEnters:r,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,r,n)},{name:"PhysicsSystem"})),e.__physicsModule=r,e.insertResource(As,Bs._fromModule(r)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=r}}function Is(e,t,s){const r=e.world;if(r.has(s,C)){const e=r.get(s,C);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(r.has(s,T)){const e=r.get(s,T);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(r.has(s,A)){const e=r.get(s,A);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Bs{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(Bs.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 Fs(e,t,s=!0){const r=e.getResourceManager(),n=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,n);const o=r.createTexture(t.width,t.height,n,t.pixels.length,1,s);return e._free(n),o}function Us(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function ks(e,t,s,r){const n=e.scale.x*t*(s?-1:1),o=e.scale.y*t*(r?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,h=a+a,d=l+l,p=c+c,f=a*h,m=a*d,g=a*p,x=l*d,y=l*p,_=c*p,w=u*h,v=u*d,b=u*p;return new Float32Array([(1-(x+_))*n,(m+b)*n,(g-v)*n,0,(m-b)*o,(1-(f+_))*o,(y+w)*o,0,(g+v)*i,(y-w)*i,(1-(f+x))*i,0,e.position.x,e.position.y,e.position.z,1])}async function Ws(e,t,s,r,n,o,i){const a=await async function(e,t,s){const r={};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!==r[n])continue;try{r[n]=Fs(e,await s.loadPixels(n))}catch{r[n]=0}}return r}(t,s,r);!function(e,t,s){if(!t.textureMetadata)return;const r=e.getResourceManager();for(const e in t.textureMetadata){const n=s[e];if(n&&n>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;r.setTextureMetadata(n,e.left,e.right,e.top,e.bottom)}}}}(t,s,a);let l={},c=null;if(n&&(c=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),l=await async function(e,t,s,r,n){const o={};for(const i of r.entities)for(const r of i.components){if("SpineAnimation"!==r.type||!r.data)continue;const i=r.data.skeletonPath,a=r.data.atlasPath;if(!i||!a)continue;const l=n.resolvePath(i),c=n.resolvePath(a);try{const r=n.readText(a),u=l.endsWith(".skel");let h,d;if(u){const e=n.readBinary(i);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=n.readText(i),s=(new TextEncoder).encode(e);d=s.length,h=t._malloc(d+1),t.HEAPU8.set(s,h),t.HEAPU8[h+d]=0}const p=s.loadSkeleton(h,d,r,r.length,u);if(t._free(h),p<0)continue;o[i]=p;const f=Us(r),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const r=m+"/"+f[t];try{const o=n.loadPixelsRaw?await n.loadPixelsRaw(r):await n.loadPixels(r),i=Fs(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,n,c,s,r)),o){new Rs("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const u=function(e,t){const s={},r={};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===s[n])try{const e=JSON.parse(t.readText(n));if(!e.vertexSource||!e.fragmentSource){s[n]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=r[o];i||(i=ut.createShader(e.vertexSource,e.fragmentSource),r[o]=i),s[n]=ut.createFromAsset(e,i)}catch{s[n]=0}}return s}(s,r),h=wt(e.world,s);if(function(e,t,s,r){for(const n of t.entities){const t=r.get(n.id);if(void 0!==t)for(const r of n.components)if("Sprite"===r.type&&r.data.texture&&"string"==typeof r.data.texture){const n=e.get(t,$);n&&(n.texture=s[r.data.texture]||0,e.insert(t,$,n))}}}(e.world,s,a,h),function(e,t,s,r){for(const n of t.entities){const t=r.get(n.id);if(void 0!==t)for(const r of n.components){if(!r.data||"string"!=typeof r.data.material||!r.data.material)continue;const n=s[r.data.material]||0;if(n)if("Sprite"===r.type){const s=e.get(t,$);s&&(s.material=n,e.insert(t,$,s))}else if("SpineAnimation"===r.type){const s=e.get(t,G);s&&(s.material=n,e.insert(t,G,s))}}}}(e.world,s,u,h),n&&c){const r=function(e,t,s,r){const n={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=s[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=r.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}(c,s,l,h);!function(e,t,s,r,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,h=a?.timeScale??1;u&&r.update(i,l*h);let d=0;if(c.has(o,L)){const e=ks(c.get(o,L),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const p=r.getMeshBatchCount(i);for(let e=0;e<p;e++){const n=r.getMeshBatchVertexCount(i,e),o=r.getMeshBatchIndexCount(i,e);if(!n||!o)continue;const a=8*n*4,l=2*o,c=s._malloc(a),u=s._malloc(l),h=s._malloc(4),p=s._malloc(4);r.getMeshBatchData(i,e,c,u,h,p);const f=s.HEAPU32[h>>2],m=s.HEAPU32[p>>2],g=new Float32Array(s.HEAPF32.buffer,c,8*n),x=new Uint16Array(s.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,d),t._free(y),t._free(_),s._free(c),s._free(u),s._free(h),s._free(p)}d&&t._free(d)}})}(e,t,n,c,r)}}class Ds{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const r=e.data.skeletonPath,n=e.data.atlasPath;r&&(r.endsWith(".skel")?s.add(r):t.add(r)),n&&t.add(n)}"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 s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(r)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),r=await s.blob(),n=await createImageBitmap(r),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 zs={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=is.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:is.getTargetTexture(s),width:e.width,height:e.height}},release(e){is.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(is.releaseRenderTarget(e._handle),zs.create({width:t,height:s,depth:!0})),begin(e,t){is.begin(t,e._handle)},end(){is.end()},getDepthTexture:e=>is.getTargetDepthTexture(e._handle)};let Ls=!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 s="string"==typeof e?e:e.toString(),r={method:t?.method??"GET",headers:t?.headers,body:t?.body},n=await l(s,r);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:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return c(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let r=0;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);n<128?s[r++]=n:n<2048?(s[r++]=192|n>>6,s[r++]=128|63&n):n>=55296&&n<=56319?(n=e.charCodeAt(++t)-56320+(n-55296<<10)+65536,s[r++]=240|n>>18,s[r++]=128|n>>12&63,s[r++]=128|n>>6&63,s[r++]=128|63&n):(s[r++]=224|n>>12,s[r++]=128|n>>6&63,s[r++]=128|63&n)}return s.subarray(0,r)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const r=t[e];if(r<128)s+=String.fromCharCode(r),e++;else if(192==(224&r))s+=String.fromCharCode((31&r)<<6|63&t[e+1]),e+=2;else if(224==(240&r))s+=String.fromCharCode((15&r)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const n=((7&r)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(n>>10),56320+(1023&n)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=w,exports.App=fs,exports.AssetPlugin=Tt,exports.AssetServer=Pt,exports.Assets=Ct,exports.AsyncCache=St,exports.BitmapText=V,exports.BodyType=M,exports.BoxCollider=C,exports.Button=ze,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=Dt,exports.EntityCommands=ne,exports.GLDebug=us,exports.Geometry=Yt,exports.INVALID_ENTITY=0,exports.INVALID_FONT=b,exports.INVALID_TEXTURE=v,exports.Input=de,exports.InputPlugin=pe,exports.InputState=he,exports.Interactable=ke,exports.LocalTransform=z,exports.Material=ut,exports.MaterialLoader=_t,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=Y,exports.Parent=N,exports.Physics=Bs,exports.PhysicsEvents=Ts,exports.PhysicsPlugin=Rs,exports.PostProcess=Zt,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_)try{const e=await s(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),r=new Ds(this.baseUrl_);await r.prefetch(t);let n=null;const o=this.app_.__spineInitPromise;if(o){n=(await o).controller.raw}await Ws(this.app_,this.app_.wasmModule,t,r,n),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([H]);for(const r of s){if(e.get(r,H).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1920/1080;const r=e.getEntitiesWithComponents([O]);for(const n of r){const r=e.get(n,O);if(r.designResolution){const e=r.pixelsPerUnit||100;t=r.designResolution.y/2/e,s=r.designResolution.x/r.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,z,o);const i={isActive:!0,projectionType:1,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,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=[],s=[]){const r=[];return e.forEach((e,t)=>{se(e)&&r.push(t)}),{_type:"query",_components:e,_mutIndices:r,_with:t,_without:s}}(e)},exports.QueryInstance=re,exports.RenderPipeline=ps,exports.RenderTexture=zs,exports.Renderer=is,exports.Res=Q,exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.RigidBody=P,exports.ScreenSpace=Xe,exports.ShaderSources=yt,exports.SpineAnimation=G,exports.Sprite=$,exports.SystemRunner=ue,exports.Text=we,exports.TextInput=Ke,exports.TextInputPlugin=Je,exports.TextPlugin=Se,exports.TextRenderer=ve,exports.Time=te,exports.UICameraInfo=He,exports.UIEventQueue=Le,exports.UIEvents=$e,exports.UIInteraction=We,exports.UIInteractionPlugin=je,exports.UILayoutPlugin=Ye,exports.UIMask=Ce,exports.UIMaskPlugin=Fe,exports.UIRect=be,exports.Velocity=j,exports.WebAssetProvider=Ds,exports.World=ge,exports.WorldTransform=L,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=At,exports.clearDrawCallbacks=function(){hs.clear()},exports.clearUserComponents=function(){I().clear()},exports.color=(e=1,t=1,s=1,r=1)=>({r:e,g:t,b:s,a:r}),exports.computeUIRectLayout=Ve,exports.createMaskProcessor=Be,exports.createWebApp=function(e,t){const s=fs.new(),r=new e.Registry;s.connectCpp(r,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ft(e),at(e),Xt(e),Kt(e),ns(e),ls(e);const n=new ps;s.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=xs(e,r,t,n),i=s.getResource(He);if(o.length>0){const e=o[0],s=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(s.x*t),i.vpY=Math.round((1-s.y-s.h)*n),i.vpW=Math.round(s.w*t),i.vpH=Math.round(s.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}s.insertResource(He,{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:s}=i(),c=e.registry_getCanvasEntity(r);if(c>=0){const e=r.getCanvas(c).backgroundColor;is.setClearColor(e.r,e.g,e.b,e.a)}const u=(a()-o)/1e3;is.resize(t,s),Zt.isInitialized()&&Zt.getPassCount()>0&&!Zt.isBypassed()&&Zt.resize(t,s);const h=xs(e,r,t,s);if(l(t,s),0===h.length)n.render({registry:{_cpp:r},viewProjection:ms,width:t,height:s,elapsed:u});else{for(const e of h){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*s),l=Math.round(o.w*t),c=Math.round(o.h*s);n.renderCamera({registry:{_cpp:r},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:c},clearFlags:e.clearFlags,elapsed:u})}is.setViewport(0,0,t,s)}}};return s.addSystemToSchedule(exports.Schedule.First,c),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(At),s.addPlugin(fe),s.addPlugin(Pe),s.addPlugin(Ue),s.addPlugin(qe),s.addPlugin(Ne),s.addPlugin(et),s},exports.defineComponent=B,exports.defineResource=J,exports.defineSystem=le,exports.defineTag=F,exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([Y]);for(const r of s){const s=e.get(r,Y);if(s&&s.value===t)return r}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}},exports.getComponentDefaults=function(e){const t=q[e];if(t)return{...t._default};const s=U(e);return s?{...s._default}:null},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=U,exports.initDrawAPI=Ft,exports.initGLDebugAPI=ls,exports.initGeometryAPI=Xt,exports.initMaterialAPI=at,exports.initPostProcessAPI=Kt,exports.initRendererAPI=ns,exports.inputPlugin=fe,exports.intersectRects=Te,exports.invertMatrix4=Me,exports.isBuiltinComponent=D,exports.isEditor=function(){return Ls},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!Ls},exports.isTextureRef=st,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=bt,exports.loadPhysicsModule=Cs,exports.loadRuntimeScene=Ws,exports.loadSceneData=wt,exports.loadSceneWithAssets=vt,exports.platformFetch=s,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,s){return t().instantiateWasm(e,s)},exports.platformReadFile=r,exports.platformReadTextFile=n,exports.pointInWorldRect=Re,exports.quat=(e=1,t=0,s=0,r=0)=>({w:e,x:t,y:s,z:r}),exports.registerDrawCallback=function(e,t){hs.set(e,t)},exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(Ct);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=xt,exports.screenToWorld=Ee,exports.setEditorMode=function(e){Ls=e},exports.shutdownDrawAPI=Ut,exports.shutdownGLDebugAPI=cs,exports.shutdownGeometryAPI=Vt,exports.shutdownMaterialAPI=lt,exports.shutdownPostProcessAPI=Jt,exports.shutdownRendererAPI=os,exports.textInputPlugin=et,exports.textPlugin=Pe,exports.uiInteractionPlugin=Ne,exports.uiLayoutPlugin=qe,exports.uiMaskPlugin=Ue,exports.unregisterDrawCallback=ds,exports.updateCameraAspectRatio=function(e,t){const s=e.getEntitiesWithComponents([H]);for(const r of s){const s=e.get(r,H);s&&(s.aspectRatio=t,e.insert(r,H,s))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),exports.vec4=(e=0,t=0,s=0,r=1)=>({x:e,y:t,z:s,w:r}),exports.worldRectToScreen=Ae,exports.wxFileExists=f,exports.wxFileExistsSync=function(e){const t=h();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=d,exports.wxReadTextFile=p,exports.wxWriteFile=function(e,t){return new Promise((s,r)=>{h().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{r(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 n(e,n){return t().fetch(e,n)}async function s(e){return t().readFile(e)}async function r(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,n){return t().createCanvas(e,n)}function a(){return t().now()}function l(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 c(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 u=null;function d(){return u||(u=wx.getFileSystemManager()),u}function h(e){return new Promise((t,n)=>{d().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function p(e,t="utf-8"){return new Promise((n,s)=>{d().readFile({filePath:e,encoding:t,success:e=>{n(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,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 y(e){const{width:t,height:n}=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,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)}}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 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)})}},v=4294967295,b=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}),M=S("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),A={Static:0,Kinematic:1,Dynamic:2};let E=0;function R(e,t){const n=++E;return{_id:Symbol(`Component_${n}_${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 n=I(),s=n.get(e);if(s)return s;const r=R(e,t);return n.set(e,r),k(e,t,!1),r}function F(e){const t=I(),n=t.get(e);if(n)return n;const s=R(e,{});return t.set(e,s),k(e,{},!0),s}function U(e){return I().get(e)}function k(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}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 z=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}}),$=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:v,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),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:b}),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:z,WorldTransform:$,Sprite:L,Camera:H,Canvas:O,Velocity:N,Parent:j,Children:X,BitmapText:V,SpineAnimation:G,RigidBody:P,BoxCollider:C,CircleCollider:T,CapsuleCollider:M};let J=0;function K(e,t){const n=++J;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_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 ne(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=>ne(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}}class re{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=D(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 oe{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new re(this,null);return this.spawned_.push(e),e}entity(e){return new re(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 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,n){const s=++ae;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.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 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 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 n=new de;e.insertResource(he,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(exports.Schedule.Last,le([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const fe=new pe;function me(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}: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,n){return D(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}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,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,me(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(!D(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 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,dirty:!0});class ve{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 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),p=r?Math.ceil(o):d+2*u,f=r?Math.ceil(i):h+2*u;if(r&&e.overflow===exports.TextOverflow.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(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;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}, ${x}, ${y})`,r&&e.overflow===exports.TextOverflow.Clip&&(n.save(),n.beginPath(),n.rect(0,0,p,f),n.clip());const _=l.length*c;let w;if(r)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 v=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}n.fillText(t,s,v),v+=c}r&&e.overflow===exports.TextOverflow.Clip&&n.restore();const b=n.getImageData(0,0,p,f),S=new Uint8Array(b.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 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 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 be=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}});class Se{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new ve(t),s=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,le([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,we));const e=s.getEntitiesWithComponents([we]);for(const t of e){const e=s.get(t,we);if(!e.dirty)continue;s.has(t,L)||s.insert(t,L,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const r=s.has(t,be)?s.get(t,be):null,o=n.renderForEntity(t,e,r),i=s.get(t,L);i.texture=o.textureHandle,i.size.x=o.width,i.size.y=o.height,i.uvOffset.x=0,i.uvOffset.y=0,i.uvScale.x=1,i.uvScale.y=1,s.insert(t,L,i),e.dirty=!1}}))}}const Pe=new Se,Ce=B("UIMask",{enabled:!0});function Te(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 Me(e,t,n,s,r,o,i,a,l,c,u){const d=e-n*r,h=e+n*(1-r),p=t-s*o,f=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,x]=m(d,p),[y,_]=m(h,f),w=Math.min(g,y),v=Math.max(g,y),b=Math.min(x,_),S=Math.max(x,_);return{x:Math.round(w),y:Math.round(b),w:Math.round(v-w),h:Math.round(S-b)}}function Ae(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],p=e[10],f=e[11],m=e[12],g=e[13],x=e[14],y=e[15],_=s*l-r*a,w=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,T=d*x-p*m,M=d*y-f*m,A=h*x-p*g,E=h*y-f*g,R=p*y-f*x;let I=_*R-w*E+v*A+b*M-S*T+P*C;return 0===I||(I=1/I,n[0]=(l*R-c*E+u*A)*I,n[1]=(o*E-r*R-i*A)*I,n[2]=(g*P-x*S+y*b)*I,n[3]=(p*S-h*P-f*b)*I,n[4]=(c*M-a*R-u*T)*I,n[5]=(s*R-o*M+i*T)*I,n[6]=(x*v-m*P-y*w)*I,n[7]=(d*P-p*v+f*w)*I,n[8]=(a*E-l*M+u*C)*I,n[9]=(r*M-s*E-i*C)*I,n[10]=(m*S-g*v+y*_)*I,n[11]=(h*v-d*S-f*_)*I,n[12]=(l*T-a*A-c*C)*I,n[13]=(s*A-r*T+o*C)*I,n[14]=(g*w-m*b-x*_)*I,n[15]=(d*b-h*w+p*_)*I),n}function Ee(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 Re(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 Ie(e,t,n,s,r,o,i){if(!e.has(t,be)||!e.has(t,$))return null;const a=e.get(t,be),l=e.get(t,$),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,n,s,r,o,i)}function Be(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Ce]);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,Ce).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=Ie(t,n,r,o,i,a,l);e&&(s=Te(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=Ie(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 Fe{build(e){if(!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Be(e.wasmModule,e.world))}}const Ue=new Fe,ke=B("Interactable",{enabled:!0}),We=B("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var De;exports.ButtonState=void 0,(De=exports.ButtonState||(exports.ButtonState={}))[De.Normal=0]="Normal",De[De.Hovered=1]="Hovered",De[De.Pressed=2]="Pressed",De[De.Disabled=3]="Disabled";const ze=B("Button",{state:exports.ButtonState.Normal,transition:null});class $e{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 Le=K(new $e,"UIEvents"),He=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"),Oe=new Float32Array(16);class Ne{build(e){const t=e.world,n=new $e;e.insertResource(Le,n);let s=null,r=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,le([Q(he),Q(He)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([We]);for(const e of i){const n=t.get(e,We);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;Ae(o.viewProjection,Oe);const u=Ee(l,c,Oe,o.vpX,o.vpY,o.vpW,o.vpH),d=t.getEntitiesWithComponents([ke,be,$]);let h=null,p=-1/0;for(const e of d){t.has(e,We)||t.insert(e,We);if(!t.get(e,ke).enabled)continue;const n=t.get(e,$),s=t.get(e,be),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(Re(u.x,u.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y)){let n=0;t.has(e,L)&&(n=t.get(e,L).layer),n>=p&&(p=n,h=e)}}if(s!==h){if(null!==s&&t.valid(s)&&t.has(s,We)){t.get(s,We).hovered=!1,n.emit(s,"hover_exit")}if(null!==h){t.get(h,We).hovered=!0,n.emit(h,"hover_enter")}s=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,We);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,We)){const e=t.get(r,We);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(exports.Schedule.Update,le([],()=>{const e=t.getEntitiesWithComponents([ze]);for(const n of e){if(t.has(n,ke)||t.insert(n,ke,{enabled:!0}),!t.has(n,We))continue;const e=t.get(n,We),s=t.get(n,ze),r=t.get(n,ke),o=s.state;if(r.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(n,L)){const e=t.get(n,L),r=s.transition;switch(s.state){case exports.ButtonState.Normal:e.color={...r.normalColor};break;case exports.ButtonState.Hovered:e.color={...r.hoveredColor};break;case exports.ButtonState.Pressed:e.color={...r.pressedColor};break;case exports.ButtonState.Disabled:e.color={...r.disabledColor}}t.insert(n,L,e)}}},{name:"ButtonSystem"}))}}const je=new Ne,Xe=F("ScreenSpace");function Ve(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,p,f,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,p=t-o,f=e+s,m=t+o}else h=l+n.x,p=u+n.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 Ge(e,t,n,s,r,o){if(!e.has(t,be))return;const i=e.get(t,be),a=Ve(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,X))return;const c=e.get(t,X);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&Ge(e,t,a.rect,a.centerX,a.centerY,!1)}class Ye{build(e){const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,le([Q(He)],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([Xe,be,z]);for(const e of o)Ge(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const qe=new Ye,Je=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 Ke{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=i(512,64),o=r.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||!n.valid(a))return;const t=n.get(a,Je);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(Le).emit(a,"change")}t.cursorPos=h.selectionStart??s.length,t.dirty=!0,g()}function f(e){if(a===e)return;m();const t=n.get(e,Je);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&&n.valid(a)&&n.has(a,Je)){const e=n.get(a,Je);e.focused=!1,e.dirty=!0}a=null,h.blur()}function g(){c=!0,u=0}function x(e,i,a,l){(r.width<a||r.height<l)&&(r.width=Ze(Math.max(r.width,a)),r.height=Ze(Math.max(r.height,l))),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,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=Qe(o,h,a-2*m);let t=m;for(const n of e)o.fillText(n,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,n,s;if(i.multiline){const e=Qe(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)*f,s=f}else t=m+o.measureText(e).width,n=(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,n,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 v=y.createTexture(a,l,_,x.length,1,!0);s.set(e,v),t._free(_);const b=n.get(e,L);b.texture=v,b.size.x=a,b.size.y=l,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},n.insert(e,L,b)}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=n.get(a,Je);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(Le).emit(a,"submit"),void m()}}),h.addEventListener("blur",()=>{if(null!==a&&n.valid(a)&&n.has(a,Je)){const e=n.get(a,Je);e.focused=!1,e.dirty=!0}a=null}),e.addSystemToSchedule(exports.Schedule.PreUpdate,le([Q(Le)],e=>{const t=n.getEntitiesWithComponents([Je,ke]);for(const e of t){if(!n.has(e,We))continue;if(n.get(e,We).justPressed)return void f(e)}if(null!==a){const e=n.getEntitiesWithComponents([ke]);for(const t of e){if(n.has(t,Je))continue;if(!n.has(t,We))continue;if(n.get(t,We).justPressed)return void m()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(exports.Schedule.PreUpdate,le([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===d?0:(e-d)/1e3;if(d=e,null!==a&&(u+=r,u>=.5&&(u-=.5,c=!c,null!==a&&n.valid(a)&&n.has(a,Je)))){n.get(a,Je).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Je)||(o.releaseTexture(t),s.delete(e));const i=n.getEntitiesWithComponents([Je,be]);for(const e of i){const t=n.get(e,Je);if(!t.dirty)continue;const s=n.get(e,be),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,L)||n.insert(e,L,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),x(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Qe(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 Ze(e){let t=1;for(;t<e;)t*=2;return t}const et=new Ke;var tt;function nt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(tt=exports.BlendMode||(exports.BlendMode={}))[tt.Normal=0]="Normal",tt[tt.Additive=1]="Additive",tt[tt.Multiply=2]="Multiply",tt[tt.Screen=3]="Screen",tt[tt.PremultipliedAlpha=4]="PremultipliedAlpha";let st=null,rt=null,ot=1;const it=new Map;function at(e){st=e,rt=e.getResourceManager(),xt()}function lt(){0!==ht&&st&&(st._free(ht),ht=0),it.clear(),ot=1,dt=!1,rt=null,st=null}function ct(){if(!rt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return rt}const ut={createShader:(e,t)=>ct().createShader(e,t),releaseShader(e){e>0&&ct().releaseShader(e)},create(e){const t=ot++,n={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))n.uniforms.set(t,s);return it.set(t,n),t},get:e=>it.get(e),setUniform(e,t,n){const s=it.get(e);s&&s.uniforms.set(t,n)},getUniform(e,t){const n=it.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=it.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=it.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const n=it.get(e);n&&(n.depthTest=t)},getShader(e){const t=it.get(e);return t?.shader??0},release(e){it.delete(e)},isValid:e=>it.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??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=it.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=ot++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return it.set(n,s),n},toAssetData(e,t){const n=it.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=it.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let dt=!1,ht=0;const pt=4096,ft=new Map;let mt=null;function gt(e){const t=(0===ht&&st&&(ht=st._malloc(pt)),ht);if(0===t||!st)return{ptr:0,count:0};let n=0,s=0;const r=st.HEAPU8,o=st.HEAPU32,i=st.HEAPF32;for(const[a,l]of e){if(n+128>pt)break;let e=ft.get(a);e||(mt||(mt=new TextEncoder),e=mt.encode(a),ft.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 xt(){if(!st||dt)return;st.materialDataProvider=(e,t,n,s,r)=>{const o=it.get(e);if(!o)return st.HEAPU32[t>>2]=0,st.HEAPU32[n>>2]=0,st.HEAPU32[s>>2]=0,void(st.HEAPU32[r>>2]=0);st.HEAPU32[t>>2]=o.shader,st.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=gt(o.uniforms);st.HEAPU32[s>>2]=i,st.HEAPU32[r>>2]=a},dt=!0}const yt={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 _t{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&&(ut.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())ut.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 n=await r(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),a=await this.shaderLoader_.load(i);return{handle:ut.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 n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function wt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();n.set(s.id,t),e.insert(t,Y,{value:s.name});for(const n of s.components)bt(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();s.set(i.id,t),e.insert(t,Y,{value:i.name});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}}bt(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 bt(e,t,n){const s=n.data;switch(n.type){case"LocalTransform":e.insert(t,z,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 n=s;n.anchor&&!n.anchorMin&&(n.anchorMin={...n.anchor},n.anchorMax={...n.anchor},delete n.anchor),e.insert(t,be,n);break}case"UIMask":e.insert(t,Ce,s);break;case"Interactable":e.insert(t,ke,s);break;case"Button":e.insert(t,ze,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,M,s);break;default:{const r=U(n.type);r?e.insert(t,r,s):console.warn(`Unknown component type: ${n.type}`);break}}}class St{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 Pt{constructor(e){this.textureCache_=new St,this.shaderCache_=new St,this.jsonCache_=new St,this.textCache_=new St,this.binaryCache_=new St,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new St,this.prefabCache_=new St,this.embedded_=new Map,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 _t(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n)}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){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];if(e.textures)for(const s of e.textures)n.push(this.loadTexture(s).then(e=>{t.textures.set(s,e)}));if(e.materials)for(const s of e.materials)n.push(this.loadMaterial(s).then(e=>{t.materials.set(s,e)}));if(e.spine)for(const s of e.spine){const e=`${s.skeleton}:${s.atlas}`;n.push(this.loadSpine(s.skeleton,s.atlas,s.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const s of e.json)n.push(this.loadJson(s).then(e=>{t.json.set(s,e)}));if(e.text)for(const s of e.text)n.push(this.loadText(s).then(e=>{t.text.set(s,e)}));if(e.binary)for(const s of e.binary)n.push(this.loadBinary(s).then(e=>{t.binary.set(s,e)}));return await Promise.all(n),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 loadByAddress(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"json":return this.loadJson(e.path);case"text":return this.loadText(e.path);default:return this.loadBinary(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e)switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(e=>{t.textures.set(s.path,e)}));break;case"material":n.push(this.loadMaterial(s.path).then(e=>{t.materials.set(s.path,e)}));break;case"json":n.push(this.loadJson(s.path).then(e=>{t.json.set(s.path,e)}));break;case"text":n.push(this.loadText(s.path).then(e=>{t.text.set(s.path,e)}));break;default:n.push(this.loadBinary(s.path).then(e=>{t.binary.set(s.path,e)}))}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)??n;return new Promise((n,r)=>{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=()=>r(new Error(`Failed to load image: ${e}`)),o.src=s})}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;if(!await o(t))throw new Error(`Shader file not found: ${e}`);const n=await r(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:s,fragment:i}=this.parseEsShader(n);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return ut.createShader(s,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const n=await r(t);return JSON.parse(n)}const s=await n(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):r(t)}const s=await n(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):s(t)}const r=await n(e);if(!r.ok)throw new Error(`Failed to fetch binary: ${e} (${r.status})`);return r.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const 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 Ct=K(null,"Assets");class Tt{build(e){const t=e.wasmModule;t?e.insertResource(Ct,new Pt(t)):console.warn("AssetPlugin: No WASM module available")}}const Mt=new Tt;let At=null,Et=0,Rt=0,It=0;const Bt=new Float32Array(256);function Ft(e){At=e,Et=At._malloc(64),Rt=At._malloc(64),It=At._malloc(1024)}function Ut(){At&&(Et&&(At._free(Et),Et=0),Rt&&(At._free(Rt),Rt=0),It&&(At._free(It),It=0)),At=null}function kt(){if(!At)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return At}const Wt={r:1,g:1,b:1,a:1},Dt={begin(e){const t=kt();t.HEAPF32.set(e,Et/4),t.draw_begin(Et)},end(){kt().draw_end()},line(e,t,n,s=1){kt().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){kt().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){kt().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){kt().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){kt().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=Wt){kt().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=Wt){kt().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){kt().draw_setLayer(e)},setDepth(e){kt().draw_setDepth(e)},getDrawCallCount:()=>At?At.draw_getDrawCallCount():0,getPrimitiveCount:()=>At?At.draw_getPrimitiveCount():0,setBlendMode(e){kt().draw_setBlendMode(e)},setDepthTest(e){kt().draw_setDepthTest(e)},drawMesh(e,t,n){const s=kt();s.HEAPF32.set(n,Rt/4),s.draw_mesh(e,t,Rt)},drawMeshWithMaterial(e,t,n){const s=kt(),r=ut.get(t);if(!r)return;if(Dt.setBlendMode(r.blendMode),Dt.setDepthTest(r.depthTest),0===r.uniforms.size)return void Dt.drawMesh(e,r.shader,n);s.HEAPF32.set(n,Rt/4);let o=0,i=0;for(const[e,t]of r.uniforms){const n=$t(e);if(!(n<0)){if(nt(t))Bt[o++]=10,Bt[o++]=n,Bt[o++]=t.slot??i++,Bt[o++]=t.textureId;else if("number"==typeof t)Bt[o++]=1,Bt[o++]=n,Bt[o++]=t;else if(Array.isArray(t)){Bt[o++]=t.length,Bt[o++]=n;for(let e=0;e<t.length;e++)Bt[o++]=t[e]}else"w"in t?(Bt[o++]=4,Bt[o++]=n,Bt[o++]=t.x,Bt[o++]=t.y,Bt[o++]=t.z,Bt[o++]=t.w):"z"in t?(Bt[o++]=3,Bt[o++]=n,Bt[o++]=t.x,Bt[o++]=t.y,Bt[o++]=t.z):(Bt[o++]=2,Bt[o++]=n,Bt[o++]=t.x,Bt[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(Bt.subarray(0,o),It/4),s.draw_meshWithUniforms(e,r.shader,Rt,It,o)):s.draw_mesh(e,r.shader,Rt)}},zt={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 $t(e){return zt[e]??-1}var Lt;exports.DataType=void 0,(Lt=exports.DataType||(exports.DataType={}))[Lt.Float=1]="Float",Lt[Lt.Float2=2]="Float2",Lt[Lt.Float3=3]="Float3",Lt[Lt.Float4=4]="Float4",Lt[Lt.Int=5]="Int",Lt[Lt.Int2=6]="Int2",Lt[Lt.Int3=7]="Int3",Lt[Lt.Int4=8]="Int4";let Ht=null,Ot=0,Nt=0,jt=0;function Xt(e){Ht=e,Ot=Ht._malloc(262144),Nt=Ht._malloc(65536),jt=Ht._malloc(256)}function Vt(){Ht&&(Ot&&Ht._free(Ot),Nt&&Ht._free(Nt),jt&&Ht._free(jt),Ot=0,Nt=0,jt=0),Ht=null}function Gt(){if(!Ht)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Ht}const Yt={create(e){const t=Gt(),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,Ot/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,jt,r).set(o),t.geometry_init(n,Ot,s,jt,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,Nt,s).set(e.indices),t.geometry_setIndices16(n,Nt,s)}else{new Uint32Array(t.HEAPU8.buffer,Nt,s).set(e.indices),t.geometry_setIndices32(n,Nt,s)}}return n},updateVertices(e,t,n=0){const s=Gt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,Ot/4),s.geometry_updateVertices(e,Ot,r,n)},release(e){e>0&&Gt().geometry_release(e)},isValid:e=>!(!Ht||e<=0)&&Ht.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Yt.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: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 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 Yt.create({vertices:new Float32Array(n),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,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 Yt.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 qt=null;function Jt(e){qt=e}function Kt(){qt&&Zt.isInitialized()&&Zt.shutdown(),qt=null}function Qt(){if(!qt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return qt}const Zt={init:(e,t)=>Qt().postprocess_init(e,t),shutdown(){Qt().postprocess_shutdown()},resize(e,t){Qt().postprocess_resize(e,t)},addPass:(e,t)=>Qt().postprocess_addPass(e,t),removePass(e){Qt().postprocess_removePass(e)},setEnabled(e,t){Qt().postprocess_setPassEnabled(e,t)},isEnabled:e=>Qt().postprocess_isPassEnabled(e),setUniform(e,t,n){Qt().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Qt().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Qt().postprocess_begin()},end(){Qt().postprocess_end()},getPassCount:()=>Qt().postprocess_getPassCount(),isInitialized:()=>!!qt&&qt.postprocess_isInitialized(),setBypass(e){Qt().postprocess_setBypass(e)},isBypassed:()=>!qt||qt.postprocess_isBypassed(),createBlur:()=>ut.createShader(en,"#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:()=>ut.createShader(en,"#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:()=>ut.createShader(en,"#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:()=>ut.createShader(en,"#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")},en="#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 tn;exports.RenderStage=void 0,(tn=exports.RenderStage||(exports.RenderStage={}))[tn.Background=0]="Background",tn[tn.Opaque=1]="Opaque",tn[tn.Transparent=2]="Transparent",tn[tn.Overlay=3]="Overlay";let nn=null,sn=0;function rn(e){nn=e,sn=nn._malloc(64)}function on(){nn&&sn&&(nn._free(sn),sn=0),nn=null}const an={init(e,t){nn?.renderer_init(e,t)},resize(e,t){nn?.renderer_resize(e,t)},begin(e,t){nn&&sn&&(nn.HEAPF32.set(e,sn/4),nn.renderer_begin(sn,t??0))},flush(){nn?.renderer_flush()},end(){nn?.renderer_end()},submitSprites(e){nn&&nn.renderer_submitSprites(e._cpp)},submitBitmapText(e){nn&&nn.renderer_submitBitmapText(e._cpp)},submitSpine(e){nn&&nn.renderer_submitSpine?.(e._cpp)},setStage(e){nn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>nn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){nn?.renderer_releaseTarget(e)},getTargetTexture:e=>nn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>nn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){nn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){nn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){nn?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){nn?.renderer_clearBuffers(e)},getStats:()=>nn?{drawCalls:nn.renderer_getDrawCalls(),triangles:nn.renderer_getTriangles(),sprites:nn.renderer_getSprites(),text:nn.renderer_getText(),spine:nn.renderer_getSpine?.()??0,meshes:nn.renderer_getMeshes(),culled:nn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let ln=null;function cn(e){ln=e}function un(){ln=null}const dn={enable(){ln?.gl_enableErrorCheck(!0)},disable(){ln?.gl_enableErrorCheck(!1)},check:e=>ln?.gl_checkErrors(e)??0,diagnose(){ln?.renderer_diagnose()}},hn=new Map;function pn(e){hn.delete(e)}class fn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}setSpineRenderer(e){this.spineRenderer_=e}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_||(an.resize(s,r),Zt.isInitialized()&&Zt.getPassCount()>0&&Zt.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),an.setViewport(0,0,s,r),an.clearBuffers(3),an.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),an.submitSprites(t),an.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):an.submitSpine(t),an.flush(),this.executeDrawCallbacks(n,o),an.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;an.setViewport(s.x,s.y,s.w,s.h),an.setScissor(s.x,s.y,s.w,s.h,!0),an.clearBuffers(r),an.setScissor(0,0,0,0,!1),an.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),an.submitSprites(t),an.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):an.submitSpine(t),an.flush(),this.executeDrawCallbacks(n,o),an.end()}executeDrawCallbacks(e,t){const n=hn;if(n.size>0){Dt.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)}Dt.end();for(const e of s)pn(e)}}}class mn{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 n=t/1e3;for(this.updateTime(n),this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=n;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 mn}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,un(),on(),Kt(),Vt(),lt(),Ut()}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 gn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function xn(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 yn(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=xn(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=wn(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=bn(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const p=Pn(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:Cn(u,p),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 _n=new Float32Array(16);function wn(e,t,n,s,r,o){const i=_n;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 vn=new Float32Array(16);function bn(e,t,n,s){const r=vn;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 Sn=new Float32Array(16);function Pn(e,t,n){const s=Sn;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 Cn(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 Tn(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 Tn(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};Mn(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 Mn(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}async function An(e,t){if(t)return t();return(0,(await import(e)).default)()}const En=K({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Rn=K(null,"PhysicsAPI");function In(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Bn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Fn{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(En,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=An(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(exports.Schedule.PostUpdate,le([Q(te)],a=>{const l=i.getEntitiesWithComponents([P,z,$]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,P),l=i.get(r,$);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=In(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),Un(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===A.Kinematic){const e=In(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,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,$)){const n=e.world.get(t.entity,$),s=In(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),p=c-s}}u.position.x=d,u.position.y=h;const f=Bn(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,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(En,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.__physicsModule=s,e.insertResource(Rn,kn._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=s}}function Un(e,t,n){const s=e.world;if(s.has(n,C)){const e=s.get(n,C);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,T)){const e=s.get(n,T);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,M)){const e=s.get(n,M);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class kn{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(kn.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 Wn(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 Dn(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 zn(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,p=c+c,f=a*d,m=a*h,g=a*p,x=l*h,y=l*p,_=c*p,w=u*d,v=u*h,b=u*p;return new Float32Array([(1-(x+_))*r,(m+b)*r,(g-v)*r,0,(m-b)*o,(1-(f+_))*o,(y+w)*o,0,(g+v)*i,(y-w)*i,(1-(f+x))*i,0,e.position.x,e.position.y,e.position.z,1])}async function $n(e,t,n,s,r,o,i){const a=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]=Wn(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,a);let l={},c=null;if(r&&(c=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),l=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 p=n.loadSkeleton(d,h,s,s.length,u);if(t._free(d),p<0)continue;o[i]=p;const f=Dn(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const s=m+"/"+f[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=Wn(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,c,n,s)),o){new Fn("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const u=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;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=Wn(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),d=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=ut.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=ut.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),h=wt(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,L);r&&(r.texture=n[s.data.texture]||0,e.insert(t,L,r))}}}(e.world,n,a,h),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,u,h),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,L);n&&(n.material=r,e.insert(t,L,n))}else if("SpineAnimation"===s.type){const n=e.get(t,G);n&&(n.material=r,e.insert(t,G,n))}}}}(e.world,n,d,h),r&&c){const s=function(e,t,n,s){const r={};for(const o of t.entities)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}(c,n,l,h);!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,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,$)){const e=zn(c.get(o,$),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 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),p=n._malloc(4);s.getMeshBatchData(i,e,c,u,d,p);const f=n.HEAPU32[d>>2],m=n.HEAPU32[p>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*r),x=new Uint16Array(n.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,r,_,o,f,m,h),t._free(y),t._free(_),n._free(c),n._free(u),n._free(d),n._free(p)}h&&t._free(h)}})}(e,t,r,c,s)}}class Ln{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}}const Hn={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=an.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:an.getTargetTexture(n),width:e.width,height:e.height}},release(e){an.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(an.releaseRenderTarget(e._handle),Hn.create({width:t,height:n,depth:!0})),begin(e,t){an.begin(t,e._handle)},end(){an.end()},getDepthTexture:e=>an.getTargetDepthTexture(e._handle)};let On=!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 n="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await l(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 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),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=w,exports.App=mn,exports.AssetPlugin=Tt,exports.AssetServer=Pt,exports.Assets=Ct,exports.AsyncCache=St,exports.BitmapText=V,exports.BodyType=A,exports.BoxCollider=C,exports.Button=ze,exports.Camera=H,exports.Canvas=O,exports.CapsuleCollider=M,exports.Children=X,exports.CircleCollider=T,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=oe,exports.Draw=Dt,exports.EntityCommands=re,exports.GLDebug=dn,exports.Geometry=Yt,exports.INVALID_ENTITY=0,exports.INVALID_FONT=b,exports.INVALID_TEXTURE=v,exports.Input=he,exports.InputPlugin=pe,exports.InputState=de,exports.Interactable=ke,exports.LocalTransform=z,exports.Material=ut,exports.MaterialLoader=_t,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=Y,exports.Parent=j,exports.Physics=kn,exports.PhysicsEvents=En,exports.PhysicsPlugin=Fn,exports.PostProcess=Zt,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_)try{const e=await n(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new Ln(this.baseUrl_);await s.prefetch(t);let r=null;const o=this.app_.__spineInitPromise;if(o){r=(await o).controller.raw}await $n(this.app_,this.app_.wasmModule,t,s,r),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([H]);for(const s of n){if(e.get(s,H).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,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,H,i)}}},exports.Query=function(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{ne(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)},exports.QueryInstance=se,exports.RenderPipeline=fn,exports.RenderTexture=Hn,exports.Renderer=an,exports.Res=Q,exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.RigidBody=P,exports.ScreenSpace=Xe,exports.ShaderSources=yt,exports.SpineAnimation=G,exports.Sprite=L,exports.SystemRunner=ue,exports.Text=we,exports.TextInput=Je,exports.TextInputPlugin=Ke,exports.TextPlugin=Se,exports.TextRenderer=ve,exports.Time=te,exports.UICameraInfo=He,exports.UIEventQueue=$e,exports.UIEvents=Le,exports.UIInteraction=We,exports.UIInteractionPlugin=Ne,exports.UILayoutPlugin=Ye,exports.UIMask=Ce,exports.UIMaskPlugin=Fe,exports.UIRect=be,exports.Velocity=N,exports.WebAssetProvider=Ln,exports.World=ge,exports.WorldTransform=$,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(){hn.clear()},exports.clearUserComponents=function(){I().clear()},exports.color=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),exports.computeUIRectLayout=Ve,exports.createMaskProcessor=Be,exports.createWebApp=function(e,t){const n=mn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ft(e),at(e),Xt(e),Jt(e),rn(e),cn(e);const r=new fn;n.pipeline_=r;let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function l(t,r){const o=yn(e,s,t,r),i=n.getResource(He);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(He,{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:n}=i();if(0===t||0===n)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;an.setClearColor(e.x,e.y,e.z,e.w)}const u=(a()-o)/1e3;an.resize(t,n),Zt.isInitialized()&&Zt.getPassCount()>0&&!Zt.isBypassed()&&Zt.resize(t,n);const d=yn(e,s,t,n);if(l(t,n),0===d.length)r.render({registry:{_cpp:s},viewProjection:gn,width:t,height:n,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)*n),l=Math.round(o.w*t),c=Math.round(o.h*n);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:c},clearFlags:e.clearFlags,elapsed:u})}an.setViewport(0,0,t,n)}}};return n.addSystemToSchedule(exports.Schedule.First,c),n.addSystemToSchedule(exports.Schedule.Last,u),n.addPlugin(Mt),n.addPlugin(fe),n.addPlugin(Pe),n.addPlugin(Ue),n.addPlugin(qe),n.addPlugin(je),n.addPlugin(et),n},exports.defineComponent=B,exports.defineResource=K,exports.defineSystem=le,exports.defineTag=F,exports.findEntityByName=function(e,t){const n=e.getEntitiesWithComponents([Y]);for(const s of n){const n=e.get(s,Y);if(n&&n.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 n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}},exports.getComponentDefaults=function(e){const t=q[e];if(t)return{...t._default};const n=U(e);return n?{...n._default}:null},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=U,exports.initDrawAPI=Ft,exports.initGLDebugAPI=cn,exports.initGeometryAPI=Xt,exports.initMaterialAPI=at,exports.initPostProcessAPI=Jt,exports.initRendererAPI=rn,exports.inputPlugin=fe,exports.instantiatePrefab=async function(e,t,n){const{entities:s,rootId:r}=await Tn(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}))},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}},exports.intersectRects=Te,exports.invertMatrix4=Ae,exports.isBuiltinComponent=D,exports.isEditor=function(){return On},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!On},exports.isTextureRef=nt,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=bt,exports.loadPhysicsModule=An,exports.loadRuntimeScene=$n,exports.loadSceneData=wt,exports.loadSceneWithAssets=vt,exports.platformFetch=n,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,n){return t().instantiateWasm(e,n)},exports.platformReadFile=s,exports.platformReadTextFile=r,exports.pointInWorldRect=Re,exports.quat=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s}),exports.registerDrawCallback=function(e,t){hn.set(e,t)},exports.registerEmbeddedAssets=function(e,t){const n=e.getResource(Ct);n&&n.registerEmbeddedAssets(t)},exports.registerMaterialCallback=xt,exports.screenToWorld=Ee,exports.setEditorMode=function(e){On=e},exports.shutdownDrawAPI=Ut,exports.shutdownGLDebugAPI=un,exports.shutdownGeometryAPI=Vt,exports.shutdownMaterialAPI=lt,exports.shutdownPostProcessAPI=Kt,exports.shutdownRendererAPI=on,exports.textInputPlugin=et,exports.textPlugin=Pe,exports.uiInteractionPlugin=je,exports.uiLayoutPlugin=qe,exports.uiMaskPlugin=Ue,exports.unregisterDrawCallback=pn,exports.updateCameraAspectRatio=function(e,t){const n=e.getEntitiesWithComponents([H]);for(const s of n){const n=e.get(s,H);n&&(n.aspectRatio=t,e.insert(s,H,n))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),exports.vec4=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,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((n,s)=>{d().writeFile({filePath:e,data:t,success:()=>n(),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 713c24d15..76e0cecc5 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 h(e,n){return t().createCanvas(e,n)}function d(){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 _(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 y(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 v(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 b=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 b||(b=wx.createCanvas(),b.width=e,b.height=t,S=b.getContext("2d")),(b.width<e||b.height<t)&&(b.width=Math.max(b.width,e),b.height=Math.max(b.height,t)),{canvas:b,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 M(e){return C(await P(e))}let T=!1;const E=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return _(e)}async readTextFile(e){return y(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 z(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=z("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),H=z("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),L=z("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 j=0;function N(e,t){const n=++j;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=N(e,t);return n.set(e,r),K(e,t,!1),r}function Y(e){const t=X(),n=t.get(e);if(n)return n;const s=N(e,{});return t.set(e,s),K(e,{},!0),s}function G(e){return X().get(e)}function q(){X().clear()}function K(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function J(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function Q(e){return!0===e._builtin}const Z=J("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=J("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=J("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=J("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=J("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),re=J("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),oe=J("Parent",{entity:0}),ie=J("Children",{entities:[]}),ae=J("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:F}),le=J("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:$,BoxCollider:D,CircleCollider:H,CapsuleCollider:L};function he(e){const t=ue[e];if(t)return{...t._default};const n=G(e);return n?{...n._default}:null}let de=0;function fe(e,t){const n=++de;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 _e{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 ye=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&&"mut"===e._type}function ve(...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 be{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 Me;!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"}(Me||(Me={}));let Te=0;function Ee(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:Me.Update,system:e})}function Fe(e){Ae().push({schedule:Me.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 be(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(Me.Last,Ee([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ze=new We;function $e(e){if(null==e||"object"!=typeof e||Array.isArray(e))return e;const t=e;if("r"in t&&"g"in t&&"b"in t&&"a"in t&&!("x"in t))return{x:t.r,y:t.g,z:t.b,w:t.a};const n={};for(const e of Object.keys(t)){const s=t[e];n[e]=null==s||"object"!=typeof s||Array.isArray(s)?s:$e(s)}return n}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={...t._default,...n};if(this.cppRegistry_){const n=`add${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e,$e(s))}return s}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 je=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,dirty:!0});class Ne{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(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),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=r?Math.ceil(o):h+2*u,p=r?Math.ceil(i):d+2*u;if(r&&e.overflow===Oe.Ellipsis&&d>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const 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===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 v=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,v),v+=c}r&&e.overflow===Oe.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 M=P.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{textureHandle:M,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}});class Ve{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Ne(t),s=e.world;e.addSystemToSchedule(Me.PreUpdate,Ee([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,je));const e=s.getEntitiesWithComponents([je]);for(const t of e){const e=s.get(t,je);if(!e.dirty)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 r=s.has(t,Xe)?s.get(t,Xe):null,o=n.renderForEntity(t,e,r),i=s.get(t,te);i.texture=o.textureHandle,i.size.x=o.width,i.size.y=o.height,i.uvOffset.x=0,i.uvOffset.y=0,i.uvScale.x=1,i.uvScale.y=1,s.insert(t,te,i),e.dirty=!1}}))}}const Ye=new Ve,Ge=V("UIMask",{enabled:!0});function qe(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 Ke(e,t,n,s,r,o,i,a,l,c,u){const h=e-n*r,d=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(h,f),[y,w]=m(d,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 Je(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],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=h*g-d*m,M=h*_-f*m,T=h*y-p*m,E=d*_-f*g,A=d*y-p*g,R=f*y-p*_;let F=w*R-x*A+v*E+b*T-S*M+P*C;return 0===F||(F=1/F,n[0]=(l*R-c*A+u*E)*F,n[1]=(o*A-r*R-i*E)*F,n[2]=(g*P-_*S+y*b)*F,n[3]=(f*S-d*P-p*b)*F,n[4]=(c*T-a*R-u*M)*F,n[5]=(s*R-o*T+i*M)*F,n[6]=(_*v-m*P-y*x)*F,n[7]=(h*P-f*v+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*v+y*w)*F,n[11]=(d*v-h*S-p*w)*F,n[12]=(l*M-a*E-c*C)*F,n[13]=(s*E-r*M+o*C)*F,n[14]=(g*x-m*b-_*w)*F,n[15]=(h*b-d*x+f*w)*F),n}function Qe(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:u/h}}function Ze(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 et(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 Ke(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function tt(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Ge]);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,Ge).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 h(s,u){const d=e.getChildEntities(n,s);for(const n of d){let s=u;if(c.has(n)){const e=et(t,n,r,o,i,a,l);e&&(s=qe(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of u){const n=et(t,e,r,o,i,a,l);n&&h(e,n)}}(e,t,n,l,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class nt{build(e){if(!e.wasmModule)return;const t=e.pipeline_;t&&t.setMaskProcessor(tt(e.wasmModule,e.world))}}const st=new nt,rt=V("Interactable",{enabled:!0}),ot=V("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var it;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(it||(it={}));const at=V("Button",{state:it.Normal,transition:null});class lt{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 ct=fe(new lt,"UIEvents"),ut=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"),ht=new Float32Array(16);class dt{build(e){const t=e.world,n=new lt;e.insertResource(ct,n);let s=null,r=null;e.addSystemToSchedule(Me.PreUpdate,Ee([pe(ke),pe(ut)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([ot]);for(const e of i){const n=t.get(e,ot);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;Je(o.viewProjection,ht);const u=Qe(l,c,ht,o.vpX,o.vpY,o.vpW,o.vpH),h=t.getEntitiesWithComponents([rt,Xe,ee]);let d=null,f=-1/0;for(const e of h){t.has(e,ot)||t.insert(e,ot);if(!t.get(e,rt).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(Ze(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,d=e)}}if(s!==d){if(null!==s&&t.valid(s)&&t.has(s,ot)){t.get(s,ot).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,ot).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,ot);e.pressed=!0,e.justPressed=!0,r=d,n.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,ot)){const e=t.get(r,ot);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Me.Update,Ee([],()=>{const e=t.getEntitiesWithComponents([at]);for(const n of e){if(t.has(n,rt)||t.insert(n,rt,{enabled:!0}),!t.has(n,ot))continue;const e=t.get(n,ot),s=t.get(n,at),r=t.get(n,rt),o=s.state;if(r.enabled?e.pressed?s.state=it.Pressed:e.hovered?s.state=it.Hovered:s.state=it.Normal:s.state=it.Disabled,o!==s.state&&s.transition&&t.has(n,te)){const e=t.get(n,te),r=s.transition;switch(s.state){case it.Normal:e.color={...r.normalColor};break;case it.Hovered:e.color={...r.hoveredColor};break;case it.Pressed:e.color={...r.pressedColor};break;case it.Disabled:e.color={...r.disabledColor}}t.insert(n,te,e)}}},{name:"ButtonSystem"}))}}const ft=new dt,pt=Y("ScreenSpace");function mt(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,h=o.bottom+t.y*a;let d,f,p,m;if(l===c&&u===h){const e=l+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;d=e-s,f=t-o,p=e+s,m=t+o}else d=l+n.x,f=u+n.y,p=c+s.x,m=h+s.y;return{centerX:.5*(d+p),centerY:.5*(f+m),width:p-d,height:m-f,rect:{left:d,bottom:f,right:p,top:m}}}function gt(e,t,n,s,r,o){if(!e.has(t,Xe))return;const i=e.get(t,Xe),a=mt(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)&&gt(e,t,a.rect,a.centerX,a.centerY,!1)}class _t{build(e){const t=e.world;e.addSystemToSchedule(Me.PreUpdate,Ee([pe(ut)],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([pt,Xe,Z]);for(const e of o)gt(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const yt=new _t,wt=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 xt{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=h(512,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,u=0;const d=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,wt);if(t.readOnly)return;let s=d.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),d.value=s),s!==t.value){t.value=s;e.getResource(ct).emit(i,"change")}t.cursorPos=d.selectionStart??s.length,t.dirty=!0,g()}function p(e){if(i===e)return;m();const t=n.get(e,wt);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,d.value=t.value,d.selectionStart=t.cursorPos,d.selectionEnd=t.cursorPos,d.focus(),g())}function m(){if(null!==i&&n.valid(i)&&n.has(i,wt)){const e=n.get(i,wt);e.focused=!1,e.dirty=!0}i=null,d.blur()}function g(){l=!0,c=0}function _(e,i,a,c){(r.width<a||r.height<c)&&(r.width=bt(Math.max(r.width,a)),r.height=bt(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 h=0===i.value.length,d=h?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=h?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=vt(o,d,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(d,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=vt(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,te);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,te,b)}d.addEventListener("input",()=>{a||null===i||f()}),d.addEventListener("compositionstart",()=>{a=!0}),d.addEventListener("compositionend",()=>{a=!1,f()}),d.addEventListener("keydown",t=>{if(null===i)return;if("Escape"===t.key)return void m();const s=n.get(i,wt);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(ct).emit(i,"submit"),void m()}}),d.addEventListener("blur",()=>{if(null!==i&&n.valid(i)&&n.has(i,wt)){const e=n.get(i,wt);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(Me.PreUpdate,Ee([pe(ct)],e=>{const t=n.getEntitiesWithComponents([wt,rt]);for(const e of t){if(!n.has(e,ot))continue;if(n.get(e,ot).justPressed)return void p(e)}if(null!==i){const e=n.getEntitiesWithComponents([rt]);for(const t of e){if(n.has(t,wt))continue;if(!n.has(t,ot))continue;if(n.get(t,ot).justPressed)return void m()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Me.PreUpdate,Ee([],()=>{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,wt)))){n.get(i,wt).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,wt)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([wt,Xe]);for(const e of a){const t=n.get(e,wt);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}),_(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function vt(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 bt(e){let t=1;for(;t<e;)t*=2;return t}const St=new xt;var Pt;function Ct(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"}(Pt||(Pt={}));let Mt=null,Tt=null,Et=1;const At=new Map;function Rt(e){Mt=e,Tt=e.getResourceManager(),Ht()}function Ft(){0!==kt&&Mt&&(Mt._free(kt),kt=0),At.clear(),Et=1,It=!1,Tt=null,Mt=null}function Ut(){if(!Tt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Tt}const Bt={createShader:(e,t)=>Ut().createShader(e,t),releaseShader(e){e>0&&Ut().releaseShader(e)},create(e){const t=Et++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Pt.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return At.set(t,n),t},get:e=>At.get(e),setUniform(e,t,n){const s=At.get(e);s&&s.uniforms.set(t,n)},getUniform(e,t){const n=At.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=At.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=At.get(e);return t?.blendMode??Pt.Normal},setDepthTest(e,t){const n=At.get(e);n&&(n.depthTest=t)},getShader(e){const t=At.get(e);return t?.shader??0},release(e){At.delete(e)},isValid:e=>At.has(e),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??Pt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=At.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Et++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return At.set(n,s),n},toAssetData(e,t){const n=At.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=At.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let It=!1,kt=0;const Wt=4096,zt=new Map;let $t=null;function Dt(e){const t=(0===kt&&Mt&&(kt=Mt._malloc(Wt)),kt);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>Wt)break;let e=zt.get(a);e||($t||($t=new TextEncoder),e=$t.encode(a),zt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function Ht(){if(!Mt||It)return;Mt.materialDataProvider=(e,t,n,s,r)=>{const o=At.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}=Dt(o.uniforms);Mt.HEAPU32[s>>2]=i,Mt.HEAPU32[r>>2]=a},It=!0}const Lt={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class Ot{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&&(Bt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Bt.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:Bt.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 jt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();n.set(s.id,t),e.insert(t,ce,{value:s.name});for(const n of s.components)Xt(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 Nt(e,t,n){const s=new Map,r=n?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();s.set(i.id,t),e.insert(t,ce,{value:i.name});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}}Xt(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 Xt(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,je,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,Ge,s);break;case"Interactable":e.insert(t,rt,s);break;case"Button":e.insert(t,at,s);break;case"RigidBody":e.insert(t,$,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=G(n.type);r?e.insert(t,r,s):console.warn(`Unknown component type: ${n.type}`);break}}}function Vt(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 Yt(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 Gt{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 qt{constructor(e){this.textureCache_=new Gt,this.shaderCache_=new Gt,this.jsonCache_=new Gt,this.textCache_=new Gt,this.binaryCache_=new Gt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Gt,this.embedded_=new Map,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.module_=e,this.canvas_=h(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 Ot(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n)}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.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 loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return Nt(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];if(e.textures)for(const s of e.textures)n.push(this.loadTexture(s).then(e=>{t.textures.set(s,e)}));if(e.materials)for(const s of e.materials)n.push(this.loadMaterial(s).then(e=>{t.materials.set(s,e)}));if(e.spine)for(const s of e.spine){const e=`${s.skeleton}:${s.atlas}`;n.push(this.loadSpine(s.skeleton,s.atlas,s.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const s of e.json)n.push(this.loadJson(s).then(e=>{t.json.set(s,e)}));if(e.text)for(const s of e.text)n.push(this.loadText(s).then(e=>{t.text.set(s,e)}));if(e.binary)for(const s of e.binary)n.push(this.loadBinary(s).then(e=>{t.binary.set(s,e)}));return await Promise.all(n),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 loadByAddress(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"json":return this.loadJson(e.path);case"text":return this.loadText(e.path);default:return this.loadBinary(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e)switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(e=>{t.textures.set(s.path,e)}));break;case"material":n.push(this.loadMaterial(s.path).then(e=>{t.materials.set(s.path,e)}));break;case"json":n.push(this.loadJson(s.path).then(e=>{t.json.set(s.path,e)}));break;case"text":n.push(this.loadText(s.path).then(e=>{t.text.set(s.path,e)}));break;default:n.push(this.loadBinary(s.path).then(e=>{t.binary.set(s.path,e)}))}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)??n;return new Promise((n,r)=>{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=()=>r(new Error(`Failed to load image: ${e}`)),o.src=s})}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;if(!await c(t))throw new Error(`Shader file not found: ${e}`);const n=await l(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:s,fragment:r}=this.parseEsShader(n);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return Bt.createShader(s,r)}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 e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const n=await l(t);return JSON.parse(n)}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 e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):l(t)}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 e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):a(t)}const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Kt=fe(null,"Assets");class Jt{build(e){const t=e.wasmModule;t?e.insertResource(Kt,new qt(t)):console.warn("AssetPlugin: No WASM module available")}}const Qt=new Jt;function Zt(e,t){const n=e.getResource(Kt);n&&n.registerEmbeddedAssets(t)}let en=null,tn=0,nn=0,sn=0;const rn=new Float32Array(256);function on(e){en=e,tn=en._malloc(64),nn=en._malloc(64),sn=en._malloc(1024)}function an(){en&&(tn&&(en._free(tn),tn=0),nn&&(en._free(nn),nn=0),sn&&(en._free(sn),sn=0)),en=null}function ln(){if(!en)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return en}const cn={r:1,g:1,b:1,a:1},un={begin(e){const t=ln();t.HEAPF32.set(e,tn/4),t.draw_begin(tn)},end(){ln().draw_end()},line(e,t,n,s=1){ln().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){ln().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){ln().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){ln().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){ln().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=cn){ln().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=cn){ln().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){ln().draw_setLayer(e)},setDepth(e){ln().draw_setDepth(e)},getDrawCallCount:()=>en?en.draw_getDrawCallCount():0,getPrimitiveCount:()=>en?en.draw_getPrimitiveCount():0,setBlendMode(e){ln().draw_setBlendMode(e)},setDepthTest(e){ln().draw_setDepthTest(e)},drawMesh(e,t,n){const s=ln();s.HEAPF32.set(n,nn/4),s.draw_mesh(e,t,nn)},drawMeshWithMaterial(e,t,n){const s=ln(),r=Bt.get(t);if(!r)return;if(un.setBlendMode(r.blendMode),un.setDepthTest(r.depthTest),0===r.uniforms.size)return void un.drawMesh(e,r.shader,n);s.HEAPF32.set(n,nn/4);let o=0,i=0;for(const[e,t]of r.uniforms){const n=dn(e);if(!(n<0)){if(Ct(t))rn[o++]=10,rn[o++]=n,rn[o++]=t.slot??i++,rn[o++]=t.textureId;else if("number"==typeof t)rn[o++]=1,rn[o++]=n,rn[o++]=t;else if(Array.isArray(t)){rn[o++]=t.length,rn[o++]=n;for(let e=0;e<t.length;e++)rn[o++]=t[e]}else"w"in t?(rn[o++]=4,rn[o++]=n,rn[o++]=t.x,rn[o++]=t.y,rn[o++]=t.z,rn[o++]=t.w):"z"in t?(rn[o++]=3,rn[o++]=n,rn[o++]=t.x,rn[o++]=t.y,rn[o++]=t.z):(rn[o++]=2,rn[o++]=n,rn[o++]=t.x,rn[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(rn.subarray(0,o),sn/4),s.draw_meshWithUniforms(e,r.shader,nn,sn,o)):s.draw_mesh(e,r.shader,nn)}},hn={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function dn(e){return hn[e]??-1}var fn;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(fn||(fn={}));let pn=null,mn=0,gn=0,_n=0;function yn(e){pn=e,mn=pn._malloc(262144),gn=pn._malloc(65536),_n=pn._malloc(256)}function wn(){pn&&(mn&&pn._free(mn),gn&&pn._free(gn),_n&&pn._free(_n),mn=0,gn=0,_n=0),pn=null}function xn(){if(!pn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return pn}const vn={create(e){const t=xn(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,mn/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,_n,r).set(o),t.geometry_init(n,mn,s,_n,r,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,gn,s).set(e.indices),t.geometry_setIndices16(n,gn,s)}else{new Uint32Array(t.HEAPU8.buffer,gn,s).set(e.indices),t.geometry_setIndices32(n,gn,s)}}return n},updateVertices(e,t,n=0){const s=xn(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,mn/4),s.geometry_updateVertices(e,mn,r,n)},release(e){e>0&&xn().geometry_release(e)},isValid:e=>!(!pn||e<=0)&&pn.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return vn.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:fn.Float2},{name:"a_texCoord",type:fn.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const 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 vn.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:fn.Float2},{name:"a_texCoord",type:fn.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,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 vn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:fn.Float2},{name:"a_texCoord",type:fn.Float2}],indices:new Uint16Array(i)})}};let bn=null;function Sn(e){bn=e}function Pn(){bn&&Mn.isInitialized()&&Mn.shutdown(),bn=null}function Cn(){if(!bn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return bn}const Mn={init:(e,t)=>Cn().postprocess_init(e,t),shutdown(){Cn().postprocess_shutdown()},resize(e,t){Cn().postprocess_resize(e,t)},addPass:(e,t)=>Cn().postprocess_addPass(e,t),removePass(e){Cn().postprocess_removePass(e)},setEnabled(e,t){Cn().postprocess_setPassEnabled(e,t)},isEnabled:e=>Cn().postprocess_isPassEnabled(e),setUniform(e,t,n){Cn().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Cn().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Cn().postprocess_begin()},end(){Cn().postprocess_end()},getPassCount:()=>Cn().postprocess_getPassCount(),isInitialized:()=>!!bn&&bn.postprocess_isInitialized(),setBypass(e){Cn().postprocess_setBypass(e)},isBypassed:()=>!bn||bn.postprocess_isBypassed(),createBlur:()=>Bt.createShader(Tn,"#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:()=>Bt.createShader(Tn,"#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:()=>Bt.createShader(Tn,"#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:()=>Bt.createShader(Tn,"#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")},Tn="#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 En;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(En||(En={}));let An=null,Rn=0;function Fn(e){An=e,Rn=An._malloc(64)}function Un(){An&&Rn&&(An._free(Rn),Rn=0),An=null}const Bn={init(e,t){An?.renderer_init(e,t)},resize(e,t){An?.renderer_resize(e,t)},begin(e,t){An&&Rn&&(An.HEAPF32.set(e,Rn/4),An.renderer_begin(Rn,t??0))},flush(){An?.renderer_flush()},end(){An?.renderer_end()},submitSprites(e){An&&An.renderer_submitSprites(e._cpp)},submitBitmapText(e){An&&An.renderer_submitBitmapText(e._cpp)},submitSpine(e){An&&An.renderer_submitSpine?.(e._cpp)},setStage(e){An?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>An?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){An?.renderer_releaseTarget(e)},getTargetTexture:e=>An?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>An?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){An?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){An?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){An?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){An?.renderer_clearBuffers(e)},getStats:()=>An?{drawCalls:An.renderer_getDrawCalls(),triangles:An.renderer_getTriangles(),sprites:An.renderer_getSprites(),text:An.renderer_getText(),spine:An.renderer_getSpine?.()??0,meshes:An.renderer_getMeshes(),culled:An.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let In=null;function kn(e){In=e}function Wn(){In=null}const zn={enable(){In?.gl_enableErrorCheck(!0)},disable(){In?.gl_enableErrorCheck(!1)},check:e=>In?.gl_checkErrors(e)??0,diagnose(){In?.renderer_diagnose()}},$n=new Map;function Dn(e,t){$n.set(e,t)}function Hn(e){$n.delete(e)}function Ln(){$n.clear()}class On{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}setSpineRenderer(e){this.spineRenderer_=e}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_||(Bn.resize(s,r),Mn.isInitialized()&&Mn.getPassCount()>0&&Mn.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),Bn.setViewport(0,0,s,r),Bn.clearBuffers(3),Bn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),Bn.submitSprites(t),Bn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Bn.submitSpine(t),Bn.flush(),this.executeDrawCallbacks(n,o),Bn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;Bn.setViewport(s.x,s.y,s.w,s.h),Bn.setScissor(s.x,s.y,s.w,s.h,!0),Bn.clearBuffers(r),Bn.setScissor(0,0,0,0,!1),Bn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Bn.submitSprites(t),Bn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Bn.submitSpine(t),Bn.flush(),this.executeDrawCallbacks(n,o),Bn.end()}executeDrawCallbacks(e,t){const n=$n;if(n.size>0){un.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)}un.end();for(const e of s)Hn(e)}}}class jn{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=d(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.runSchedule(Me.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Me.FixedPreUpdate),this.runSchedule(Me.FixedUpdate),this.runSchedule(Me.FixedPostUpdate);this.runSchedule(Me.PreUpdate),this.runSchedule(Me.Update),this.runSchedule(Me.PostUpdate),this.runSchedule(Me.Last),requestAnimationFrame(this.mainLoop)},this.world_=new De,this.resources_=new _e;for(const e of Object.values(Me))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new jn}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(Me.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Me.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}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(ye,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Me.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Wn(),Un(),Pn(),wn(),Ft(),an()}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(ye);t.delta=e,t.elapsed+=e,t.frameCount++}}function Nn(e,t){const n=jn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),on(e),Rt(e),yn(e),Sn(e),Fn(e),kn(e);const r=new On;n.pipeline_=r;let o=d();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r){const o=Gn(e,s,t,r),i=n.getResource(ut);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(ut,{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(),l=e.registry_getCanvasEntity(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;Bn.setClearColor(e.r,e.g,e.b,e.a)}const c=(d()-o)/1e3;Bn.resize(t,n),Mn.isInitialized()&&Mn.getPassCount()>0&&!Mn.isBypassed()&&Mn.resize(t,n);const u=Gn(e,s,t,n);if(a(t,n),0===u.length)r.render({registry:{_cpp:s},viewProjection:Vn,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})}Bn.setViewport(0,0,t,n)}}};return n.addSystemToSchedule(Me.First,l),n.addSystemToSchedule(Me.Last,c),n.addPlugin(Qt),n.addPlugin(ze),n.addPlugin(Ye),n.addPlugin(st),n.addPlugin(yt),n.addPlugin(ft),n.addPlugin(St),n}function Xn(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 Vn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Yn(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 Gn(e,t,n,s){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,h=0,d=0;if(1===r.projectionType){if(d=r.orthoSize,o){d=Yn(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}h=d*c,u=Kn(-h,h,-d,d,-r.farPlane,r.farPlane)}else u=Qn(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=es(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:ts(u,f),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:h,halfH:d,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const qn=new Float32Array(16);function Kn(e,t,n,s,r,o){const i=qn;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 Jn=new Float32Array(16);function Qn(e,t,n,s){const r=Jn;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 Zn=new Float32Array(16);function es(e,t,n){const s=Zn;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 ts(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 ns(e,t){if(t)return t();return(0,(await import(e)).default)()}const ss=fe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),rs=fe(null,"PhysicsAPI");function os(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function is(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class as{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(ss,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=ns(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(Me.PostUpdate,Ee([pe(ye)],a=>{const l=i.getEntitiesWithComponents([$,Z,ee]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,$),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=os(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),ls(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=os(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 h=a,d=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=os(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),u=Math.sin(-s);h=(r*i-o*u)/(0!==n.scale.x?n.scale.x:1),d=(r*u+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}u.position.x=h,u.position.y=d;const p=is(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(ss,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.__physicsModule=s,e.insertResource(rs,cs._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=s}}function ls(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 cs{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(cs.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 us(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 hs(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 ds(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,h=a+a,d=l+l,f=c+c,p=a*h,m=a*d,g=a*f,_=l*d,y=l*f,w=c*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(_+w))*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 fs(e,t,n,s,r,o,i){const a=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]=us(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,a);let l={},c=null;if(r&&(c=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),l=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 h,d;if(u){const e=r.readBinary(i);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=r.readText(i),n=(new TextEncoder).encode(e);d=n.length,h=t._malloc(d+1),t.HEAPU8.set(n,h),t.HEAPU8[h+d]=0}const f=n.loadSkeleton(h,d,s,s.length,u);if(t._free(h),f<0)continue;o[i]=f;const p=hs(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=us(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,c,n,s)),o){new as("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const u=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=Bt.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=Bt.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),h=jt(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,a,h),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,u,h),r&&c){const s=function(e,t,n,s){const r={};for(const o of t.entities)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}(c,n,l,h);!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,h=a?.timeScale??1;u&&s.update(i,l*h);let d=0;if(c.has(o,ee)){const e=ds(c.get(o,ee),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,h,f);const p=n.HEAPU32[h>>2],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,d),t._free(y),t._free(w),n._free(c),n._free(u),n._free(h),n._free(f)}d&&t._free(d)}})}(e,t,r,c,s)}}class ps{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;for(const s of e.entities)for(const e of s.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)}"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const s=[];for(const e of t)s.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of n)s.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(s)}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 ms{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_)try{const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new ps(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.__spineInitPromise;if(r){s=(await r).controller.raw}await fs(this.app_,this.app_.wasmModule,t,n,s),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}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 gs={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Bn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Bn.getTargetTexture(n),width:e.width,height:e.height}},release(e){Bn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Bn.releaseRenderTarget(e._handle),gs.create({width:t,height:n,depth:!0})),begin(e,t){Bn.begin(t,e._handle)},end(){Bn.end()},getDepthTexture:e=>Bn.getTargetDepthTexture(e._handle)};let _s=!1;function ys(e){_s=e}function ws(){return _s}function xs(){return!_s}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=E;export{jn as App,Jt as AssetPlugin,qt as AssetServer,Kt as Assets,Gt as AsyncCache,ae as BitmapText,Pt as BlendMode,O as BodyType,D as BoxCollider,at as Button,it as ButtonState,ne as Camera,se as Canvas,L as CapsuleCollider,ie as Children,H as CircleCollider,Se as Commands,Ce as CommandsInstance,fn as DataType,un as Draw,Pe as EntityCommands,zn as GLDebug,vn as Geometry,A as INVALID_ENTITY,F as INVALID_FONT,R as INVALID_TEXTURE,ke as Input,We as InputPlugin,Ie as InputState,rt as Interactable,Z as LocalTransform,Bt as Material,Ot as MaterialLoader,we as Mut,ce as Name,oe as Parent,cs as Physics,ss as PhysicsEvents,as as PhysicsPlugin,Mn as PostProcess,ms as PreviewPlugin,ve as Query,be as QueryInstance,On as RenderPipeline,En as RenderStage,gs as RenderTexture,Bn as Renderer,pe as Res,me as ResMut,$ as RigidBody,Me as Schedule,pt as ScreenSpace,Lt as ShaderSources,le as SpineAnimation,te as Sprite,Be as SystemRunner,je as Text,He as TextAlign,wt as TextInput,xt as TextInputPlugin,Oe as TextOverflow,Ve as TextPlugin,Ne as TextRenderer,Le as TextVerticalAlign,ye as Time,ut as UICameraInfo,lt as UIEventQueue,ct as UIEvents,ot as UIInteraction,dt as UIInteractionPlugin,_t as UILayoutPlugin,Ge as UIMask,nt as UIMaskPlugin,Xe as UIRect,re as Velocity,ps as WebAssetProvider,De as World,ee as WorldTransform,Fe as addStartupSystem,Re as addSystem,Ue as addSystemToSchedule,Qt as assetPlugin,Ln as clearDrawCallbacks,q as clearUserComponents,k as color,mt as computeUIRectLayout,tt as createMaskProcessor,Nn as createWebApp,V as defineComponent,fe as defineResource,Ee as defineSystem,Y as defineTag,Yt as findEntityByName,Xn as flushPendingSystems,he as getComponentDefaults,t as getPlatform,s as getPlatformType,G as getUserComponent,on as initDrawAPI,kn as initGLDebugAPI,yn as initGeometryAPI,Rt as initMaterialAPI,Sn as initPostProcessAPI,Fn as initRendererAPI,ze as inputPlugin,qe as intersectRects,Je as invertMatrix4,Q as isBuiltinComponent,ws as isEditor,n as isPlatformInitialized,xs as isRuntime,Ct as isTextureRef,r as isWeChat,o as isWeb,Xt as loadComponent,ns as loadPhysicsModule,fs as loadRuntimeScene,jt as loadSceneData,Nt as loadSceneWithAssets,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Ze as pointInWorldRect,W as quat,Dn as registerDrawCallback,Zt as registerEmbeddedAssets,Ht as registerMaterialCallback,Qe as screenToWorld,ys as setEditorMode,an as shutdownDrawAPI,Wn as shutdownGLDebugAPI,wn as shutdownGeometryAPI,Ft as shutdownMaterialAPI,Pn as shutdownPostProcessAPI,Un as shutdownRendererAPI,St as textInputPlugin,Ye as textPlugin,ft as uiInteractionPlugin,yt as uiLayoutPlugin,st as uiMaskPlugin,Hn as unregisterDrawCallback,Vt as updateCameraAspectRatio,U as vec2,B as vec3,I as vec4,Ke as worldRectToScreen,w as wxFileExists,x as wxFileExistsSync,C as wxGetImagePixels,P as wxLoadImage,M as wxLoadImagePixels,_ as wxReadFile,y as wxReadTextFile,v as wxWriteFile};
+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}function f(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 z(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=z("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),L=z("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),H=z("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 j=0;function N(e,t){const n=++j;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=N(e,t);return n.set(e,r),J(e,t,!1),r}function Y(e){const t=X(),n=t.get(e);if(n)return n;const s=N(e,{});return t.set(e,s),J(e,{},!0),s}function G(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:$,BoxCollider:D,CircleCollider:L,CapsuleCollider:H};function he(e){const t=ue[e];if(t)return{...t._default};const n=G(e);return n?{...n._default}:null}let de=0;function fe(e,t){const n=++de;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 ze=new We;function $e(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}:$e(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,$e(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 Le,He,Oe;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Le||(Le={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(He||(He={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Oe||(Oe={}));const je=V("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Le.Left,verticalAlign:He.Top,wordWrap:!0,overflow:Oe.Visible,lineHeight:1.2,dirty:!0});class Ne{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(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),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=r?Math.ceil(o):h+2*u,p=r?Math.ceil(i):d+2*u;if(r&&e.overflow===Oe.Ellipsis&&d>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const 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 He.Top:x=u;break;case He.Middle:x=(p-w)/2;break;case He.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 Le.Left:s=u;break;case Le.Center:s=f/2;break;case Le.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 Le.Left:return"left";case Le.Center:return"center";case Le.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}});class Ve{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Ne(t),s=e.world;e.addSystemToSchedule(Ee.PreUpdate,Me([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,je));const e=s.getEntitiesWithComponents([je]);for(const t of e){const e=s.get(t,je);if(!e.dirty)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 r=s.has(t,Xe)?s.get(t,Xe):null,o=n.renderForEntity(t,e,r),i=s.get(t,te);i.texture=o.textureHandle,i.size.x=o.width,i.size.y=o.height,i.uvOffset.x=0,i.uvOffset.y=0,i.uvScale.x=1,i.uvScale.y=1,s.insert(t,te,i),e.dirty=!1}}))}}const Ye=new Ve,Ge=V("UIMask",{enabled:!0});function qe(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 Je(e,t,n,s,r,o,i,a,l,c,u){const h=e-n*r,d=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(h,f),[_,w]=m(d,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 Ke(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],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=h*g-d*m,E=h*y-f*m,T=h*_-p*m,M=d*y-f*g,A=d*_-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-d*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]=(h*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]=(d*b-h*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]=(h*v-d*x+f*w)*F),n}function Qe(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:u/h}}function Ze(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 et(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 Je(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function tt(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Ge]);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,Ge).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 h(s,u){const d=e.getChildEntities(n,s);for(const n of d){let s=u;if(c.has(n)){const e=et(t,n,r,o,i,a,l);e&&(s=qe(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of u){const n=et(t,e,r,o,i,a,l);n&&h(e,n)}}(e,t,n,l,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class nt{build(e){if(!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(tt(e.wasmModule,e.world))}}const st=new nt,rt=V("Interactable",{enabled:!0}),ot=V("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var it;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(it||(it={}));const at=V("Button",{state:it.Normal,transition:null});class lt{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 ct=fe(new lt,"UIEvents"),ut=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"),ht=new Float32Array(16);class dt{build(e){const t=e.world,n=new lt;e.insertResource(ct,n);let s=null,r=null;e.addSystemToSchedule(Ee.PreUpdate,Me([pe(ke),pe(ut)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([ot]);for(const e of i){const n=t.get(e,ot);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;Ke(o.viewProjection,ht);const u=Qe(l,c,ht,o.vpX,o.vpY,o.vpW,o.vpH),h=t.getEntitiesWithComponents([rt,Xe,ee]);let d=null,f=-1/0;for(const e of h){t.has(e,ot)||t.insert(e,ot);if(!t.get(e,rt).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(Ze(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,d=e)}}if(s!==d){if(null!==s&&t.valid(s)&&t.has(s,ot)){t.get(s,ot).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,ot).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,ot);e.pressed=!0,e.justPressed=!0,r=d,n.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,ot)){const e=t.get(r,ot);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([at]);for(const n of e){if(t.has(n,rt)||t.insert(n,rt,{enabled:!0}),!t.has(n,ot))continue;const e=t.get(n,ot),s=t.get(n,at),r=t.get(n,rt),o=s.state;if(r.enabled?e.pressed?s.state=it.Pressed:e.hovered?s.state=it.Hovered:s.state=it.Normal:s.state=it.Disabled,o!==s.state&&s.transition&&t.has(n,te)){const e=t.get(n,te),r=s.transition;switch(s.state){case it.Normal:e.color={...r.normalColor};break;case it.Hovered:e.color={...r.hoveredColor};break;case it.Pressed:e.color={...r.pressedColor};break;case it.Disabled:e.color={...r.disabledColor}}t.insert(n,te,e)}}},{name:"ButtonSystem"}))}}const ft=new dt,pt=Y("ScreenSpace");function mt(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,h=o.bottom+t.y*a;let d,f,p,m;if(l===c&&u===h){const e=l+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;d=e-s,f=t-o,p=e+s,m=t+o}else d=l+n.x,f=u+n.y,p=c+s.x,m=h+s.y;return{centerX:.5*(d+p),centerY:.5*(f+m),width:p-d,height:m-f,rect:{left:d,bottom:f,right:p,top:m}}}function gt(e,t,n,s,r,o){if(!e.has(t,Xe))return;const i=e.get(t,Xe),a=mt(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)&&gt(e,t,a.rect,a.centerX,a.centerY,!1)}class yt{build(e){const t=e.world;e.addSystemToSchedule(Ee.PreUpdate,Me([pe(ut)],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([pt,Xe,Z]);for(const e of o)gt(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const _t=new yt,wt=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 xt{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=h(512,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,u=0;const d=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,wt);if(t.readOnly)return;let s=d.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),d.value=s),s!==t.value){t.value=s;e.getResource(ct).emit(i,"change")}t.cursorPos=d.selectionStart??s.length,t.dirty=!0,g()}function p(e){if(i===e)return;m();const t=n.get(e,wt);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,d.value=t.value,d.selectionStart=t.cursorPos,d.selectionEnd=t.cursorPos,d.focus(),g())}function m(){if(null!==i&&n.valid(i)&&n.has(i,wt)){const e=n.get(i,wt);e.focused=!1,e.dirty=!0}i=null,d.blur()}function g(){l=!0,c=0}function y(e,i,a,c){(r.width<a||r.height<c)&&(r.width=vt(Math.max(r.width,a)),r.height=vt(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 h=0===i.value.length,d=h?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=h?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=bt(o,d,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(d,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=bt(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)}d.addEventListener("input",()=>{a||null===i||f()}),d.addEventListener("compositionstart",()=>{a=!0}),d.addEventListener("compositionend",()=>{a=!1,f()}),d.addEventListener("keydown",t=>{if(null===i)return;if("Escape"===t.key)return void m();const s=n.get(i,wt);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(ct).emit(i,"submit"),void m()}}),d.addEventListener("blur",()=>{if(null!==i&&n.valid(i)&&n.has(i,wt)){const e=n.get(i,wt);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(Ee.PreUpdate,Me([pe(ct)],e=>{const t=n.getEntitiesWithComponents([wt,rt]);for(const e of t){if(!n.has(e,ot))continue;if(n.get(e,ot).justPressed)return void p(e)}if(null!==i){const e=n.getEntitiesWithComponents([rt]);for(const t of e){if(n.has(t,wt))continue;if(!n.has(t,ot))continue;if(n.get(t,ot).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,wt)))){n.get(i,wt).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,wt)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([wt,Xe]);for(const e of a){const t=n.get(e,wt);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 bt(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 vt(e){let t=1;for(;t<e;)t*=2;return t}const St=new xt;var Pt;function Ct(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"}(Pt||(Pt={}));let Et=null,Tt=null,Mt=1;const At=new Map;function Rt(e){Et=e,Tt=e.getResourceManager(),Lt()}function Ft(){0!==kt&&Et&&(Et._free(kt),kt=0),At.clear(),Mt=1,It=!1,Tt=null,Et=null}function Ut(){if(!Tt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Tt}const Bt={createShader:(e,t)=>Ut().createShader(e,t),releaseShader(e){e>0&&Ut().releaseShader(e)},create(e){const t=Mt++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Pt.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return At.set(t,n),t},get:e=>At.get(e),setUniform(e,t,n){const s=At.get(e);s&&s.uniforms.set(t,n)},getUniform(e,t){const n=At.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=At.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=At.get(e);return t?.blendMode??Pt.Normal},setDepthTest(e,t){const n=At.get(e);n&&(n.depthTest=t)},getShader(e){const t=At.get(e);return t?.shader??0},release(e){At.delete(e)},isValid:e=>At.has(e),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??Pt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=At.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 At.set(n,s),n},toAssetData(e,t){const n=At.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=At.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let It=!1,kt=0;const Wt=4096,zt=new Map;let $t=null;function Dt(e){const t=(0===kt&&Et&&(kt=Et._malloc(Wt)),kt);if(0===t||!Et)return{ptr:0,count:0};let n=0,s=0;const r=Et.HEAPU8,o=Et.HEAPU32,i=Et.HEAPF32;for(const[a,l]of e){if(n+128>Wt)break;let e=zt.get(a);e||($t||($t=new TextEncoder),e=$t.encode(a),zt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function Lt(){if(!Et||It)return;Et.materialDataProvider=(e,t,n,s,r)=>{const o=At.get(e);if(!o)return Et.HEAPU32[t>>2]=0,Et.HEAPU32[n>>2]=0,Et.HEAPU32[s>>2]=0,void(Et.HEAPU32[r>>2]=0);Et.HEAPU32[t>>2]=o.shader,Et.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Dt(o.uniforms);Et.HEAPU32[s>>2]=i,Et.HEAPU32[r>>2]=a},It=!0}const Ht={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 Ot{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&&(Bt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Bt.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:Bt.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 jt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();n.set(s.id,t),e.insert(t,ce,{value:s.name});for(const n of s.components)Xt(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 Nt(e,t,n){const s=new Map,r=n?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();s.set(i.id,t),e.insert(t,ce,{value:i.name});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}}Xt(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 Xt(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,je,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,Ge,s);break;case"Interactable":e.insert(t,rt,s);break;case"Button":e.insert(t,at,s);break;case"RigidBody":e.insert(t,$,s);break;case"BoxCollider":e.insert(t,D,s);break;case"CircleCollider":e.insert(t,L,s);break;case"CapsuleCollider":e.insert(t,H,s);break;default:{const r=G(n.type);r?e.insert(t,r,s):console.warn(`Unknown component type: ${n.type}`);break}}}function Vt(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 Yt(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 Gt{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 qt{constructor(e){this.textureCache_=new Gt,this.shaderCache_=new Gt,this.jsonCache_=new Gt,this.textCache_=new Gt,this.binaryCache_=new Gt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Gt,this.prefabCache_=new Gt,this.embedded_=new Map,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.module_=e,this.canvas_=h(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 Ot(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n)}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 Nt(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];if(e.textures)for(const s of e.textures)n.push(this.loadTexture(s).then(e=>{t.textures.set(s,e)}));if(e.materials)for(const s of e.materials)n.push(this.loadMaterial(s).then(e=>{t.materials.set(s,e)}));if(e.spine)for(const s of e.spine){const e=`${s.skeleton}:${s.atlas}`;n.push(this.loadSpine(s.skeleton,s.atlas,s.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const s of e.json)n.push(this.loadJson(s).then(e=>{t.json.set(s,e)}));if(e.text)for(const s of e.text)n.push(this.loadText(s).then(e=>{t.text.set(s,e)}));if(e.binary)for(const s of e.binary)n.push(this.loadBinary(s).then(e=>{t.binary.set(s,e)}));return await Promise.all(n),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 loadByAddress(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"json":return this.loadJson(e.path);case"text":return this.loadText(e.path);default:return this.loadBinary(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e)switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(e=>{t.textures.set(s.path,e)}));break;case"material":n.push(this.loadMaterial(s.path).then(e=>{t.materials.set(s.path,e)}));break;case"json":n.push(this.loadJson(s.path).then(e=>{t.json.set(s.path,e)}));break;case"text":n.push(this.loadText(s.path).then(e=>{t.text.set(s.path,e)}));break;default:n.push(this.loadBinary(s.path).then(e=>{t.binary.set(s.path,e)}))}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)??n;return new Promise((n,r)=>{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=()=>r(new Error(`Failed to load image: ${e}`)),o.src=s})}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;if(!await c(t))throw new Error(`Shader file not found: ${e}`);const n=await l(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:s,fragment:r}=this.parseEsShader(n);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return Bt.createShader(s,r)}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 e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const n=await l(t);return JSON.parse(n)}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 e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):l(t)}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 e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):a(t)}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 Jt=fe(null,"Assets");class Kt{build(e){const t=e.wasmModule;t?e.insertResource(Jt,new qt(t)):console.warn("AssetPlugin: No WASM module available")}}const Qt=new Kt;function Zt(e,t){const n=e.getResource(Jt);n&&n.registerEmbeddedAssets(t)}let en=null,tn=0,nn=0,sn=0;const rn=new Float32Array(256);function on(e){en=e,tn=en._malloc(64),nn=en._malloc(64),sn=en._malloc(1024)}function an(){en&&(tn&&(en._free(tn),tn=0),nn&&(en._free(nn),nn=0),sn&&(en._free(sn),sn=0)),en=null}function ln(){if(!en)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return en}const cn={r:1,g:1,b:1,a:1},un={begin(e){const t=ln();t.HEAPF32.set(e,tn/4),t.draw_begin(tn)},end(){ln().draw_end()},line(e,t,n,s=1){ln().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){ln().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){ln().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){ln().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){ln().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=cn){ln().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=cn){ln().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){ln().draw_setLayer(e)},setDepth(e){ln().draw_setDepth(e)},getDrawCallCount:()=>en?en.draw_getDrawCallCount():0,getPrimitiveCount:()=>en?en.draw_getPrimitiveCount():0,setBlendMode(e){ln().draw_setBlendMode(e)},setDepthTest(e){ln().draw_setDepthTest(e)},drawMesh(e,t,n){const s=ln();s.HEAPF32.set(n,nn/4),s.draw_mesh(e,t,nn)},drawMeshWithMaterial(e,t,n){const s=ln(),r=Bt.get(t);if(!r)return;if(un.setBlendMode(r.blendMode),un.setDepthTest(r.depthTest),0===r.uniforms.size)return void un.drawMesh(e,r.shader,n);s.HEAPF32.set(n,nn/4);let o=0,i=0;for(const[e,t]of r.uniforms){const n=dn(e);if(!(n<0)){if(Ct(t))rn[o++]=10,rn[o++]=n,rn[o++]=t.slot??i++,rn[o++]=t.textureId;else if("number"==typeof t)rn[o++]=1,rn[o++]=n,rn[o++]=t;else if(Array.isArray(t)){rn[o++]=t.length,rn[o++]=n;for(let e=0;e<t.length;e++)rn[o++]=t[e]}else"w"in t?(rn[o++]=4,rn[o++]=n,rn[o++]=t.x,rn[o++]=t.y,rn[o++]=t.z,rn[o++]=t.w):"z"in t?(rn[o++]=3,rn[o++]=n,rn[o++]=t.x,rn[o++]=t.y,rn[o++]=t.z):(rn[o++]=2,rn[o++]=n,rn[o++]=t.x,rn[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(rn.subarray(0,o),sn/4),s.draw_meshWithUniforms(e,r.shader,nn,sn,o)):s.draw_mesh(e,r.shader,nn)}},hn={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function dn(e){return hn[e]??-1}var fn;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(fn||(fn={}));let pn=null,mn=0,gn=0,yn=0;function _n(e){pn=e,mn=pn._malloc(262144),gn=pn._malloc(65536),yn=pn._malloc(256)}function wn(){pn&&(mn&&pn._free(mn),gn&&pn._free(gn),yn&&pn._free(yn),mn=0,gn=0,yn=0),pn=null}function xn(){if(!pn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return pn}const bn={create(e){const t=xn(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,mn/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,yn,r).set(o),t.geometry_init(n,mn,s,yn,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,gn,s).set(e.indices),t.geometry_setIndices16(n,gn,s)}else{new Uint32Array(t.HEAPU8.buffer,gn,s).set(e.indices),t.geometry_setIndices32(n,gn,s)}}return n},updateVertices(e,t,n=0){const s=xn(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,mn/4),s.geometry_updateVertices(e,mn,r,n)},release(e){e>0&&xn().geometry_release(e)},isValid:e=>!(!pn||e<=0)&&pn.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return bn.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:fn.Float2},{name:"a_texCoord",type:fn.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;n.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return bn.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:fn.Float2},{name:"a_texCoord",type:fn.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-n);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return bn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:fn.Float2},{name:"a_texCoord",type:fn.Float2}],indices:new Uint16Array(i)})}};let vn=null;function Sn(e){vn=e}function Pn(){vn&&En.isInitialized()&&En.shutdown(),vn=null}function Cn(){if(!vn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return vn}const En={init:(e,t)=>Cn().postprocess_init(e,t),shutdown(){Cn().postprocess_shutdown()},resize(e,t){Cn().postprocess_resize(e,t)},addPass:(e,t)=>Cn().postprocess_addPass(e,t),removePass(e){Cn().postprocess_removePass(e)},setEnabled(e,t){Cn().postprocess_setPassEnabled(e,t)},isEnabled:e=>Cn().postprocess_isPassEnabled(e),setUniform(e,t,n){Cn().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Cn().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Cn().postprocess_begin()},end(){Cn().postprocess_end()},getPassCount:()=>Cn().postprocess_getPassCount(),isInitialized:()=>!!vn&&vn.postprocess_isInitialized(),setBypass(e){Cn().postprocess_setBypass(e)},isBypassed:()=>!vn||vn.postprocess_isBypassed(),createBlur:()=>Bt.createShader(Tn,"#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:()=>Bt.createShader(Tn,"#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:()=>Bt.createShader(Tn,"#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:()=>Bt.createShader(Tn,"#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")},Tn="#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 Mn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Mn||(Mn={}));let An=null,Rn=0;function Fn(e){An=e,Rn=An._malloc(64)}function Un(){An&&Rn&&(An._free(Rn),Rn=0),An=null}const Bn={init(e,t){An?.renderer_init(e,t)},resize(e,t){An?.renderer_resize(e,t)},begin(e,t){An&&Rn&&(An.HEAPF32.set(e,Rn/4),An.renderer_begin(Rn,t??0))},flush(){An?.renderer_flush()},end(){An?.renderer_end()},submitSprites(e){An&&An.renderer_submitSprites(e._cpp)},submitBitmapText(e){An&&An.renderer_submitBitmapText(e._cpp)},submitSpine(e){An&&An.renderer_submitSpine?.(e._cpp)},setStage(e){An?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>An?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){An?.renderer_releaseTarget(e)},getTargetTexture:e=>An?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>An?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){An?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){An?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){An?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){An?.renderer_clearBuffers(e)},getStats:()=>An?{drawCalls:An.renderer_getDrawCalls(),triangles:An.renderer_getTriangles(),sprites:An.renderer_getSprites(),text:An.renderer_getText(),spine:An.renderer_getSpine?.()??0,meshes:An.renderer_getMeshes(),culled:An.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let In=null;function kn(e){In=e}function Wn(){In=null}const zn={enable(){In?.gl_enableErrorCheck(!0)},disable(){In?.gl_enableErrorCheck(!1)},check:e=>In?.gl_checkErrors(e)??0,diagnose(){In?.renderer_diagnose()}},$n=new Map;function Dn(e,t){$n.set(e,t)}function Ln(e){$n.delete(e)}function Hn(){$n.clear()}class On{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}setSpineRenderer(e){this.spineRenderer_=e}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_||(Bn.resize(s,r),En.isInitialized()&&En.getPassCount()>0&&En.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),Bn.setViewport(0,0,s,r),Bn.clearBuffers(3),Bn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),Bn.submitSprites(t),Bn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Bn.submitSpine(t),Bn.flush(),this.executeDrawCallbacks(n,o),Bn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;Bn.setViewport(s.x,s.y,s.w,s.h),Bn.setScissor(s.x,s.y,s.w,s.h,!0),Bn.clearBuffers(r),Bn.setScissor(0,0,0,0,!1),Bn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Bn.submitSprites(t),Bn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Bn.submitSpine(t),Bn.flush(),this.executeDrawCallbacks(n,o),Bn.end()}executeDrawCallbacks(e,t){const n=$n;if(n.size>0){un.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)}un.end();for(const e of s)Ln(e)}}}class jn{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=d(),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 jn}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_=d(),this.mainLoop())}quit(){this.running_=!1,Wn(),Un(),Pn(),wn(),Ft(),an()}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 Nn(e,t){const n=jn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),on(e),Rt(e),_n(e),Sn(e),Fn(e),kn(e);const r=new On;n.pipeline_=r;let o=d();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r){const o=Gn(e,s,t,r),i=n.getResource(ut);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(ut,{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;Bn.setClearColor(e.x,e.y,e.z,e.w)}const c=(d()-o)/1e3;Bn.resize(t,n),En.isInitialized()&&En.getPassCount()>0&&!En.isBypassed()&&En.resize(t,n);const u=Gn(e,s,t,n);if(a(t,n),0===u.length)r.render({registry:{_cpp:s},viewProjection:Vn,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})}Bn.setViewport(0,0,t,n)}}};return n.addSystemToSchedule(Ee.First,l),n.addSystemToSchedule(Ee.Last,c),n.addPlugin(Qt),n.addPlugin(ze),n.addPlugin(Ye),n.addPlugin(st),n.addPlugin(_t),n.addPlugin(ft),n.addPlugin(St),n}function Xn(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 Vn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Yn(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 Gn(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,h=0,d=0;if(1===r.projectionType){if(d=r.orthoSize,o){d=Yn(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}h=d*c,u=Jn(-h,h,-d,d,-r.farPlane,r.farPlane)}else u=Qn(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=es(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:ts(u,f),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:h,halfH:d,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const qn=new Float32Array(16);function Jn(e,t,n,s,r,o){const i=qn;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 Kn=new Float32Array(16);function Qn(e,t,n,s){const r=Kn;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 Zn=new Float32Array(16);function es(e,t,n){const s=Zn;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 ts(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 ns(e,t,n){const{entities:s,rootId:r}=await ss(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}))},i=await Nt(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}async function ss(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 ss(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};rs(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 rs(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))}}async function os(e,t){if(t)return t();return(0,(await import(e)).default)()}const is=fe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),as=fe(null,"PhysicsAPI");function ls(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function cs(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class us{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(is,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=os(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,ee]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,$),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=ls(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),hs(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=ls(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 h=a,d=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=ls(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),u=Math.sin(-s);h=(r*i-o*u)/(0!==n.scale.x?n.scale.x:1),d=(r*u+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}u.position.x=h,u.position.y=d;const p=cs(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(is,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.__physicsModule=s,e.insertResource(as,ds._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=s}}function hs(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,L)){const e=s.get(n,L);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,H)){const e=s.get(n,H);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 ds{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(ds.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 fs(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 ps(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 ms(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,h=a+a,d=l+l,f=c+c,p=a*h,m=a*d,g=a*f,y=l*d,_=l*f,w=c*f,x=u*h,b=u*d,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 gs(e,t,n,s,r,o,i){const a=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]=fs(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,a);let l={},c=null;if(r&&(c=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),l=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 h,d;if(u){const e=r.readBinary(i);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=r.readText(i),n=(new TextEncoder).encode(e);d=n.length,h=t._malloc(d+1),t.HEAPU8.set(n,h),t.HEAPU8[h+d]=0}const f=n.loadSkeleton(h,d,s,s.length,u);if(t._free(h),f<0)continue;o[i]=f;const p=ps(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=fs(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,c,n,s)),o){new us("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const u=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;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=fs(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=Bt.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=Bt.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),d=jt(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,a,d),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,u,d),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,d),r&&c){const s=function(e,t,n,s){const r={};for(const o of t.entities)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}(c,n,l,d);!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,h=a?.timeScale??1;u&&s.update(i,l*h);let d=0;if(c.has(o,ee)){const e=ms(c.get(o,ee),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,h,f);const p=n.HEAPU32[h>>2],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,d),t._free(_),t._free(w),n._free(c),n._free(u),n._free(h),n._free(f)}d&&t._free(d)}})}(e,t,r,c,s)}}class ys{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 _s{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_)try{const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new ys(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.__spineInitPromise;if(r){s=(await r).controller.raw}await gs(this.app_,this.app_.wasmModule,t,n,s),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}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 ws={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Bn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Bn.getTargetTexture(n),width:e.width,height:e.height}},release(e){Bn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Bn.releaseRenderTarget(e._handle),ws.create({width:t,height:n,depth:!0})),begin(e,t){Bn.begin(t,e._handle)},end(){Bn.end()},getDepthTexture:e=>Bn.getTargetDepthTexture(e._handle)};let xs=!1;function bs(e){xs=e}function vs(){return xs}function Ss(){return!xs}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{jn as App,Kt as AssetPlugin,qt as AssetServer,Jt as Assets,Gt as AsyncCache,ae as BitmapText,Pt as BlendMode,O as BodyType,D as BoxCollider,at as Button,it as ButtonState,ne as Camera,se as Canvas,H as CapsuleCollider,ie as Children,L as CircleCollider,Se as Commands,Ce as CommandsInstance,fn as DataType,un as Draw,Pe as EntityCommands,zn as GLDebug,bn as Geometry,A as INVALID_ENTITY,F as INVALID_FONT,R as INVALID_TEXTURE,ke as Input,We as InputPlugin,Ie as InputState,rt as Interactable,Z as LocalTransform,Bt as Material,Ot as MaterialLoader,we as Mut,ce as Name,oe as Parent,ds as Physics,is as PhysicsEvents,us as PhysicsPlugin,En as PostProcess,_s as PreviewPlugin,be as Query,ve as QueryInstance,On as RenderPipeline,Mn as RenderStage,ws as RenderTexture,Bn as Renderer,pe as Res,me as ResMut,$ as RigidBody,Ee as Schedule,pt as ScreenSpace,Ht as ShaderSources,le as SpineAnimation,te as Sprite,Be as SystemRunner,je as Text,Le as TextAlign,wt as TextInput,xt as TextInputPlugin,Oe as TextOverflow,Ve as TextPlugin,Ne as TextRenderer,He as TextVerticalAlign,_e as Time,ut as UICameraInfo,lt as UIEventQueue,ct as UIEvents,ot as UIInteraction,dt as UIInteractionPlugin,yt as UILayoutPlugin,Ge as UIMask,nt as UIMaskPlugin,Xe as UIRect,re as Velocity,ys as WebAssetProvider,De as World,ee as WorldTransform,Fe as addStartupSystem,Re as addSystem,Ue as addSystemToSchedule,Qt as assetPlugin,Hn as clearDrawCallbacks,q as clearUserComponents,k as color,mt as computeUIRectLayout,tt as createMaskProcessor,Nn as createWebApp,V as defineComponent,fe as defineResource,Me as defineSystem,Y as defineTag,Yt as findEntityByName,Xn as flushPendingSystems,he as getComponentDefaults,t as getPlatform,s as getPlatformType,G as getUserComponent,on as initDrawAPI,kn as initGLDebugAPI,_n as initGeometryAPI,Rt as initMaterialAPI,Sn as initPostProcessAPI,Fn as initRendererAPI,ze as inputPlugin,ns as instantiatePrefab,qe as intersectRects,Ke as invertMatrix4,Q as isBuiltinComponent,vs as isEditor,n as isPlatformInitialized,Ss as isRuntime,Ct as isTextureRef,r as isWeChat,o as isWeb,Xt as loadComponent,os as loadPhysicsModule,gs as loadRuntimeScene,jt as loadSceneData,Nt as loadSceneWithAssets,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Ze as pointInWorldRect,W as quat,Dn as registerDrawCallback,Zt as registerEmbeddedAssets,Lt as registerMaterialCallback,Qe as screenToWorld,bs as setEditorMode,an as shutdownDrawAPI,Wn as shutdownGLDebugAPI,wn as shutdownGeometryAPI,Ft as shutdownMaterialAPI,Pn as shutdownPostProcessAPI,Un as shutdownRendererAPI,St as textInputPlugin,Ye as textPlugin,ft as uiInteractionPlugin,_t as uiLayoutPlugin,st as uiMaskPlugin,Ln as unregisterDrawCallback,Vt as updateCameraAspectRatio,U as vec2,B as vec3,I as vec4,Je 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 ec96737c4..fe345c3c8 100644
--- a/desktop/public/sdk/esm/esengine.d.ts
+++ b/desktop/public/sdk/esm/esengine.d.ts
@@ -80,10 +80,10 @@ interface CapsuleColliderData {
restitution: number;
isSensor: boolean;
}
-declare const RigidBody: BuiltinComponentDef<RigidBodyData>;
-declare const BoxCollider: BuiltinComponentDef<BoxColliderData>;
-declare const CircleCollider: BuiltinComponentDef<CircleColliderData>;
-declare const CapsuleCollider: BuiltinComponentDef<CapsuleColliderData>;
+declare const RigidBody$1: BuiltinComponentDef<RigidBodyData>;
+declare const BoxCollider$1: BuiltinComponentDef<BoxColliderData>;
+declare const CircleCollider$1: BuiltinComponentDef<CircleColliderData>;
+declare const CapsuleCollider$1: BuiltinComponentDef<CapsuleColliderData>;
declare const BodyType: {
readonly Static: 0;
readonly Kinematic: 1;
@@ -197,16 +197,16 @@ interface BitmapTextData {
interface NameData {
value: string;
}
-declare const LocalTransform: BuiltinComponentDef<LocalTransformData>;
-declare const WorldTransform: BuiltinComponentDef<WorldTransformData>;
-declare const Sprite: BuiltinComponentDef<SpriteData>;
-declare const Camera: BuiltinComponentDef<CameraData>;
-declare const Canvas: BuiltinComponentDef<CanvasData>;
-declare const Velocity: BuiltinComponentDef<VelocityData>;
-declare const Parent: BuiltinComponentDef<ParentData>;
-declare const Children: BuiltinComponentDef<ChildrenData>;
-declare const BitmapText: BuiltinComponentDef<BitmapTextData>;
-declare const SpineAnimation: BuiltinComponentDef<SpineAnimationData>;
+declare const LocalTransform$1: BuiltinComponentDef<LocalTransformData>;
+declare const WorldTransform$1: BuiltinComponentDef<WorldTransformData>;
+declare const Sprite$1: BuiltinComponentDef<SpriteData>;
+declare const Camera$1: BuiltinComponentDef<CameraData>;
+declare const Canvas$1: BuiltinComponentDef<CanvasData>;
+declare const Velocity$1: BuiltinComponentDef<VelocityData>;
+declare const Parent$1: BuiltinComponentDef<ParentData>;
+declare const Children$1: BuiltinComponentDef<ChildrenData>;
+declare const BitmapText$1: BuiltinComponentDef<BitmapTextData>;
+declare const SpineAnimation$1: BuiltinComponentDef<SpineAnimationData>;
declare const Name: ComponentDef<NameData>;
type ComponentData<C> = C extends BuiltinComponentDef<infer T> ? T : C extends ComponentDef<infer T> ? T : never;
@@ -257,73 +257,198 @@ interface TimeData {
declare const Time: ResourceDef<TimeData>;
/**
- * @file wasm.ts
- * @brief WASM module type definitions
+ * @file wasm.generated.ts
+ * @brief ESEngine WASM Bindings TypeScript Definitions
+ * @details Generated by EHT - DO NOT EDIT
*/
-interface CppRegistry {
+interface UVec2 {
+ x: number;
+ y: number;
+}
+interface BoxCollider {
+ halfExtents: Vec2;
+ offset: Vec2;
+ density: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+}
+interface CircleCollider {
+ radius: number;
+ offset: Vec2;
+ density: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+}
+interface CapsuleCollider {
+ radius: number;
+ halfHeight: number;
+ offset: Vec2;
+ density: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+}
+interface LocalTransform {
+ position: Vec3;
+ rotation: Quat;
+ scale: Vec3;
+}
+interface WorldTransform {
+ position: Vec3;
+ rotation: Quat;
+ scale: Vec3;
+}
+interface Velocity {
+ linear: Vec3;
+ angular: Vec3;
+}
+interface SpineAnimation {
+ skeletonPath: string;
+ atlasPath: string;
+ skin: string;
+ animation: string;
+ timeScale: number;
+ loop: boolean;
+ playing: boolean;
+ flipX: boolean;
+ flipY: boolean;
+ color: Vec4;
+ layer: number;
+ skeletonScale: number;
+ material: number;
+}
+interface RigidBody {
+ bodyType: number;
+ gravityScale: number;
+ linearDamping: number;
+ angularDamping: number;
+ fixedRotation: boolean;
+ bullet: boolean;
+ enabled: boolean;
+}
+interface BitmapText {
+ text: string;
+ color: Vec4;
+ fontSize: number;
+ align: number;
+ spacing: number;
+ layer: number;
+ font: number;
+}
+interface Sprite {
+ texture: number;
+ color: Vec4;
+ size: Vec2;
+ uvOffset: Vec2;
+ uvScale: Vec2;
+ layer: number;
+ flipX: boolean;
+ flipY: boolean;
+ material: number;
+}
+interface Parent {
+ entity: number;
+}
+interface Children {
+}
+interface Canvas {
+ designResolution: UVec2;
+ pixelsPerUnit: number;
+ scaleMode: number;
+ matchWidthOrHeight: number;
+ backgroundColor: Vec4;
+}
+interface Camera {
+ projectionType: number;
+ fov: number;
+ orthoSize: number;
+ nearPlane: number;
+ farPlane: number;
+ aspectRatio: number;
+ isActive: boolean;
+ priority: number;
+ viewportX: number;
+ viewportY: number;
+ viewportW: number;
+ viewportH: number;
+ clearFlags: number;
+}
+interface Registry {
create(): Entity;
destroy(entity: Entity): void;
valid(entity: Entity): boolean;
- delete(): void;
- addLocalTransform(entity: Entity, data: unknown): void;
- getLocalTransform(entity: Entity): unknown;
+ entityCount(): number;
+ hasBoxCollider(entity: Entity): boolean;
+ getBoxCollider(entity: Entity): BoxCollider;
+ addBoxCollider(entity: Entity, component: BoxCollider): void;
+ removeBoxCollider(entity: Entity): void;
+ hasCircleCollider(entity: Entity): boolean;
+ getCircleCollider(entity: Entity): CircleCollider;
+ addCircleCollider(entity: Entity, component: CircleCollider): void;
+ removeCircleCollider(entity: Entity): void;
+ hasCapsuleCollider(entity: Entity): boolean;
+ getCapsuleCollider(entity: Entity): CapsuleCollider;
+ addCapsuleCollider(entity: Entity, component: CapsuleCollider): void;
+ removeCapsuleCollider(entity: Entity): void;
hasLocalTransform(entity: Entity): boolean;
+ getLocalTransform(entity: Entity): LocalTransform;
+ addLocalTransform(entity: Entity, component: LocalTransform): void;
removeLocalTransform(entity: Entity): void;
- addWorldTransform(entity: Entity, data: unknown): void;
- getWorldTransform(entity: Entity): unknown;
hasWorldTransform(entity: Entity): boolean;
+ getWorldTransform(entity: Entity): WorldTransform;
+ addWorldTransform(entity: Entity, component: WorldTransform): void;
removeWorldTransform(entity: Entity): void;
- addSprite(entity: Entity, data: unknown): void;
- getSprite(entity: Entity): unknown;
- hasSprite(entity: Entity): boolean;
- removeSprite(entity: Entity): void;
- addCamera(entity: Entity, data: unknown): void;
- getCamera(entity: Entity): unknown;
- hasCamera(entity: Entity): boolean;
- removeCamera(entity: Entity): void;
- addCanvas(entity: Entity, data: unknown): void;
- getCanvas(entity: Entity): unknown;
- hasCanvas(entity: Entity): boolean;
- removeCanvas(entity: Entity): void;
- addVelocity(entity: Entity, data: unknown): void;
- getVelocity(entity: Entity): unknown;
hasVelocity(entity: Entity): boolean;
+ getVelocity(entity: Entity): Velocity;
+ addVelocity(entity: Entity, component: Velocity): void;
removeVelocity(entity: Entity): void;
- addParent(entity: Entity, data: unknown): void;
- getParent(entity: Entity): unknown;
- hasParent(entity: Entity): boolean;
- removeParent(entity: Entity): void;
- addChildren(entity: Entity, data: unknown): void;
- getChildren(entity: Entity): unknown;
- hasChildren(entity: Entity): boolean;
- removeChildren(entity: Entity): void;
- addSpineAnimation(entity: Entity, data: unknown): void;
- getSpineAnimation(entity: Entity): unknown;
hasSpineAnimation(entity: Entity): boolean;
+ getSpineAnimation(entity: Entity): SpineAnimation;
+ addSpineAnimation(entity: Entity, component: SpineAnimation): void;
removeSpineAnimation(entity: Entity): void;
- addRigidBody?(entity: Entity, data: unknown): void;
- getRigidBody?(entity: Entity): unknown;
- hasRigidBody?(entity: Entity): boolean;
- removeRigidBody?(entity: Entity): void;
- addBoxCollider?(entity: Entity, data: unknown): void;
- getBoxCollider?(entity: Entity): unknown;
- hasBoxCollider?(entity: Entity): boolean;
- removeBoxCollider?(entity: Entity): void;
- addCircleCollider?(entity: Entity, data: unknown): void;
- getCircleCollider?(entity: Entity): unknown;
- hasCircleCollider?(entity: Entity): boolean;
- removeCircleCollider?(entity: Entity): void;
- addCapsuleCollider?(entity: Entity, data: unknown): void;
- getCapsuleCollider?(entity: Entity): unknown;
- hasCapsuleCollider?(entity: Entity): boolean;
- removeCapsuleCollider?(entity: Entity): void;
- addBitmapText(entity: Entity, data: unknown): void;
- getBitmapText(entity: Entity): unknown;
+ hasRigidBody(entity: Entity): boolean;
+ getRigidBody(entity: Entity): RigidBody;
+ addRigidBody(entity: Entity, component: RigidBody): void;
+ removeRigidBody(entity: Entity): void;
hasBitmapText(entity: Entity): boolean;
+ getBitmapText(entity: Entity): BitmapText;
+ addBitmapText(entity: Entity, component: BitmapText): void;
removeBitmapText(entity: Entity): void;
+ hasSprite(entity: Entity): boolean;
+ getSprite(entity: Entity): Sprite;
+ addSprite(entity: Entity, component: Sprite): void;
+ removeSprite(entity: Entity): void;
+ hasParent(entity: Entity): boolean;
+ getParent(entity: Entity): Parent;
+ addParent(entity: Entity, component: Parent): void;
+ removeParent(entity: Entity): void;
+ hasChildren(entity: Entity): boolean;
+ getChildren(entity: Entity): Children;
+ addChildren(entity: Entity, component: Children): void;
+ removeChildren(entity: Entity): void;
+ hasCanvas(entity: Entity): boolean;
+ getCanvas(entity: Entity): Canvas;
+ addCanvas(entity: Entity, component: Canvas): void;
+ removeCanvas(entity: Entity): void;
+ hasCamera(entity: Entity): boolean;
+ getCamera(entity: Entity): Camera;
+ addCamera(entity: Entity, component: Camera): void;
+ removeCamera(entity: Entity): void;
setParent(child: Entity, parent: Entity): void;
- [key: string]: any;
+}
+
+/**
+ * @file wasm.ts
+ * @brief WASM module type definitions
+ */
+
+interface CppRegistry extends Registry {
+ delete(): void;
+ removeParent(entity: Entity): void;
+ [key: string]: Function | undefined;
}
interface CppResourceManager {
createTexture(width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean): number;
@@ -482,8 +607,8 @@ declare class World {
getAllEntities(): Entity[];
setParent(child: Entity, parent: Entity): void;
removeParent(entity: Entity): void;
- insert(entity: Entity, component: AnyComponentDef, data?: unknown): unknown;
- get(entity: Entity, component: AnyComponentDef): unknown;
+ insert<C extends AnyComponentDef>(entity: Entity, component: C, data?: Partial<ComponentData<C>>): ComponentData<C>;
+ get<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C>;
has(entity: Entity, component: AnyComponentDef): boolean;
remove(entity: Entity, component: AnyComponentDef): void;
private insertBuiltin;
@@ -550,7 +675,7 @@ interface CommandsDescriptor {
declare function Commands(): CommandsDescriptor;
interface SpawnComponentEntry {
component: AnyComponentDef;
- data: unknown;
+ data: any;
}
declare class EntityCommands {
private readonly commands_;
@@ -607,7 +732,7 @@ type InferParams<P extends readonly SystemParam[]> = {
interface SystemDef {
readonly _id: symbol;
readonly _params: readonly SystemParam[];
- readonly _fn: (...args: unknown[]) => void;
+ readonly _fn: (...args: never[]) => void;
readonly _name: string;
}
declare function defineSystem<P extends readonly SystemParam[]>(params: [...P], fn: (...args: InferParams<P>) => void, options?: {
@@ -696,6 +821,7 @@ declare class App {
addStartupSystem(system: SystemDef): this;
connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this;
get wasmModule(): ESEngineModule | null;
+ get pipeline(): RenderPipeline | null;
setSpineRenderer(fn: SpineRendererFn | null): void;
get world(): World;
setFixedTimestep(timestep: number): this;
@@ -1230,6 +1356,50 @@ declare function loadComponent(world: World, entity: Entity, compData: SceneComp
declare function updateCameraAspectRatio(world: World, aspectRatio: number): void;
declare function findEntityByName(world: World, name: string): Entity | null;
+interface PrefabData {
+ version: string;
+ name: string;
+ rootEntityId: number;
+ entities: PrefabEntityData[];
+}
+interface PrefabEntityData {
+ prefabEntityId: number;
+ name: string;
+ parent: number | null;
+ children: number[];
+ components: {
+ type: string;
+ data: Record<string, unknown>;
+ }[];
+ visible: boolean;
+ nestedPrefab?: {
+ prefabPath: string;
+ overrides: PrefabOverride[];
+ };
+}
+interface PrefabOverride {
+ prefabEntityId: number;
+ type: 'property' | 'component_added' | 'component_removed' | 'name' | 'visibility';
+ componentType?: string;
+ propertyName?: string;
+ value?: unknown;
+ componentData?: {
+ type: string;
+ data: Record<string, unknown>;
+ };
+}
+interface InstantiatePrefabOptions {
+ assetServer?: AssetServer;
+ assetBaseUrl?: string;
+ parent?: Entity;
+ overrides?: PrefabOverride[];
+}
+interface InstantiatePrefabResult {
+ root: Entity;
+ entities: Map<number, Entity>;
+}
+declare function instantiatePrefab(world: World, prefab: PrefabData, options?: InstantiatePrefabOptions): Promise<InstantiatePrefabResult>;
+
/**
* @file AssetServer.ts
* @brief Asset loading and caching system
@@ -1305,6 +1475,7 @@ declare class AssetServer {
private canvas_;
private ctx_;
private fontCache_;
+ private prefabCache_;
private embedded_;
private addressableManifest_;
private addressIndex_;
@@ -1336,6 +1507,7 @@ declare class AssetServer {
releaseFont(fontPath: string): void;
private loadBmfontAsset;
private loadFntFile;
+ loadPrefab(path: string, baseUrl?: string): Promise<PrefabData>;
loadMaterial(path: string, baseUrl?: string): Promise<LoadedMaterial>;
getMaterial(path: string, baseUrl?: string): LoadedMaterial | undefined;
hasMaterial(path: string, baseUrl?: string): boolean;
@@ -2122,5 +2294,5 @@ declare const GLDebug: {
diagnose(): void;
};
-export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BitmapText, BlendMode, BodyType, BoxCollider, Button, ButtonState, Camera, Canvas, CapsuleCollider, Children, CircleCollider, Commands, CommandsInstance, DataType, Draw, EntityCommands, GLDebug, Geometry, INVALID_ENTITY, INVALID_FONT, INVALID_TEXTURE, Input, InputPlugin, InputState, Interactable, LocalTransform, Material, MaterialLoader, Mut, Name, Parent, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PreviewPlugin, Query, QueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, RigidBody, Schedule, ScreenSpace, ShaderSources, SpineAnimation, Sprite, SystemRunner, Text, TextAlign, TextInput, TextInputPlugin, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UICameraInfo, UIEventQueue, UIEvents, UIInteraction, UIInteractionPlugin, UILayoutPlugin, UIMask, UIMaskPlugin, UIRect, Velocity, WebAssetProvider, World, WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, assetPlugin, clearDrawCallbacks, clearUserComponents, color, computeUIRectLayout, createMaskProcessor, createWebApp, defineComponent, defineResource, defineSystem, defineTag, findEntityByName, flushPendingSystems, getComponentDefaults, getPlatform, getPlatformType, getUserComponent, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, inputPlugin, intersectRects, invertMatrix4, isBuiltinComponent, isEditor, isPlatformInitialized, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInWorldRect, quat, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, screenToWorld, setEditorMode, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textInputPlugin, textPlugin, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, worldRectToScreen };
-export type { AddressableManifest, AddressableManifestAsset, AddressableManifestGroup, AnyComponentDef, AssetBundle, AssetManifest, AssetsData, BitmapTextData, BoxColliderData, BuiltinComponentDef, ButtonData, ButtonTransition, CameraData, CameraRenderParams, CanvasData, CapsuleColliderData, ChildrenData, CircleColliderData, CollisionEnterEvent, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DrawAPI, DrawCallback, ESEngineModule, Entity, FileLoadOptions, FontHandle, GeometryHandle, GeometryOptions, InferParam, InferParams, InteractableData, LayoutRect, LayoutResult, LoadedMaterial, LocalTransformData, MaskProcessorFn, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, NameData, ParentData, PhysicsEventsData, PhysicsModuleFactory, PhysicsPluginConfig, PhysicsWasmModule, PlatformAdapter, PlatformRequestOptions, PlatformResponse, PlatformType, Plugin, Quat, QueryDescriptor, QueryResult, RenderParams, RenderStats, RenderTargetHandle, RenderTextureHandle, RenderTextureOptions, ResDescriptor, ResMutDescriptor, ResourceDef, RigidBodyData, RuntimeAssetProvider, SceneComponentData, SceneData, SceneEntityData, SceneLoadOptions, ScreenRect, SensorEvent, ShaderHandle, ShaderLoader, SliceBorder, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteData, SystemDef, SystemParam, TextData, TextInputData, TextRenderResult, TextureHandle, TextureInfo, TextureRef, TimeData, UICameraData, UIEvent, UIEventType, UIInteractionData, UIMaskData, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WorldTransformData };
+export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BitmapText$1 as BitmapText, BlendMode, BodyType, BoxCollider$1 as BoxCollider, Button, ButtonState, Camera$1 as Camera, Canvas$1 as Canvas, CapsuleCollider$1 as CapsuleCollider, Children$1 as Children, CircleCollider$1 as CircleCollider, Commands, CommandsInstance, DataType, Draw, EntityCommands, GLDebug, Geometry, INVALID_ENTITY, INVALID_FONT, INVALID_TEXTURE, Input, InputPlugin, InputState, Interactable, LocalTransform$1 as LocalTransform, Material, MaterialLoader, Mut, Name, Parent$1 as Parent, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PreviewPlugin, Query, QueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, RigidBody$1 as RigidBody, Schedule, ScreenSpace, ShaderSources, SpineAnimation$1 as SpineAnimation, Sprite$1 as Sprite, SystemRunner, Text, TextAlign, TextInput, TextInputPlugin, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UICameraInfo, UIEventQueue, UIEvents, UIInteraction, UIInteractionPlugin, UILayoutPlugin, UIMask, UIMaskPlugin, UIRect, Velocity$1 as Velocity, WebAssetProvider, World, WorldTransform$1 as WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, assetPlugin, clearDrawCallbacks, clearUserComponents, color, computeUIRectLayout, createMaskProcessor, createWebApp, defineComponent, defineResource, defineSystem, defineTag, findEntityByName, flushPendingSystems, getComponentDefaults, getPlatform, getPlatformType, getUserComponent, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, inputPlugin, instantiatePrefab, intersectRects, invertMatrix4, isBuiltinComponent, isEditor, isPlatformInitialized, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInWorldRect, quat, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, screenToWorld, setEditorMode, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textInputPlugin, textPlugin, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, worldRectToScreen };
+export type { AddressableManifest, AddressableManifestAsset, AddressableManifestGroup, AnyComponentDef, AssetBundle, AssetManifest, AssetsData, BitmapTextData, BoxColliderData, BuiltinComponentDef, ButtonData, ButtonTransition, CameraData, CameraRenderParams, CanvasData, CapsuleColliderData, ChildrenData, CircleColliderData, CollisionEnterEvent, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DrawAPI, DrawCallback, ESEngineModule, Entity, FileLoadOptions, FontHandle, GeometryHandle, GeometryOptions, InferParam, InferParams, InstantiatePrefabOptions, InstantiatePrefabResult, InteractableData, LayoutRect, LayoutResult, LoadedMaterial, LocalTransformData, MaskProcessorFn, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, NameData, ParentData, PhysicsEventsData, PhysicsModuleFactory, PhysicsPluginConfig, PhysicsWasmModule, PlatformAdapter, PlatformRequestOptions, PlatformResponse, PlatformType, Plugin, PrefabData, PrefabEntityData, PrefabOverride, Quat, QueryDescriptor, QueryResult, RenderParams, RenderStats, RenderTargetHandle, RenderTextureHandle, RenderTextureOptions, ResDescriptor, ResMutDescriptor, ResourceDef, RigidBodyData, RuntimeAssetProvider, SceneComponentData, SceneData, SceneEntityData, SceneLoadOptions, ScreenRect, SensorEvent, ShaderHandle, ShaderLoader, SliceBorder, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteData, SystemDef, SystemParam, TextData, TextInputData, TextRenderResult, TextureHandle, TextureInfo, TextureRef, TimeData, UICameraData, UIEvent, UIEventType, UIInteractionData, UIMaskData, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WorldTransformData };
diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.js
index 9c8d4f342..e3f38c21b 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 h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.module}}createImage(){return new Image}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),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)},h=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",h),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",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=0,m=4294967295,_=4294967295,g=(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}),M=b("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 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 z(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function L(e){return!0===e._builtin}const $=z("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),D=z("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),H=z("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=z("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=z("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),j=z("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),N=z("Parent",{entity:0}),X=z("Children",{entities:[]}),V=z("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:_}),Y=z("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),G={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},q={LocalTransform:$,WorldTransform:D,Sprite:H,Camera:W,Canvas:O,Velocity:j,Parent:N,Children:X,BitmapText:V,SpineAnimation:Y,RigidBody:S,BoxCollider:P,CircleCollider:C,CapsuleCollider:M};function K(e){const t=q[e];if(t)return{...t._default};const n=B(e);return n?{...n._default}:null}let J=0;function Q(e,t){const n=++J;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&&"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=L(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 he;!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"}(he||(he={}));let de=0;function fe(e,t,n){const s=++de;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:he.Update,system:e})}function _e(e){pe().push({schedule:he.Startup,system:e})}function ge(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(he.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){if(null==e||"object"!=typeof e||Array.isArray(e))return e;const t=e;if("r"in t&&"g"in t&&"b"in t&&"a"in t&&!("x"in t))return{x:t.r,y:t.g,z:t.b,w:t.a};const n={};for(const e of Object.keys(t)){const s=t[e];n[e]=null==s||"object"!=typeof s||Array.isArray(s)?s:Se(s)}return n}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 L(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return L(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return L(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){L(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const s={...t._default,...n};if(this.cppRegistry_){const n=`add${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e,Se(s))}return s}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(!L(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,Me,Ee;!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"}(Me||(Me={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Ee||(Ee={}));const Te=F("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Ce.Left,verticalAlign:Me.Top,wordWrap:!0,overflow:Ee.Visible,lineHeight:1.2,dirty:!0});class Ae{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(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),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=r?Math.ceil(o):h+2*u,p=r?Math.ceil(i):d+2*u;if(r&&e.overflow===Ee.Ellipsis&&d>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const m=Math.round(255*e.color.r),_=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${_}, ${g}, ${y})`,r&&e.overflow===Ee.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 Me.Top:x=u;break;case Me.Middle:x=(p-w)/2;break;case Me.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===Ee.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 M=P.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{textureHandle:M,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}});class Fe{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;e.addSystemToSchedule(he.PreUpdate,fe([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Te));const e=s.getEntitiesWithComponents([Te]);for(const t of e){const e=s.get(t,Te);if(!e.dirty)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 r=s.has(t,Re)?s.get(t,Re):null,o=n.renderForEntity(t,e,r),i=s.get(t,H);i.texture=o.textureHandle,i.size.x=o.width,i.size.y=o.height,i.uvOffset.x=0,i.uvOffset.y=0,i.uvScale.x=1,i.uvScale.y=1,s.insert(t,H,i),e.dirty=!1}}))}}const Ue=new Fe,Be=F("UIMask",{enabled:!0});function Ie(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 ke(e,t,n,s,r,o,i,a,l,c,u){const h=e-n*r,d=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(h,f),[y,w]=m(d,p),x=Math.min(_,y),v=Math.max(_,y),b=Math.min(g,w),S=Math.max(g,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}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],h=e[8],d=e[9],f=e[10],p=e[11],m=e[12],_=e[13],g=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=h*_-d*m,M=h*g-f*m,E=h*y-p*m,T=d*g-f*_,A=d*y-p*_,R=f*y-p*g;let F=w*R-x*A+v*T+b*E-S*M+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]=(_*P-g*S+y*b)*F,n[3]=(f*S-d*P-p*b)*F,n[4]=(c*E-a*R-u*M)*F,n[5]=(s*R-o*E+i*M)*F,n[6]=(g*v-m*P-y*x)*F,n[7]=(h*P-f*v+p*x)*F,n[8]=(a*A-l*E+u*C)*F,n[9]=(r*E-s*A-i*C)*F,n[10]=(m*S-_*v+y*w)*F,n[11]=(d*v-h*S-p*w)*F,n[12]=(l*M-a*T-c*C)*F,n[13]=(s*T-r*M+o*C)*F,n[14]=(_*x-m*b-g*w)*F,n[15]=(h*b-d*x+f*w)*F),n}function Le(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:u/h}}function $e(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 De(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 ke(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function He(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Be]);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,Be).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,N);){const e=t.get(s,N);if(c.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function h(s,u){const d=e.getChildEntities(n,s);for(const n of d){let s=u;if(c.has(n)){const e=De(t,n,r,o,i,a,l);e&&(s=Ie(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of u){const n=De(t,e,r,o,i,a,l);n&&h(e,n)}}(e,t,n,l,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class We{build(e){if(!e.wasmModule)return;const t=e.pipeline_;t&&t.setMaskProcessor(He(e.wasmModule,e.world))}}const Oe=new We,je=F("Interactable",{enabled:!0}),Ne=F("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Xe;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Xe||(Xe={}));const Ve=F("Button",{state:Xe.Normal,transition:null});class Ye{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 Ge=Q(new Ye,"UIEvents"),qe=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"),Ke=new Float32Array(16);class Je{build(e){const t=e.world,n=new Ye;e.insertResource(Ge,n);let s=null,r=null;e.addSystemToSchedule(he.PreUpdate,fe([Z(xe),Z(qe)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([Ne]);for(const e of i){const n=t.get(e,Ne);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,Ke);const u=Le(l,c,Ke,o.vpX,o.vpY,o.vpW,o.vpH),h=t.getEntitiesWithComponents([je,Re,D]);let d=null,f=-1/0;for(const e of h){t.has(e,Ne)||t.insert(e,Ne);if(!t.get(e,je).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($e(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,d=e)}}if(s!==d){if(null!==s&&t.valid(s)&&t.has(s,Ne)){t.get(s,Ne).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,Ne).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,Ne);e.pressed=!0,e.justPressed=!0,r=d,n.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Ne)){const e=t.get(r,Ne);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(he.Update,fe([],()=>{const e=t.getEntitiesWithComponents([Ve]);for(const n of e){if(t.has(n,je)||t.insert(n,je,{enabled:!0}),!t.has(n,Ne))continue;const e=t.get(n,Ne),s=t.get(n,Ve),r=t.get(n,je),o=s.state;if(r.enabled?e.pressed?s.state=Xe.Pressed:e.hovered?s.state=Xe.Hovered:s.state=Xe.Normal:s.state=Xe.Disabled,o!==s.state&&s.transition&&t.has(n,H)){const e=t.get(n,H),r=s.transition;switch(s.state){case Xe.Normal:e.color={...r.normalColor};break;case Xe.Hovered:e.color={...r.hoveredColor};break;case Xe.Pressed:e.color={...r.pressedColor};break;case Xe.Disabled:e.color={...r.disabledColor}}t.insert(n,H,e)}}},{name:"ButtonSystem"}))}}const Qe=new Je,Ze=U("ScreenSpace");function et(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,h=o.bottom+t.y*a;let d,f,p,m;if(l===c&&u===h){const e=l+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;d=e-s,f=t-o,p=e+s,m=t+o}else d=l+n.x,f=u+n.y,p=c+s.x,m=h+s.y;return{centerX:.5*(d+p),centerY:.5*(f+m),width:p-d,height:m-f,rect:{left:d,bottom:f,right:p,top:m}}}function tt(e,t,n,s,r,o){if(!e.has(t,Re))return;const i=e.get(t,Re),a=et(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,$);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),!e.has(t,X))return;const c=e.get(t,X);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&tt(e,t,a.rect,a.centerX,a.centerY,!1)}class nt{build(e){const t=e.world;e.addSystemToSchedule(he.PreUpdate,fe([Z(qe)],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([Ze,Re,$]);for(const e of o)tt(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const st=new nt,rt=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 ot{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=h(512,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,u=0;const d=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,rt);if(t.readOnly)return;let s=d.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),d.value=s),s!==t.value){t.value=s;e.getResource(Ge).emit(i,"change")}t.cursorPos=d.selectionStart??s.length,t.dirty=!0,g()}function p(e){if(i===e)return;_();const t=n.get(e,rt);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,d.value=t.value,d.selectionStart=t.cursorPos,d.selectionEnd=t.cursorPos,d.focus(),g())}function _(){if(null!==i&&n.valid(i)&&n.has(i,rt)){const e=n.get(i,rt);e.focused=!1,e.dirty=!0}i=null,d.blur()}function g(){l=!0,c=0}function y(e,i,a,c){(r.width<a||r.height<c)&&(r.width=at(Math.max(r.width,a)),r.height=at(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 h=0===i.value.length,d=h?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=h?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=it(o,d,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(d,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=it(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 _=o.getImageData(0,0,a,c),g=new Uint8Array(_.data.buffer),y=t.getResourceManager(),w=t._malloc(g.length);t.HEAPU8.set(g,w);const x=s.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,c,w,g.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)}d.addEventListener("input",()=>{a||null===i||f()}),d.addEventListener("compositionstart",()=>{a=!0}),d.addEventListener("compositionend",()=>{a=!1,f()}),d.addEventListener("keydown",t=>{if(null===i)return;if("Escape"===t.key)return void _();const s=n.get(i,rt);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(Ge).emit(i,"submit"),void _()}}),d.addEventListener("blur",()=>{if(null!==i&&n.valid(i)&&n.has(i,rt)){const e=n.get(i,rt);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(he.PreUpdate,fe([Z(Ge)],e=>{const t=n.getEntitiesWithComponents([rt,je]);for(const e of t){if(!n.has(e,Ne))continue;if(n.get(e,Ne).justPressed)return void p(e)}if(null!==i){const e=n.getEntitiesWithComponents([je]);for(const t of e){if(n.has(t,rt))continue;if(!n.has(t,Ne))continue;if(n.get(t,Ne).justPressed)return void _()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(he.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,rt)))){n.get(i,rt).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,rt)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([rt,Re]);for(const e of a){const t=n.get(e,rt);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 it(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 at(e){let t=1;for(;t<e;)t*=2;return t}const lt=new ot;var ct;function ut(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"}(ct||(ct={}));let ht=null,dt=null,ft=1;const pt=new Map;function mt(e){ht=e,dt=e.getResourceManager(),Ct()}function _t(){0!==xt&&ht&&(ht._free(xt),xt=0),pt.clear(),ft=1,wt=!1,dt=null,ht=null}function gt(){if(!dt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return dt}const yt={createShader:(e,t)=>gt().createShader(e,t),releaseShader(e){e>0&&gt().releaseShader(e)},create(e){const t=ft++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??ct.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return pt.set(t,n),t},get:e=>pt.get(e),setUniform(e,t,n){const s=pt.get(e);s&&s.uniforms.set(t,n)},getUniform(e,t){const n=pt.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=pt.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=pt.get(e);return t?.blendMode??ct.Normal},setDepthTest(e,t){const n=pt.get(e);n&&(n.depthTest=t)},getShader(e){const t=pt.get(e);return t?.shader??0},release(e){pt.delete(e)},isValid:e=>pt.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??ct.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=pt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=ft++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return pt.set(n,s),n},toAssetData(e,t){const n=pt.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=pt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let wt=!1,xt=0;const vt=4096,bt=new Map;let St=null;function Pt(e){const t=(0===xt&&ht&&(xt=ht._malloc(vt)),xt);if(0===t||!ht)return{ptr:0,count:0};let n=0,s=0;const r=ht.HEAPU8,o=ht.HEAPU32,i=ht.HEAPF32;for(const[a,l]of e){if(n+128>vt)break;let e=bt.get(a);e||(St||(St=new TextEncoder),e=St.encode(a),bt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function Ct(){if(!ht||wt)return;ht.materialDataProvider=(e,t,n,s,r)=>{const o=pt.get(e);if(!o)return ht.HEAPU32[t>>2]=0,ht.HEAPU32[n>>2]=0,ht.HEAPU32[s>>2]=0,void(ht.HEAPU32[r>>2]=0);ht.HEAPU32[t>>2]=o.shader,ht.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Pt(o.uniforms);ht.HEAPU32[s>>2]=i,ht.HEAPU32[r>>2]=a},wt=!0}const Mt={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 Et{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&&(yt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())yt.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:yt.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 Tt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();n.set(s.id,t),e.insert(t,G,{value:s.name});for(const n of s.components)Rt(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 At(e,t,n){const s=new Map,r=n?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();s.set(i.id,t),e.insert(t,G,{value:i.name});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}}Rt(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 Rt(e,t,n){const s=n.data;switch(n.type){case"LocalTransform":e.insert(t,$,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,Be,s);break;case"Interactable":e.insert(t,je,s);break;case"Button":e.insert(t,Ve,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,M,s);break;default:{const r=B(n.type);r?e.insert(t,r,s):console.warn(`Unknown component type: ${n.type}`);break}}}function Ft(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 Ut(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 Bt{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 It{constructor(e){this.textureCache_=new Bt,this.shaderCache_=new Bt,this.jsonCache_=new Bt,this.textCache_=new Bt,this.binaryCache_=new Bt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Bt,this.embedded_=new Map,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.module_=e,this.canvas_=h(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 Et(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n)}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.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 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 At(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];if(e.textures)for(const s of e.textures)n.push(this.loadTexture(s).then(e=>{t.textures.set(s,e)}));if(e.materials)for(const s of e.materials)n.push(this.loadMaterial(s).then(e=>{t.materials.set(s,e)}));if(e.spine)for(const s of e.spine){const e=`${s.skeleton}:${s.atlas}`;n.push(this.loadSpine(s.skeleton,s.atlas,s.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const s of e.json)n.push(this.loadJson(s).then(e=>{t.json.set(s,e)}));if(e.text)for(const s of e.text)n.push(this.loadText(s).then(e=>{t.text.set(s,e)}));if(e.binary)for(const s of e.binary)n.push(this.loadBinary(s).then(e=>{t.binary.set(s,e)}));return await Promise.all(n),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 loadByAddress(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"json":return this.loadJson(e.path);case"text":return this.loadText(e.path);default:return this.loadBinary(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e)switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(e=>{t.textures.set(s.path,e)}));break;case"material":n.push(this.loadMaterial(s.path).then(e=>{t.materials.set(s.path,e)}));break;case"json":n.push(this.loadJson(s.path).then(e=>{t.json.set(s.path,e)}));break;case"text":n.push(this.loadText(s.path).then(e=>{t.text.set(s.path,e)}));break;default:n.push(this.loadBinary(s.path).then(e=>{t.binary.set(s.path,e)}))}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)??n;return new Promise((n,r)=>{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=()=>r(new Error(`Failed to load image: ${e}`)),o.src=s})}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;if(!await c(t))throw new Error(`Shader file not found: ${e}`);const n=await l(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:s,fragment:r}=this.parseEsShader(n);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return yt.createShader(s,r)}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 e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const n=await l(t);return JSON.parse(n)}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 e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):l(t)}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 e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):a(t)}const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const kt=Q(null,"Assets");class zt{build(e){const t=e.wasmModule;t?e.insertResource(kt,new It(t)):console.warn("AssetPlugin: No WASM module available")}}const Lt=new zt;function $t(e,t){const n=e.getResource(kt);n&&n.registerEmbeddedAssets(t)}let Dt=null,Ht=0,Wt=0,Ot=0;const jt=new Float32Array(256);function Nt(e){Dt=e,Ht=Dt._malloc(64),Wt=Dt._malloc(64),Ot=Dt._malloc(1024)}function Xt(){Dt&&(Ht&&(Dt._free(Ht),Ht=0),Wt&&(Dt._free(Wt),Wt=0),Ot&&(Dt._free(Ot),Ot=0)),Dt=null}function Vt(){if(!Dt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Dt}const Yt={r:1,g:1,b:1,a:1},Gt={begin(e){const t=Vt();t.HEAPF32.set(e,Ht/4),t.draw_begin(Ht)},end(){Vt().draw_end()},line(e,t,n,s=1){Vt().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){Vt().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){Vt().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){Vt().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){Vt().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=Yt){Vt().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=Yt){Vt().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){Vt().draw_setLayer(e)},setDepth(e){Vt().draw_setDepth(e)},getDrawCallCount:()=>Dt?Dt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Dt?Dt.draw_getPrimitiveCount():0,setBlendMode(e){Vt().draw_setBlendMode(e)},setDepthTest(e){Vt().draw_setDepthTest(e)},drawMesh(e,t,n){const s=Vt();s.HEAPF32.set(n,Wt/4),s.draw_mesh(e,t,Wt)},drawMeshWithMaterial(e,t,n){const s=Vt(),r=yt.get(t);if(!r)return;if(Gt.setBlendMode(r.blendMode),Gt.setDepthTest(r.depthTest),0===r.uniforms.size)return void Gt.drawMesh(e,r.shader,n);s.HEAPF32.set(n,Wt/4);let o=0,i=0;for(const[e,t]of r.uniforms){const n=Kt(e);if(!(n<0)){if(ut(t))jt[o++]=10,jt[o++]=n,jt[o++]=t.slot??i++,jt[o++]=t.textureId;else if("number"==typeof t)jt[o++]=1,jt[o++]=n,jt[o++]=t;else if(Array.isArray(t)){jt[o++]=t.length,jt[o++]=n;for(let e=0;e<t.length;e++)jt[o++]=t[e]}else"w"in t?(jt[o++]=4,jt[o++]=n,jt[o++]=t.x,jt[o++]=t.y,jt[o++]=t.z,jt[o++]=t.w):"z"in t?(jt[o++]=3,jt[o++]=n,jt[o++]=t.x,jt[o++]=t.y,jt[o++]=t.z):(jt[o++]=2,jt[o++]=n,jt[o++]=t.x,jt[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(jt.subarray(0,o),Ot/4),s.draw_meshWithUniforms(e,r.shader,Wt,Ot,o)):s.draw_mesh(e,r.shader,Wt)}},qt={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 Kt(e){return qt[e]??-1}var Jt;!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"}(Jt||(Jt={}));let Qt=null,Zt=0,en=0,tn=0;function nn(e){Qt=e,Zt=Qt._malloc(262144),en=Qt._malloc(65536),tn=Qt._malloc(256)}function sn(){Qt&&(Zt&&Qt._free(Zt),en&&Qt._free(en),tn&&Qt._free(tn),Zt=0,en=0,tn=0),Qt=null}function rn(){if(!Qt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Qt}const on={create(e){const t=rn(),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,Zt/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,tn,r).set(o),t.geometry_init(n,Zt,s,tn,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,en,s).set(e.indices),t.geometry_setIndices16(n,en,s)}else{new Uint32Array(t.HEAPU8.buffer,en,s).set(e.indices),t.geometry_setIndices32(n,en,s)}}return n},updateVertices(e,t,n=0){const s=rn(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,Zt/4),s.geometry_updateVertices(e,Zt,r,n)},release(e){e>0&&rn().geometry_release(e)},isValid:e=>!(!Qt||e<=0)&&Qt.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return on.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:Jt.Float2},{name:"a_texCoord",type:Jt.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 on.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Jt.Float2},{name:"a_texCoord",type:Jt.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 on.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Jt.Float2},{name:"a_texCoord",type:Jt.Float2}],indices:new Uint16Array(i)})}};let an=null;function ln(e){an=e}function cn(){an&&hn.isInitialized()&&hn.shutdown(),an=null}function un(){if(!an)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return an}const hn={init:(e,t)=>un().postprocess_init(e,t),shutdown(){un().postprocess_shutdown()},resize(e,t){un().postprocess_resize(e,t)},addPass:(e,t)=>un().postprocess_addPass(e,t),removePass(e){un().postprocess_removePass(e)},setEnabled(e,t){un().postprocess_setPassEnabled(e,t)},isEnabled:e=>un().postprocess_isPassEnabled(e),setUniform(e,t,n){un().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){un().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){un().postprocess_begin()},end(){un().postprocess_end()},getPassCount:()=>un().postprocess_getPassCount(),isInitialized:()=>!!an&&an.postprocess_isInitialized(),setBypass(e){un().postprocess_setBypass(e)},isBypassed:()=>!an||an.postprocess_isBypassed(),createBlur:()=>yt.createShader(dn,"#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:()=>yt.createShader(dn,"#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:()=>yt.createShader(dn,"#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:()=>yt.createShader(dn,"#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")},dn="#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 fn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(fn||(fn={}));let pn=null,mn=0;function _n(e){pn=e,mn=pn._malloc(64)}function gn(){pn&&mn&&(pn._free(mn),mn=0),pn=null}const yn={init(e,t){pn?.renderer_init(e,t)},resize(e,t){pn?.renderer_resize(e,t)},begin(e,t){pn&&mn&&(pn.HEAPF32.set(e,mn/4),pn.renderer_begin(mn,t??0))},flush(){pn?.renderer_flush()},end(){pn?.renderer_end()},submitSprites(e){pn&&pn.renderer_submitSprites(e._cpp)},submitBitmapText(e){pn&&pn.renderer_submitBitmapText(e._cpp)},submitSpine(e){pn&&pn.renderer_submitSpine?.(e._cpp)},setStage(e){pn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>pn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){pn?.renderer_releaseTarget(e)},getTargetTexture:e=>pn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>pn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){pn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){pn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){pn?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){pn?.renderer_clearBuffers(e)},getStats:()=>pn?{drawCalls:pn.renderer_getDrawCalls(),triangles:pn.renderer_getTriangles(),sprites:pn.renderer_getSprites(),text:pn.renderer_getText(),spine:pn.renderer_getSpine?.()??0,meshes:pn.renderer_getMeshes(),culled:pn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let wn=null;function xn(e){wn=e}function vn(){wn=null}const bn={enable(){wn?.gl_enableErrorCheck(!0)},disable(){wn?.gl_enableErrorCheck(!1)},check:e=>wn?.gl_checkErrors(e)??0,diagnose(){wn?.renderer_diagnose()}},Sn=new Map;function Pn(e,t){Sn.set(e,t)}function Cn(e){Sn.delete(e)}function Mn(){Sn.clear()}class En{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}setSpineRenderer(e){this.spineRenderer_=e}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_||(yn.resize(s,r),hn.isInitialized()&&hn.getPassCount()>0&&hn.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),yn.setViewport(0,0,s,r),yn.clearBuffers(3),yn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),yn.submitSprites(t),yn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):yn.submitSpine(t),yn.flush(),this.executeDrawCallbacks(n,o),yn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;yn.setViewport(s.x,s.y,s.w,s.h),yn.setScissor(s.x,s.y,s.w,s.h,!0),yn.clearBuffers(r),yn.setScissor(0,0,0,0,!1),yn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),yn.submitSprites(t),yn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):yn.submitSpine(t),yn.flush(),this.executeDrawCallbacks(n,o),yn.end()}executeDrawCallbacks(e,t){const n=Sn;if(n.size>0){Gt.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)}Gt.end();for(const e of s)Cn(e)}}}class Tn{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=d(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.runSchedule(he.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(he.FixedPreUpdate),this.runSchedule(he.FixedUpdate),this.runSchedule(he.FixedPostUpdate);this.runSchedule(he.PreUpdate),this.runSchedule(he.Update),this.runSchedule(he.PostUpdate),this.runSchedule(he.Last),requestAnimationFrame(this.mainLoop)},this.world_=new Pe,this.resources_=new ne;for(const e of Object.values(he))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Tn}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(he.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(he.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}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(he.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,vn(),gn(),cn(),sn(),_t(),Xt()}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 An(e,t){const n=Tn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Nt(e),mt(e),nn(e),ln(e),_n(e),xn(e);const r=new En;n.pipeline_=r;let o=d();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r){const o=Bn(e,s,t,r),i=n.getResource(qe);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(qe,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,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(),l=e.registry_getCanvasEntity(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;yn.setClearColor(e.r,e.g,e.b,e.a)}const c=(d()-o)/1e3;yn.resize(t,n),hn.isInitialized()&&hn.getPassCount()>0&&!hn.isBypassed()&&hn.resize(t,n);const u=Bn(e,s,t,n);if(a(t,n),0===u.length)r.render({registry:{_cpp:s},viewProjection:Fn,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})}yn.setViewport(0,0,t,n)}}};return n.addSystemToSchedule(he.First,l),n.addSystemToSchedule(he.Last,c),n.addPlugin(Lt),n.addPlugin(be),n.addPlugin(Ue),n.addPlugin(Oe),n.addPlugin(st),n.addPlugin(Qe),n.addPlugin(lt),n}function Rn(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 Fn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Un(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 Bn(e,t,n,s){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,h=0,d=0;if(1===r.projectionType){if(d=r.orthoSize,o){d=Un(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}h=d*c,u=kn(-h,h,-d,d,-r.farPlane,r.farPlane)}else u=Ln(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=Dn(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:Hn(u,f),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:h,halfH:d,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const In=new Float32Array(16);function kn(e,t,n,s,r,o){const i=In;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 zn=new Float32Array(16);function Ln(e,t,n,s){const r=zn;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 $n=new Float32Array(16);function Dn(e,t,n){const s=$n;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 Hn(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 Wn(e,t){if(t)return t();return(0,(await import(e)).default)()}const On=Q({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),jn=Q(null,"PhysicsAPI");function Nn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Xn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Vn{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(On,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Wn(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(he.PostUpdate,fe([Z(se)],a=>{const l=i.getEntitiesWithComponents([S,$,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=Nn(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),Yn(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===E.Kinematic){const e=Nn(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,$);if(!u)continue;let h=a,d=l,f=c;if(e.world.has(i,N)){const t=e.world.get(i,N);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,D)){const n=e.world.get(t.entity,D),s=Nn(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),u=Math.sin(-s);h=(r*i-o*u)/(0!==n.scale.x?n.scale.x:1),d=(r*u+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}u.position.x=h,u.position.y=d;const p=Xn(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,$,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(On,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.__physicsModule=s,e.insertResource(jn,Gn._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=s}}function Yn(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,M)){const e=s.get(n,M);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Gn{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(Gn.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 qn(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 Kn(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 Jn(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,h=a+a,d=l+l,f=c+c,p=a*h,m=a*d,_=a*f,g=l*d,y=l*f,w=c*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(g+w))*r,(m+b)*r,(_-v)*r,0,(m-b)*o,(1-(p+w))*o,(y+x)*o,0,(_+v)*i,(y-x)*i,(1-(p+g))*i,0,e.position.x,e.position.y,e.position.z,1])}async function Qn(e,t,n,s,r,o,i){const a=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]=qn(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,a);let l={},c=null;if(r&&(c=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),l=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 h,d;if(u){const e=r.readBinary(i);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=r.readText(i),n=(new TextEncoder).encode(e);d=n.length,h=t._malloc(d+1),t.HEAPU8.set(n,h),t.HEAPU8[h+d]=0}const f=n.loadSkeleton(h,d,s,s.length,u);if(t._free(h),f<0)continue;o[i]=f;const p=Kn(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=qn(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,c,n,s)),o){new Vn("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const u=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=yt.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=yt.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),h=Tt(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,a,h),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,u,h),r&&c){const s=function(e,t,n,s){const r={};for(const o of t.entities)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}(c,n,l,h);!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,h=a?.timeScale??1;u&&s.update(i,l*h);let d=0;if(c.has(o,D)){const e=Jn(c.get(o,D),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,h,f);const p=n.HEAPU32[h>>2],m=n.HEAPU32[f>>2],_=new Float32Array(n.HEAPF32.buffer,c,8*r),g=new Uint16Array(n.HEAPU8.buffer,u,o),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(_,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(g),t.renderer_submitTriangles(y,r,w,o,p,m,d),t._free(y),t._free(w),n._free(c),n._free(u),n._free(h),n._free(f)}d&&t._free(d)}})}(e,t,r,c,s)}}class Zn{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;for(const s of e.entities)for(const e of s.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)}"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const s=[];for(const e of t)s.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of n)s.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(s)}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 es{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_)try{const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new Zn(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.__spineInitPromise;if(r){s=(await r).controller.raw}await Qn(this.app_,this.app_.wasmModule,t,n,s),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}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,$,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 ts={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=yn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:yn.getTargetTexture(n),width:e.width,height:e.height}},release(e){yn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(yn.releaseRenderTarget(e._handle),ts.create({width:t,height:n,depth:!0})),begin(e,t){yn.begin(t,e._handle)},end(){yn.end()},getDepthTexture:e=>yn.getTargetDepthTexture(e._handle)};let ns=!1;function ss(e){ns=e}function rs(){return ns}function os(){return!ns}e=f;export{Tn as App,zt as AssetPlugin,It as AssetServer,kt as Assets,Bt as AsyncCache,V as BitmapText,ct as BlendMode,E as BodyType,P as BoxCollider,Ve as Button,Xe as ButtonState,W as Camera,O as Canvas,M as CapsuleCollider,X as Children,C as CircleCollider,le as Commands,ue as CommandsInstance,Jt as DataType,Gt as Draw,ce as EntityCommands,bn as GLDebug,on as Geometry,p as INVALID_ENTITY,_ as INVALID_FONT,m as INVALID_TEXTURE,xe as Input,ve as InputPlugin,we as InputState,je as Interactable,$ as LocalTransform,yt as Material,Et as MaterialLoader,re as Mut,G as Name,N as Parent,Gn as Physics,On as PhysicsEvents,Vn as PhysicsPlugin,hn as PostProcess,es as PreviewPlugin,ie as Query,ae as QueryInstance,En as RenderPipeline,fn as RenderStage,ts as RenderTexture,yn as Renderer,Z as Res,ee as ResMut,S as RigidBody,he as Schedule,Ze as ScreenSpace,Mt as ShaderSources,Y as SpineAnimation,H as Sprite,ye as SystemRunner,Te as Text,Ce as TextAlign,rt as TextInput,ot as TextInputPlugin,Ee as TextOverflow,Fe as TextPlugin,Ae as TextRenderer,Me as TextVerticalAlign,se as Time,qe as UICameraInfo,Ye as UIEventQueue,Ge as UIEvents,Ne as UIInteraction,Je as UIInteractionPlugin,nt as UILayoutPlugin,Be as UIMask,We as UIMaskPlugin,Re as UIRect,j as Velocity,Zn as WebAssetProvider,Pe as World,D as WorldTransform,_e as addStartupSystem,me as addSystem,ge as addSystemToSchedule,Lt as assetPlugin,Mn as clearDrawCallbacks,I as clearUserComponents,x as color,et as computeUIRectLayout,He as createMaskProcessor,An as createWebApp,F as defineComponent,Q as defineResource,fe as defineSystem,U as defineTag,Ut as findEntityByName,Rn as flushPendingSystems,K as getComponentDefaults,t as getPlatform,s as getPlatformType,B as getUserComponent,Nt as initDrawAPI,xn as initGLDebugAPI,nn as initGeometryAPI,mt as initMaterialAPI,ln as initPostProcessAPI,_n as initRendererAPI,be as inputPlugin,Ie as intersectRects,ze as invertMatrix4,L as isBuiltinComponent,rs as isEditor,n as isPlatformInitialized,os as isRuntime,ut as isTextureRef,r as isWeChat,o as isWeb,Rt as loadComponent,Wn as loadPhysicsModule,Qn as loadRuntimeScene,Tt as loadSceneData,At as loadSceneWithAssets,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,$e as pointInWorldRect,v as quat,Pn as registerDrawCallback,$t as registerEmbeddedAssets,Ct as registerMaterialCallback,Le as screenToWorld,ss as setEditorMode,Xt as shutdownDrawAPI,vn as shutdownGLDebugAPI,sn as shutdownGeometryAPI,_t as shutdownMaterialAPI,cn as shutdownPostProcessAPI,gn as shutdownRendererAPI,lt as textInputPlugin,Ue as textPlugin,Qe as uiInteractionPlugin,st as uiLayoutPlugin,Oe as uiMaskPlugin,Cn as unregisterDrawCallback,Ft as updateCameraAspectRatio,g as vec2,y as vec3,w as vec4,ke 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 h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.module}}createImage(){return new Image}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),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)},h=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",h),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",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=0,m=4294967295,_=4294967295,g=(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 z(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function L(e){return!0===e._builtin}const $=z("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),D=z("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),H=z("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=z("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=z("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),j=z("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),N=z("Parent",{entity:0}),X=z("Children",{entities:[]}),V=z("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:_}),Y=z("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),G={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},q={LocalTransform:$,WorldTransform:D,Sprite:H,Camera:W,Canvas:O,Velocity:j,Parent:N,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=L(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 he;!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"}(he||(he={}));let de=0;function fe(e,t,n){const s=++de;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:he.Update,system:e})}function _e(e){pe().push({schedule:he.Startup,system:e})}function ge(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(he.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 L(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return L(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return L(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){L(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(!L(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,dirty:!0});class Ae{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(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),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=r?Math.ceil(o):h+2*u,p=r?Math.ceil(i):d+2*u;if(r&&e.overflow===Me.Ellipsis&&d>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const m=Math.round(255*e.color.r),_=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${_}, ${g}, ${y})`,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}});class Fe{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;e.addSystemToSchedule(he.PreUpdate,fe([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Te));const e=s.getEntitiesWithComponents([Te]);for(const t of e){const e=s.get(t,Te);if(!e.dirty)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 r=s.has(t,Re)?s.get(t,Re):null,o=n.renderForEntity(t,e,r),i=s.get(t,H);i.texture=o.textureHandle,i.size.x=o.width,i.size.y=o.height,i.uvOffset.x=0,i.uvOffset.y=0,i.uvScale.x=1,i.uvScale.y=1,s.insert(t,H,i),e.dirty=!1}}))}}const Ue=new Fe,Be=F("UIMask",{enabled:!0});function Ie(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 ke(e,t,n,s,r,o,i,a,l,c,u){const h=e-n*r,d=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(h,f),[y,w]=m(d,p),x=Math.min(_,y),v=Math.max(_,y),b=Math.min(g,w),S=Math.max(g,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}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],h=e[8],d=e[9],f=e[10],p=e[11],m=e[12],_=e[13],g=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=h*_-d*m,E=h*g-f*m,M=h*y-p*m,T=d*g-f*_,A=d*y-p*_,R=f*y-p*g;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]=(_*P-g*S+y*b)*F,n[3]=(f*S-d*P-p*b)*F,n[4]=(c*M-a*R-u*E)*F,n[5]=(s*R-o*M+i*E)*F,n[6]=(g*v-m*P-y*x)*F,n[7]=(h*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-_*v+y*w)*F,n[11]=(d*v-h*S-p*w)*F,n[12]=(l*E-a*T-c*C)*F,n[13]=(s*T-r*E+o*C)*F,n[14]=(_*x-m*b-g*w)*F,n[15]=(h*b-d*x+f*w)*F),n}function Le(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:u/h}}function $e(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 De(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 ke(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function He(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Be]);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,Be).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,N);){const e=t.get(s,N);if(c.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function h(s,u){const d=e.getChildEntities(n,s);for(const n of d){let s=u;if(c.has(n)){const e=De(t,n,r,o,i,a,l);e&&(s=Ie(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of u){const n=De(t,e,r,o,i,a,l);n&&h(e,n)}}(e,t,n,l,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class We{build(e){if(!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(He(e.wasmModule,e.world))}}const Oe=new We,je=F("Interactable",{enabled:!0}),Ne=F("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Xe;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Xe||(Xe={}));const Ve=F("Button",{state:Xe.Normal,transition:null});class Ye{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 Ge=Q(new Ye,"UIEvents"),qe=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"),Je=new Float32Array(16);class Ke{build(e){const t=e.world,n=new Ye;e.insertResource(Ge,n);let s=null,r=null;e.addSystemToSchedule(he.PreUpdate,fe([Z(xe),Z(qe)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([Ne]);for(const e of i){const n=t.get(e,Ne);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,Je);const u=Le(l,c,Je,o.vpX,o.vpY,o.vpW,o.vpH),h=t.getEntitiesWithComponents([je,Re,D]);let d=null,f=-1/0;for(const e of h){t.has(e,Ne)||t.insert(e,Ne);if(!t.get(e,je).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($e(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,d=e)}}if(s!==d){if(null!==s&&t.valid(s)&&t.has(s,Ne)){t.get(s,Ne).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,Ne).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,Ne);e.pressed=!0,e.justPressed=!0,r=d,n.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Ne)){const e=t.get(r,Ne);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(he.Update,fe([],()=>{const e=t.getEntitiesWithComponents([Ve]);for(const n of e){if(t.has(n,je)||t.insert(n,je,{enabled:!0}),!t.has(n,Ne))continue;const e=t.get(n,Ne),s=t.get(n,Ve),r=t.get(n,je),o=s.state;if(r.enabled?e.pressed?s.state=Xe.Pressed:e.hovered?s.state=Xe.Hovered:s.state=Xe.Normal:s.state=Xe.Disabled,o!==s.state&&s.transition&&t.has(n,H)){const e=t.get(n,H),r=s.transition;switch(s.state){case Xe.Normal:e.color={...r.normalColor};break;case Xe.Hovered:e.color={...r.hoveredColor};break;case Xe.Pressed:e.color={...r.pressedColor};break;case Xe.Disabled:e.color={...r.disabledColor}}t.insert(n,H,e)}}},{name:"ButtonSystem"}))}}const Qe=new Ke,Ze=U("ScreenSpace");function et(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,h=o.bottom+t.y*a;let d,f,p,m;if(l===c&&u===h){const e=l+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;d=e-s,f=t-o,p=e+s,m=t+o}else d=l+n.x,f=u+n.y,p=c+s.x,m=h+s.y;return{centerX:.5*(d+p),centerY:.5*(f+m),width:p-d,height:m-f,rect:{left:d,bottom:f,right:p,top:m}}}function tt(e,t,n,s,r,o){if(!e.has(t,Re))return;const i=e.get(t,Re),a=et(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,$);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),!e.has(t,X))return;const c=e.get(t,X);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&tt(e,t,a.rect,a.centerX,a.centerY,!1)}class nt{build(e){const t=e.world;e.addSystemToSchedule(he.PreUpdate,fe([Z(qe)],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([Ze,Re,$]);for(const e of o)tt(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const st=new nt,rt=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 ot{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=h(512,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,u=0;const d=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,rt);if(t.readOnly)return;let s=d.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),d.value=s),s!==t.value){t.value=s;e.getResource(Ge).emit(i,"change")}t.cursorPos=d.selectionStart??s.length,t.dirty=!0,g()}function p(e){if(i===e)return;_();const t=n.get(e,rt);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,d.value=t.value,d.selectionStart=t.cursorPos,d.selectionEnd=t.cursorPos,d.focus(),g())}function _(){if(null!==i&&n.valid(i)&&n.has(i,rt)){const e=n.get(i,rt);e.focused=!1,e.dirty=!0}i=null,d.blur()}function g(){l=!0,c=0}function y(e,i,a,c){(r.width<a||r.height<c)&&(r.width=at(Math.max(r.width,a)),r.height=at(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 h=0===i.value.length,d=h?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=h?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=it(o,d,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(d,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=it(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 _=o.getImageData(0,0,a,c),g=new Uint8Array(_.data.buffer),y=t.getResourceManager(),w=t._malloc(g.length);t.HEAPU8.set(g,w);const x=s.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,c,w,g.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)}d.addEventListener("input",()=>{a||null===i||f()}),d.addEventListener("compositionstart",()=>{a=!0}),d.addEventListener("compositionend",()=>{a=!1,f()}),d.addEventListener("keydown",t=>{if(null===i)return;if("Escape"===t.key)return void _();const s=n.get(i,rt);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(Ge).emit(i,"submit"),void _()}}),d.addEventListener("blur",()=>{if(null!==i&&n.valid(i)&&n.has(i,rt)){const e=n.get(i,rt);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(he.PreUpdate,fe([Z(Ge)],e=>{const t=n.getEntitiesWithComponents([rt,je]);for(const e of t){if(!n.has(e,Ne))continue;if(n.get(e,Ne).justPressed)return void p(e)}if(null!==i){const e=n.getEntitiesWithComponents([je]);for(const t of e){if(n.has(t,rt))continue;if(!n.has(t,Ne))continue;if(n.get(t,Ne).justPressed)return void _()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(he.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,rt)))){n.get(i,rt).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,rt)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([rt,Re]);for(const e of a){const t=n.get(e,rt);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 it(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 at(e){let t=1;for(;t<e;)t*=2;return t}const lt=new ot;var ct;function ut(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"}(ct||(ct={}));let ht=null,dt=null,ft=1;const pt=new Map;function mt(e){ht=e,dt=e.getResourceManager(),Ct()}function _t(){0!==xt&&ht&&(ht._free(xt),xt=0),pt.clear(),ft=1,wt=!1,dt=null,ht=null}function gt(){if(!dt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return dt}const yt={createShader:(e,t)=>gt().createShader(e,t),releaseShader(e){e>0&&gt().releaseShader(e)},create(e){const t=ft++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??ct.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return pt.set(t,n),t},get:e=>pt.get(e),setUniform(e,t,n){const s=pt.get(e);s&&s.uniforms.set(t,n)},getUniform(e,t){const n=pt.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=pt.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=pt.get(e);return t?.blendMode??ct.Normal},setDepthTest(e,t){const n=pt.get(e);n&&(n.depthTest=t)},getShader(e){const t=pt.get(e);return t?.shader??0},release(e){pt.delete(e)},isValid:e=>pt.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??ct.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=pt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=ft++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return pt.set(n,s),n},toAssetData(e,t){const n=pt.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=pt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let wt=!1,xt=0;const vt=4096,bt=new Map;let St=null;function Pt(e){const t=(0===xt&&ht&&(xt=ht._malloc(vt)),xt);if(0===t||!ht)return{ptr:0,count:0};let n=0,s=0;const r=ht.HEAPU8,o=ht.HEAPU32,i=ht.HEAPF32;for(const[a,l]of e){if(n+128>vt)break;let e=bt.get(a);e||(St||(St=new TextEncoder),e=St.encode(a),bt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function Ct(){if(!ht||wt)return;ht.materialDataProvider=(e,t,n,s,r)=>{const o=pt.get(e);if(!o)return ht.HEAPU32[t>>2]=0,ht.HEAPU32[n>>2]=0,ht.HEAPU32[s>>2]=0,void(ht.HEAPU32[r>>2]=0);ht.HEAPU32[t>>2]=o.shader,ht.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Pt(o.uniforms);ht.HEAPU32[s>>2]=i,ht.HEAPU32[r>>2]=a},wt=!0}const Et={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 Mt{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&&(yt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())yt.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:yt.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 Tt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();n.set(s.id,t),e.insert(t,G,{value:s.name});for(const n of s.components)Rt(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 At(e,t,n){const s=new Map,r=n?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();s.set(i.id,t),e.insert(t,G,{value:i.name});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}}Rt(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 Rt(e,t,n){const s=n.data;switch(n.type){case"LocalTransform":e.insert(t,$,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,Be,s);break;case"Interactable":e.insert(t,je,s);break;case"Button":e.insert(t,Ve,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 Ft(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 Ut(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 Bt{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 It{constructor(e){this.textureCache_=new Bt,this.shaderCache_=new Bt,this.jsonCache_=new Bt,this.textCache_=new Bt,this.binaryCache_=new Bt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Bt,this.prefabCache_=new Bt,this.embedded_=new Map,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.module_=e,this.canvas_=h(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 Mt(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n)}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 At(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];if(e.textures)for(const s of e.textures)n.push(this.loadTexture(s).then(e=>{t.textures.set(s,e)}));if(e.materials)for(const s of e.materials)n.push(this.loadMaterial(s).then(e=>{t.materials.set(s,e)}));if(e.spine)for(const s of e.spine){const e=`${s.skeleton}:${s.atlas}`;n.push(this.loadSpine(s.skeleton,s.atlas,s.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const s of e.json)n.push(this.loadJson(s).then(e=>{t.json.set(s,e)}));if(e.text)for(const s of e.text)n.push(this.loadText(s).then(e=>{t.text.set(s,e)}));if(e.binary)for(const s of e.binary)n.push(this.loadBinary(s).then(e=>{t.binary.set(s,e)}));return await Promise.all(n),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 loadByAddress(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"json":return this.loadJson(e.path);case"text":return this.loadText(e.path);default:return this.loadBinary(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e)switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(e=>{t.textures.set(s.path,e)}));break;case"material":n.push(this.loadMaterial(s.path).then(e=>{t.materials.set(s.path,e)}));break;case"json":n.push(this.loadJson(s.path).then(e=>{t.json.set(s.path,e)}));break;case"text":n.push(this.loadText(s.path).then(e=>{t.text.set(s.path,e)}));break;default:n.push(this.loadBinary(s.path).then(e=>{t.binary.set(s.path,e)}))}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)??n;return new Promise((n,r)=>{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=()=>r(new Error(`Failed to load image: ${e}`)),o.src=s})}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;if(!await c(t))throw new Error(`Shader file not found: ${e}`);const n=await l(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:s,fragment:r}=this.parseEsShader(n);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return yt.createShader(s,r)}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 e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const n=await l(t);return JSON.parse(n)}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 e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):l(t)}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 e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):a(t)}const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const kt=Q(null,"Assets");class zt{build(e){const t=e.wasmModule;t?e.insertResource(kt,new It(t)):console.warn("AssetPlugin: No WASM module available")}}const Lt=new zt;function $t(e,t){const n=e.getResource(kt);n&&n.registerEmbeddedAssets(t)}let Dt=null,Ht=0,Wt=0,Ot=0;const jt=new Float32Array(256);function Nt(e){Dt=e,Ht=Dt._malloc(64),Wt=Dt._malloc(64),Ot=Dt._malloc(1024)}function Xt(){Dt&&(Ht&&(Dt._free(Ht),Ht=0),Wt&&(Dt._free(Wt),Wt=0),Ot&&(Dt._free(Ot),Ot=0)),Dt=null}function Vt(){if(!Dt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Dt}const Yt={r:1,g:1,b:1,a:1},Gt={begin(e){const t=Vt();t.HEAPF32.set(e,Ht/4),t.draw_begin(Ht)},end(){Vt().draw_end()},line(e,t,n,s=1){Vt().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){Vt().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){Vt().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){Vt().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){Vt().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=Yt){Vt().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=Yt){Vt().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){Vt().draw_setLayer(e)},setDepth(e){Vt().draw_setDepth(e)},getDrawCallCount:()=>Dt?Dt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Dt?Dt.draw_getPrimitiveCount():0,setBlendMode(e){Vt().draw_setBlendMode(e)},setDepthTest(e){Vt().draw_setDepthTest(e)},drawMesh(e,t,n){const s=Vt();s.HEAPF32.set(n,Wt/4),s.draw_mesh(e,t,Wt)},drawMeshWithMaterial(e,t,n){const s=Vt(),r=yt.get(t);if(!r)return;if(Gt.setBlendMode(r.blendMode),Gt.setDepthTest(r.depthTest),0===r.uniforms.size)return void Gt.drawMesh(e,r.shader,n);s.HEAPF32.set(n,Wt/4);let o=0,i=0;for(const[e,t]of r.uniforms){const n=Jt(e);if(!(n<0)){if(ut(t))jt[o++]=10,jt[o++]=n,jt[o++]=t.slot??i++,jt[o++]=t.textureId;else if("number"==typeof t)jt[o++]=1,jt[o++]=n,jt[o++]=t;else if(Array.isArray(t)){jt[o++]=t.length,jt[o++]=n;for(let e=0;e<t.length;e++)jt[o++]=t[e]}else"w"in t?(jt[o++]=4,jt[o++]=n,jt[o++]=t.x,jt[o++]=t.y,jt[o++]=t.z,jt[o++]=t.w):"z"in t?(jt[o++]=3,jt[o++]=n,jt[o++]=t.x,jt[o++]=t.y,jt[o++]=t.z):(jt[o++]=2,jt[o++]=n,jt[o++]=t.x,jt[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(jt.subarray(0,o),Ot/4),s.draw_meshWithUniforms(e,r.shader,Wt,Ot,o)):s.draw_mesh(e,r.shader,Wt)}},qt={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 Jt(e){return qt[e]??-1}var Kt;!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"}(Kt||(Kt={}));let Qt=null,Zt=0,en=0,tn=0;function nn(e){Qt=e,Zt=Qt._malloc(262144),en=Qt._malloc(65536),tn=Qt._malloc(256)}function sn(){Qt&&(Zt&&Qt._free(Zt),en&&Qt._free(en),tn&&Qt._free(tn),Zt=0,en=0,tn=0),Qt=null}function rn(){if(!Qt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Qt}const on={create(e){const t=rn(),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,Zt/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,tn,r).set(o),t.geometry_init(n,Zt,s,tn,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,en,s).set(e.indices),t.geometry_setIndices16(n,en,s)}else{new Uint32Array(t.HEAPU8.buffer,en,s).set(e.indices),t.geometry_setIndices32(n,en,s)}}return n},updateVertices(e,t,n=0){const s=rn(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,Zt/4),s.geometry_updateVertices(e,Zt,r,n)},release(e){e>0&&rn().geometry_release(e)},isValid:e=>!(!Qt||e<=0)&&Qt.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return on.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:Kt.Float2},{name:"a_texCoord",type:Kt.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 on.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Kt.Float2},{name:"a_texCoord",type:Kt.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 on.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Kt.Float2},{name:"a_texCoord",type:Kt.Float2}],indices:new Uint16Array(i)})}};let an=null;function ln(e){an=e}function cn(){an&&hn.isInitialized()&&hn.shutdown(),an=null}function un(){if(!an)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return an}const hn={init:(e,t)=>un().postprocess_init(e,t),shutdown(){un().postprocess_shutdown()},resize(e,t){un().postprocess_resize(e,t)},addPass:(e,t)=>un().postprocess_addPass(e,t),removePass(e){un().postprocess_removePass(e)},setEnabled(e,t){un().postprocess_setPassEnabled(e,t)},isEnabled:e=>un().postprocess_isPassEnabled(e),setUniform(e,t,n){un().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){un().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){un().postprocess_begin()},end(){un().postprocess_end()},getPassCount:()=>un().postprocess_getPassCount(),isInitialized:()=>!!an&&an.postprocess_isInitialized(),setBypass(e){un().postprocess_setBypass(e)},isBypassed:()=>!an||an.postprocess_isBypassed(),createBlur:()=>yt.createShader(dn,"#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:()=>yt.createShader(dn,"#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:()=>yt.createShader(dn,"#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:()=>yt.createShader(dn,"#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")},dn="#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 fn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(fn||(fn={}));let pn=null,mn=0;function _n(e){pn=e,mn=pn._malloc(64)}function gn(){pn&&mn&&(pn._free(mn),mn=0),pn=null}const yn={init(e,t){pn?.renderer_init(e,t)},resize(e,t){pn?.renderer_resize(e,t)},begin(e,t){pn&&mn&&(pn.HEAPF32.set(e,mn/4),pn.renderer_begin(mn,t??0))},flush(){pn?.renderer_flush()},end(){pn?.renderer_end()},submitSprites(e){pn&&pn.renderer_submitSprites(e._cpp)},submitBitmapText(e){pn&&pn.renderer_submitBitmapText(e._cpp)},submitSpine(e){pn&&pn.renderer_submitSpine?.(e._cpp)},setStage(e){pn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>pn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){pn?.renderer_releaseTarget(e)},getTargetTexture:e=>pn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>pn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){pn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){pn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){pn?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){pn?.renderer_clearBuffers(e)},getStats:()=>pn?{drawCalls:pn.renderer_getDrawCalls(),triangles:pn.renderer_getTriangles(),sprites:pn.renderer_getSprites(),text:pn.renderer_getText(),spine:pn.renderer_getSpine?.()??0,meshes:pn.renderer_getMeshes(),culled:pn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let wn=null;function xn(e){wn=e}function vn(){wn=null}const bn={enable(){wn?.gl_enableErrorCheck(!0)},disable(){wn?.gl_enableErrorCheck(!1)},check:e=>wn?.gl_checkErrors(e)??0,diagnose(){wn?.renderer_diagnose()}},Sn=new Map;function Pn(e,t){Sn.set(e,t)}function Cn(e){Sn.delete(e)}function En(){Sn.clear()}class Mn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}setSpineRenderer(e){this.spineRenderer_=e}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_||(yn.resize(s,r),hn.isInitialized()&&hn.getPassCount()>0&&hn.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),yn.setViewport(0,0,s,r),yn.clearBuffers(3),yn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),yn.submitSprites(t),yn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):yn.submitSpine(t),yn.flush(),this.executeDrawCallbacks(n,o),yn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;yn.setViewport(s.x,s.y,s.w,s.h),yn.setScissor(s.x,s.y,s.w,s.h,!0),yn.clearBuffers(r),yn.setScissor(0,0,0,0,!1),yn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),yn.submitSprites(t),yn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):yn.submitSpine(t),yn.flush(),this.executeDrawCallbacks(n,o),yn.end()}executeDrawCallbacks(e,t){const n=Sn;if(n.size>0){Gt.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)}Gt.end();for(const e of s)Cn(e)}}}class Tn{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=d(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.runSchedule(he.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(he.FixedPreUpdate),this.runSchedule(he.FixedUpdate),this.runSchedule(he.FixedPostUpdate);this.runSchedule(he.PreUpdate),this.runSchedule(he.Update),this.runSchedule(he.PostUpdate),this.runSchedule(he.Last),requestAnimationFrame(this.mainLoop)},this.world_=new Pe,this.resources_=new ne;for(const e of Object.values(he))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Tn}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(he.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(he.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(he.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,vn(),gn(),cn(),sn(),_t(),Xt()}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 An(e,t){const n=Tn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Nt(e),mt(e),nn(e),ln(e),_n(e),xn(e);const r=new Mn;n.pipeline_=r;let o=d();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r){const o=Bn(e,s,t,r),i=n.getResource(qe);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(qe,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,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;yn.setClearColor(e.x,e.y,e.z,e.w)}const c=(d()-o)/1e3;yn.resize(t,n),hn.isInitialized()&&hn.getPassCount()>0&&!hn.isBypassed()&&hn.resize(t,n);const u=Bn(e,s,t,n);if(a(t,n),0===u.length)r.render({registry:{_cpp:s},viewProjection:Fn,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})}yn.setViewport(0,0,t,n)}}};return n.addSystemToSchedule(he.First,l),n.addSystemToSchedule(he.Last,c),n.addPlugin(Lt),n.addPlugin(be),n.addPlugin(Ue),n.addPlugin(Oe),n.addPlugin(st),n.addPlugin(Qe),n.addPlugin(lt),n}function Rn(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 Fn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Un(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 Bn(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,h=0,d=0;if(1===r.projectionType){if(d=r.orthoSize,o){d=Un(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}h=d*c,u=kn(-h,h,-d,d,-r.farPlane,r.farPlane)}else u=Ln(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=Dn(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:Hn(u,f),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:h,halfH:d,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const In=new Float32Array(16);function kn(e,t,n,s,r,o){const i=In;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 zn=new Float32Array(16);function Ln(e,t,n,s){const r=zn;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 $n=new Float32Array(16);function Dn(e,t,n){const s=$n;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 Hn(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 Wn(e,t,n){const{entities:s,rootId:r}=await On(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}))},i=await At(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 On(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 On(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};jn(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 jn(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))}}async function Nn(e,t){if(t)return t();return(0,(await import(e)).default)()}const Xn=Q({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Vn=Q(null,"PhysicsAPI");function Yn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Gn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class qn{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(Xn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Nn(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(he.PostUpdate,fe([Z(se)],a=>{const l=i.getEntitiesWithComponents([S,$,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=Yn(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),Jn(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=Yn(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,$);if(!u)continue;let h=a,d=l,f=c;if(e.world.has(i,N)){const t=e.world.get(i,N);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,D)){const n=e.world.get(t.entity,D),s=Yn(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),u=Math.sin(-s);h=(r*i-o*u)/(0!==n.scale.x?n.scale.x:1),d=(r*u+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}u.position.x=h,u.position.y=d;const p=Gn(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,$,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(Xn,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.__physicsModule=s,e.insertResource(Vn,Kn._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=s}}function Jn(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 Kn{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(Kn.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 Qn(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 Zn(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 es(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,h=a+a,d=l+l,f=c+c,p=a*h,m=a*d,_=a*f,g=l*d,y=l*f,w=c*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(g+w))*r,(m+b)*r,(_-v)*r,0,(m-b)*o,(1-(p+w))*o,(y+x)*o,0,(_+v)*i,(y-x)*i,(1-(p+g))*i,0,e.position.x,e.position.y,e.position.z,1])}async function ts(e,t,n,s,r,o,i){const a=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]=Qn(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,a);let l={},c=null;if(r&&(c=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),l=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 h,d;if(u){const e=r.readBinary(i);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=r.readText(i),n=(new TextEncoder).encode(e);d=n.length,h=t._malloc(d+1),t.HEAPU8.set(n,h),t.HEAPU8[h+d]=0}const f=n.loadSkeleton(h,d,s,s.length,u);if(t._free(h),f<0)continue;o[i]=f;const p=Zn(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=Qn(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,c,n,s)),o){new qn("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const u=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;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=Qn(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=yt.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=yt.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),d=Tt(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,a,d),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,u,d),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,d),r&&c){const s=function(e,t,n,s){const r={};for(const o of t.entities)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}(c,n,l,d);!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,h=a?.timeScale??1;u&&s.update(i,l*h);let d=0;if(c.has(o,D)){const e=es(c.get(o,D),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,h,f);const p=n.HEAPU32[h>>2],m=n.HEAPU32[f>>2],_=new Float32Array(n.HEAPF32.buffer,c,8*r),g=new Uint16Array(n.HEAPU8.buffer,u,o),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(_,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(g),t.renderer_submitTriangles(y,r,w,o,p,m,d),t._free(y),t._free(w),n._free(c),n._free(u),n._free(h),n._free(f)}d&&t._free(d)}})}(e,t,r,c,s)}}class ns{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 ss{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_)try{const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new ns(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.__spineInitPromise;if(r){s=(await r).controller.raw}await ts(this.app_,this.app_.wasmModule,t,n,s),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}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,$,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 rs={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=yn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:yn.getTargetTexture(n),width:e.width,height:e.height}},release(e){yn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(yn.releaseRenderTarget(e._handle),rs.create({width:t,height:n,depth:!0})),begin(e,t){yn.begin(t,e._handle)},end(){yn.end()},getDepthTexture:e=>yn.getTargetDepthTexture(e._handle)};let os=!1;function is(e){os=e}function as(){return os}function ls(){return!os}e=f;export{Tn as App,zt as AssetPlugin,It as AssetServer,kt as Assets,Bt as AsyncCache,V as BitmapText,ct as BlendMode,M as BodyType,P as BoxCollider,Ve as Button,Xe as ButtonState,W as Camera,O as Canvas,E as CapsuleCollider,X as Children,C as CircleCollider,le as Commands,ue as CommandsInstance,Kt as DataType,Gt as Draw,ce as EntityCommands,bn as GLDebug,on as Geometry,p as INVALID_ENTITY,_ as INVALID_FONT,m as INVALID_TEXTURE,xe as Input,ve as InputPlugin,we as InputState,je as Interactable,$ as LocalTransform,yt as Material,Mt as MaterialLoader,re as Mut,G as Name,N as Parent,Kn as Physics,Xn as PhysicsEvents,qn as PhysicsPlugin,hn as PostProcess,ss as PreviewPlugin,ie as Query,ae as QueryInstance,Mn as RenderPipeline,fn as RenderStage,rs as RenderTexture,yn as Renderer,Z as Res,ee as ResMut,S as RigidBody,he as Schedule,Ze as ScreenSpace,Et as ShaderSources,Y as SpineAnimation,H as Sprite,ye as SystemRunner,Te as Text,Ce as TextAlign,rt as TextInput,ot as TextInputPlugin,Me as TextOverflow,Fe as TextPlugin,Ae as TextRenderer,Ee as TextVerticalAlign,se as Time,qe as UICameraInfo,Ye as UIEventQueue,Ge as UIEvents,Ne as UIInteraction,Ke as UIInteractionPlugin,nt as UILayoutPlugin,Be as UIMask,We as UIMaskPlugin,Re as UIRect,j as Velocity,ns as WebAssetProvider,Pe as World,D as WorldTransform,_e as addStartupSystem,me as addSystem,ge as addSystemToSchedule,Lt as assetPlugin,En as clearDrawCallbacks,I as clearUserComponents,x as color,et as computeUIRectLayout,He as createMaskProcessor,An as createWebApp,F as defineComponent,Q as defineResource,fe as defineSystem,U as defineTag,Ut as findEntityByName,Rn as flushPendingSystems,J as getComponentDefaults,t as getPlatform,s as getPlatformType,B as getUserComponent,Nt as initDrawAPI,xn as initGLDebugAPI,nn as initGeometryAPI,mt as initMaterialAPI,ln as initPostProcessAPI,_n as initRendererAPI,be as inputPlugin,Wn as instantiatePrefab,Ie as intersectRects,ze as invertMatrix4,L as isBuiltinComponent,as as isEditor,n as isPlatformInitialized,ls as isRuntime,ut as isTextureRef,r as isWeChat,o as isWeb,Rt as loadComponent,Nn as loadPhysicsModule,ts as loadRuntimeScene,Tt as loadSceneData,At as loadSceneWithAssets,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,$e as pointInWorldRect,v as quat,Pn as registerDrawCallback,$t as registerEmbeddedAssets,Ct as registerMaterialCallback,Le as screenToWorld,is as setEditorMode,Xt as shutdownDrawAPI,vn as shutdownGLDebugAPI,sn as shutdownGeometryAPI,_t as shutdownMaterialAPI,cn as shutdownPostProcessAPI,gn as shutdownRendererAPI,lt as textInputPlugin,Ue as textPlugin,Qe as uiInteractionPlugin,st as uiLayoutPlugin,Oe as uiMaskPlugin,Cn as unregisterDrawCallback,Ft as updateCameraAspectRatio,g as vec2,y as vec3,w as vec4,ke as worldRectToScreen};
//# sourceMappingURL=index.js.map
diff --git a/desktop/public/sdk/esm/physics/index.d.ts b/desktop/public/sdk/esm/physics/index.d.ts
index 283434ba6..c9f538421 100644
--- a/desktop/public/sdk/esm/physics/index.d.ts
+++ b/desktop/public/sdk/esm/physics/index.d.ts
@@ -25,6 +25,23 @@ interface Vec2 {
x: number;
y: number;
}
+interface Vec3 {
+ x: number;
+ y: number;
+ z: number;
+}
+interface Vec4 {
+ x: number;
+ y: number;
+ z: number;
+ w: number;
+}
+interface Quat {
+ w: number;
+ x: number;
+ y: number;
+ z: number;
+}
/**
* @file PhysicsComponents.ts
@@ -65,10 +82,10 @@ interface CapsuleColliderData {
restitution: number;
isSensor: boolean;
}
-declare const RigidBody: BuiltinComponentDef<RigidBodyData>;
-declare const BoxCollider: BuiltinComponentDef<BoxColliderData>;
-declare const CircleCollider: BuiltinComponentDef<CircleColliderData>;
-declare const CapsuleCollider: BuiltinComponentDef<CapsuleColliderData>;
+declare const RigidBody$1: BuiltinComponentDef<RigidBodyData>;
+declare const BoxCollider$1: BuiltinComponentDef<BoxColliderData>;
+declare const CircleCollider$1: BuiltinComponentDef<CircleColliderData>;
+declare const CapsuleCollider$1: BuiltinComponentDef<CapsuleColliderData>;
declare const BodyType: {
readonly Static: 0;
readonly Kinematic: 1;
@@ -96,75 +113,201 @@ interface BuiltinComponentDef<T> {
readonly _default: T;
}
type AnyComponentDef = ComponentDef<any> | BuiltinComponentDef<any>;
+type ComponentData<C> = C extends BuiltinComponentDef<infer T> ? T : C extends ComponentDef<infer T> ? T : never;
/**
- * @file wasm.ts
- * @brief WASM module type definitions
+ * @file wasm.generated.ts
+ * @brief ESEngine WASM Bindings TypeScript Definitions
+ * @details Generated by EHT - DO NOT EDIT
*/
-interface CppRegistry {
+interface UVec2 {
+ x: number;
+ y: number;
+}
+interface BoxCollider {
+ halfExtents: Vec2;
+ offset: Vec2;
+ density: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+}
+interface CircleCollider {
+ radius: number;
+ offset: Vec2;
+ density: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+}
+interface CapsuleCollider {
+ radius: number;
+ halfHeight: number;
+ offset: Vec2;
+ density: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+}
+interface LocalTransform {
+ position: Vec3;
+ rotation: Quat;
+ scale: Vec3;
+}
+interface WorldTransform {
+ position: Vec3;
+ rotation: Quat;
+ scale: Vec3;
+}
+interface Velocity {
+ linear: Vec3;
+ angular: Vec3;
+}
+interface SpineAnimation {
+ skeletonPath: string;
+ atlasPath: string;
+ skin: string;
+ animation: string;
+ timeScale: number;
+ loop: boolean;
+ playing: boolean;
+ flipX: boolean;
+ flipY: boolean;
+ color: Vec4;
+ layer: number;
+ skeletonScale: number;
+ material: number;
+}
+interface RigidBody {
+ bodyType: number;
+ gravityScale: number;
+ linearDamping: number;
+ angularDamping: number;
+ fixedRotation: boolean;
+ bullet: boolean;
+ enabled: boolean;
+}
+interface BitmapText {
+ text: string;
+ color: Vec4;
+ fontSize: number;
+ align: number;
+ spacing: number;
+ layer: number;
+ font: number;
+}
+interface Sprite {
+ texture: number;
+ color: Vec4;
+ size: Vec2;
+ uvOffset: Vec2;
+ uvScale: Vec2;
+ layer: number;
+ flipX: boolean;
+ flipY: boolean;
+ material: number;
+}
+interface Parent {
+ entity: number;
+}
+interface Children {
+}
+interface Canvas {
+ designResolution: UVec2;
+ pixelsPerUnit: number;
+ scaleMode: number;
+ matchWidthOrHeight: number;
+ backgroundColor: Vec4;
+}
+interface Camera {
+ projectionType: number;
+ fov: number;
+ orthoSize: number;
+ nearPlane: number;
+ farPlane: number;
+ aspectRatio: number;
+ isActive: boolean;
+ priority: number;
+ viewportX: number;
+ viewportY: number;
+ viewportW: number;
+ viewportH: number;
+ clearFlags: number;
+}
+interface Registry {
create(): Entity;
destroy(entity: Entity): void;
valid(entity: Entity): boolean;
- delete(): void;
- addLocalTransform(entity: Entity, data: unknown): void;
- getLocalTransform(entity: Entity): unknown;
+ entityCount(): number;
+ hasBoxCollider(entity: Entity): boolean;
+ getBoxCollider(entity: Entity): BoxCollider;
+ addBoxCollider(entity: Entity, component: BoxCollider): void;
+ removeBoxCollider(entity: Entity): void;
+ hasCircleCollider(entity: Entity): boolean;
+ getCircleCollider(entity: Entity): CircleCollider;
+ addCircleCollider(entity: Entity, component: CircleCollider): void;
+ removeCircleCollider(entity: Entity): void;
+ hasCapsuleCollider(entity: Entity): boolean;
+ getCapsuleCollider(entity: Entity): CapsuleCollider;
+ addCapsuleCollider(entity: Entity, component: CapsuleCollider): void;
+ removeCapsuleCollider(entity: Entity): void;
hasLocalTransform(entity: Entity): boolean;
+ getLocalTransform(entity: Entity): LocalTransform;
+ addLocalTransform(entity: Entity, component: LocalTransform): void;
removeLocalTransform(entity: Entity): void;
- addWorldTransform(entity: Entity, data: unknown): void;
- getWorldTransform(entity: Entity): unknown;
hasWorldTransform(entity: Entity): boolean;
+ getWorldTransform(entity: Entity): WorldTransform;
+ addWorldTransform(entity: Entity, component: WorldTransform): void;
removeWorldTransform(entity: Entity): void;
- addSprite(entity: Entity, data: unknown): void;
- getSprite(entity: Entity): unknown;
- hasSprite(entity: Entity): boolean;
- removeSprite(entity: Entity): void;
- addCamera(entity: Entity, data: unknown): void;
- getCamera(entity: Entity): unknown;
- hasCamera(entity: Entity): boolean;
- removeCamera(entity: Entity): void;
- addCanvas(entity: Entity, data: unknown): void;
- getCanvas(entity: Entity): unknown;
- hasCanvas(entity: Entity): boolean;
- removeCanvas(entity: Entity): void;
- addVelocity(entity: Entity, data: unknown): void;
- getVelocity(entity: Entity): unknown;
hasVelocity(entity: Entity): boolean;
+ getVelocity(entity: Entity): Velocity;
+ addVelocity(entity: Entity, component: Velocity): void;
removeVelocity(entity: Entity): void;
- addParent(entity: Entity, data: unknown): void;
- getParent(entity: Entity): unknown;
- hasParent(entity: Entity): boolean;
- removeParent(entity: Entity): void;
- addChildren(entity: Entity, data: unknown): void;
- getChildren(entity: Entity): unknown;
- hasChildren(entity: Entity): boolean;
- removeChildren(entity: Entity): void;
- addSpineAnimation(entity: Entity, data: unknown): void;
- getSpineAnimation(entity: Entity): unknown;
hasSpineAnimation(entity: Entity): boolean;
+ getSpineAnimation(entity: Entity): SpineAnimation;
+ addSpineAnimation(entity: Entity, component: SpineAnimation): void;
removeSpineAnimation(entity: Entity): void;
- addRigidBody?(entity: Entity, data: unknown): void;
- getRigidBody?(entity: Entity): unknown;
- hasRigidBody?(entity: Entity): boolean;
- removeRigidBody?(entity: Entity): void;
- addBoxCollider?(entity: Entity, data: unknown): void;
- getBoxCollider?(entity: Entity): unknown;
- hasBoxCollider?(entity: Entity): boolean;
- removeBoxCollider?(entity: Entity): void;
- addCircleCollider?(entity: Entity, data: unknown): void;
- getCircleCollider?(entity: Entity): unknown;
- hasCircleCollider?(entity: Entity): boolean;
- removeCircleCollider?(entity: Entity): void;
- addCapsuleCollider?(entity: Entity, data: unknown): void;
- getCapsuleCollider?(entity: Entity): unknown;
- hasCapsuleCollider?(entity: Entity): boolean;
- removeCapsuleCollider?(entity: Entity): void;
- addBitmapText(entity: Entity, data: unknown): void;
- getBitmapText(entity: Entity): unknown;
+ hasRigidBody(entity: Entity): boolean;
+ getRigidBody(entity: Entity): RigidBody;
+ addRigidBody(entity: Entity, component: RigidBody): void;
+ removeRigidBody(entity: Entity): void;
hasBitmapText(entity: Entity): boolean;
+ getBitmapText(entity: Entity): BitmapText;
+ addBitmapText(entity: Entity, component: BitmapText): void;
removeBitmapText(entity: Entity): void;
+ hasSprite(entity: Entity): boolean;
+ getSprite(entity: Entity): Sprite;
+ addSprite(entity: Entity, component: Sprite): void;
+ removeSprite(entity: Entity): void;
+ hasParent(entity: Entity): boolean;
+ getParent(entity: Entity): Parent;
+ addParent(entity: Entity, component: Parent): void;
+ removeParent(entity: Entity): void;
+ hasChildren(entity: Entity): boolean;
+ getChildren(entity: Entity): Children;
+ addChildren(entity: Entity, component: Children): void;
+ removeChildren(entity: Entity): void;
+ hasCanvas(entity: Entity): boolean;
+ getCanvas(entity: Entity): Canvas;
+ addCanvas(entity: Entity, component: Canvas): void;
+ removeCanvas(entity: Entity): void;
+ hasCamera(entity: Entity): boolean;
+ getCamera(entity: Entity): Camera;
+ addCamera(entity: Entity, component: Camera): void;
+ removeCamera(entity: Entity): void;
setParent(child: Entity, parent: Entity): void;
- [key: string]: any;
+}
+
+/**
+ * @file wasm.ts
+ * @brief WASM module type definitions
+ */
+
+interface CppRegistry extends Registry {
+ delete(): void;
+ removeParent(entity: Entity): void;
+ [key: string]: Function | undefined;
}
interface CppResourceManager {
createTexture(width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean): number;
@@ -323,8 +466,8 @@ declare class World {
getAllEntities(): Entity[];
setParent(child: Entity, parent: Entity): void;
removeParent(entity: Entity): void;
- insert(entity: Entity, component: AnyComponentDef, data?: unknown): unknown;
- get(entity: Entity, component: AnyComponentDef): unknown;
+ insert<C extends AnyComponentDef>(entity: Entity, component: C, data?: Partial<ComponentData<C>>): ComponentData<C>;
+ get<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C>;
has(entity: Entity, component: AnyComponentDef): boolean;
remove(entity: Entity, component: AnyComponentDef): void;
private insertBuiltin;
@@ -387,7 +530,7 @@ type SystemParam = QueryDescriptor<readonly QueryArg[]> | ResDescriptor<unknown>
interface SystemDef {
readonly _id: symbol;
readonly _params: readonly SystemParam[];
- readonly _fn: (...args: unknown[]) => void;
+ readonly _fn: (...args: never[]) => void;
readonly _name: string;
}
@@ -396,9 +539,44 @@ interface SystemDef {
* @brief Unified render pipeline for runtime and editor
*/
+interface RenderParams {
+ registry: {
+ _cpp: CppRegistry;
+ };
+ viewProjection: Float32Array;
+ width: number;
+ height: number;
+ elapsed: number;
+}
+interface CameraRenderParams {
+ registry: {
+ _cpp: CppRegistry;
+ };
+ viewProjection: Float32Array;
+ viewportPixels: {
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+ };
+ clearFlags: number;
+ elapsed: number;
+}
type SpineRendererFn = (registry: {
_cpp: CppRegistry;
}, elapsed: number) => void;
+type MaskProcessorFn = (registry: CppRegistry, vp: Float32Array, viewportX: number, viewportY: number, viewportW: number, viewportH: number) => void;
+declare class RenderPipeline {
+ private spineRenderer_;
+ private maskProcessor_;
+ private lastWidth_;
+ private lastHeight_;
+ setSpineRenderer(fn: SpineRendererFn | null): void;
+ setMaskProcessor(fn: MaskProcessorFn | null): void;
+ render(params: RenderParams): void;
+ renderCamera(params: CameraRenderParams): void;
+ private executeDrawCallbacks;
+}
/**
* @file app.ts
@@ -427,6 +605,7 @@ declare class App {
addStartupSystem(system: SystemDef): this;
connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this;
get wasmModule(): ESEngineModule | null;
+ get pipeline(): RenderPipeline | null;
setSpineRenderer(fn: SpineRendererFn | null): void;
get world(): World;
setFixedTimestep(timestep: number): this;
@@ -551,5 +730,5 @@ declare class Physics {
applyAngularImpulse(entity: Entity, impulse: number): void;
}
-export { BodyType, BoxCollider, CapsuleCollider, CircleCollider, Physics, PhysicsAPI, PhysicsEvents, PhysicsPlugin, RigidBody, loadPhysicsModule, loadPhysicsSideModule };
+export { BodyType, BoxCollider$1 as BoxCollider, CapsuleCollider$1 as CapsuleCollider, CircleCollider$1 as CircleCollider, Physics, PhysicsAPI, PhysicsEvents, PhysicsPlugin, RigidBody$1 as RigidBody, loadPhysicsModule, loadPhysicsSideModule };
export type { BoxColliderData, CapsuleColliderData, CircleColliderData, CollisionEnterEvent, ESEngineMainModule, PhysicsEventsData, PhysicsModuleFactory, PhysicsPluginConfig, PhysicsWasmModule, RigidBodyData, SensorEvent };
diff --git a/desktop/public/sdk/esm/spine/index.d.ts b/desktop/public/sdk/esm/spine/index.d.ts
index 97ccd3bda..ebd6311cf 100644
--- a/desktop/public/sdk/esm/spine/index.d.ts
+++ b/desktop/public/sdk/esm/spine/index.d.ts
@@ -25,6 +25,23 @@ interface Vec2 {
x: number;
y: number;
}
+interface Vec3 {
+ x: number;
+ y: number;
+ z: number;
+}
+interface Vec4 {
+ x: number;
+ y: number;
+ z: number;
+ w: number;
+}
+interface Quat {
+ w: number;
+ x: number;
+ y: number;
+ z: number;
+}
/**
* @file component.ts
@@ -46,75 +63,201 @@ interface BuiltinComponentDef<T> {
readonly _default: T;
}
type AnyComponentDef = ComponentDef<any> | BuiltinComponentDef<any>;
+type ComponentData<C> = C extends BuiltinComponentDef<infer T> ? T : C extends ComponentDef<infer T> ? T : never;
/**
- * @file wasm.ts
- * @brief WASM module type definitions
+ * @file wasm.generated.ts
+ * @brief ESEngine WASM Bindings TypeScript Definitions
+ * @details Generated by EHT - DO NOT EDIT
*/
-interface CppRegistry {
+interface UVec2 {
+ x: number;
+ y: number;
+}
+interface BoxCollider {
+ halfExtents: Vec2;
+ offset: Vec2;
+ density: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+}
+interface CircleCollider {
+ radius: number;
+ offset: Vec2;
+ density: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+}
+interface CapsuleCollider {
+ radius: number;
+ halfHeight: number;
+ offset: Vec2;
+ density: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+}
+interface LocalTransform {
+ position: Vec3;
+ rotation: Quat;
+ scale: Vec3;
+}
+interface WorldTransform {
+ position: Vec3;
+ rotation: Quat;
+ scale: Vec3;
+}
+interface Velocity {
+ linear: Vec3;
+ angular: Vec3;
+}
+interface SpineAnimation {
+ skeletonPath: string;
+ atlasPath: string;
+ skin: string;
+ animation: string;
+ timeScale: number;
+ loop: boolean;
+ playing: boolean;
+ flipX: boolean;
+ flipY: boolean;
+ color: Vec4;
+ layer: number;
+ skeletonScale: number;
+ material: number;
+}
+interface RigidBody {
+ bodyType: number;
+ gravityScale: number;
+ linearDamping: number;
+ angularDamping: number;
+ fixedRotation: boolean;
+ bullet: boolean;
+ enabled: boolean;
+}
+interface BitmapText {
+ text: string;
+ color: Vec4;
+ fontSize: number;
+ align: number;
+ spacing: number;
+ layer: number;
+ font: number;
+}
+interface Sprite {
+ texture: number;
+ color: Vec4;
+ size: Vec2;
+ uvOffset: Vec2;
+ uvScale: Vec2;
+ layer: number;
+ flipX: boolean;
+ flipY: boolean;
+ material: number;
+}
+interface Parent {
+ entity: number;
+}
+interface Children {
+}
+interface Canvas {
+ designResolution: UVec2;
+ pixelsPerUnit: number;
+ scaleMode: number;
+ matchWidthOrHeight: number;
+ backgroundColor: Vec4;
+}
+interface Camera {
+ projectionType: number;
+ fov: number;
+ orthoSize: number;
+ nearPlane: number;
+ farPlane: number;
+ aspectRatio: number;
+ isActive: boolean;
+ priority: number;
+ viewportX: number;
+ viewportY: number;
+ viewportW: number;
+ viewportH: number;
+ clearFlags: number;
+}
+interface Registry {
create(): Entity;
destroy(entity: Entity): void;
valid(entity: Entity): boolean;
- delete(): void;
- addLocalTransform(entity: Entity, data: unknown): void;
- getLocalTransform(entity: Entity): unknown;
+ entityCount(): number;
+ hasBoxCollider(entity: Entity): boolean;
+ getBoxCollider(entity: Entity): BoxCollider;
+ addBoxCollider(entity: Entity, component: BoxCollider): void;
+ removeBoxCollider(entity: Entity): void;
+ hasCircleCollider(entity: Entity): boolean;
+ getCircleCollider(entity: Entity): CircleCollider;
+ addCircleCollider(entity: Entity, component: CircleCollider): void;
+ removeCircleCollider(entity: Entity): void;
+ hasCapsuleCollider(entity: Entity): boolean;
+ getCapsuleCollider(entity: Entity): CapsuleCollider;
+ addCapsuleCollider(entity: Entity, component: CapsuleCollider): void;
+ removeCapsuleCollider(entity: Entity): void;
hasLocalTransform(entity: Entity): boolean;
+ getLocalTransform(entity: Entity): LocalTransform;
+ addLocalTransform(entity: Entity, component: LocalTransform): void;
removeLocalTransform(entity: Entity): void;
- addWorldTransform(entity: Entity, data: unknown): void;
- getWorldTransform(entity: Entity): unknown;
hasWorldTransform(entity: Entity): boolean;
+ getWorldTransform(entity: Entity): WorldTransform;
+ addWorldTransform(entity: Entity, component: WorldTransform): void;
removeWorldTransform(entity: Entity): void;
- addSprite(entity: Entity, data: unknown): void;
- getSprite(entity: Entity): unknown;
- hasSprite(entity: Entity): boolean;
- removeSprite(entity: Entity): void;
- addCamera(entity: Entity, data: unknown): void;
- getCamera(entity: Entity): unknown;
- hasCamera(entity: Entity): boolean;
- removeCamera(entity: Entity): void;
- addCanvas(entity: Entity, data: unknown): void;
- getCanvas(entity: Entity): unknown;
- hasCanvas(entity: Entity): boolean;
- removeCanvas(entity: Entity): void;
- addVelocity(entity: Entity, data: unknown): void;
- getVelocity(entity: Entity): unknown;
hasVelocity(entity: Entity): boolean;
+ getVelocity(entity: Entity): Velocity;
+ addVelocity(entity: Entity, component: Velocity): void;
removeVelocity(entity: Entity): void;
- addParent(entity: Entity, data: unknown): void;
- getParent(entity: Entity): unknown;
- hasParent(entity: Entity): boolean;
- removeParent(entity: Entity): void;
- addChildren(entity: Entity, data: unknown): void;
- getChildren(entity: Entity): unknown;
- hasChildren(entity: Entity): boolean;
- removeChildren(entity: Entity): void;
- addSpineAnimation(entity: Entity, data: unknown): void;
- getSpineAnimation(entity: Entity): unknown;
hasSpineAnimation(entity: Entity): boolean;
+ getSpineAnimation(entity: Entity): SpineAnimation;
+ addSpineAnimation(entity: Entity, component: SpineAnimation): void;
removeSpineAnimation(entity: Entity): void;
- addRigidBody?(entity: Entity, data: unknown): void;
- getRigidBody?(entity: Entity): unknown;
- hasRigidBody?(entity: Entity): boolean;
- removeRigidBody?(entity: Entity): void;
- addBoxCollider?(entity: Entity, data: unknown): void;
- getBoxCollider?(entity: Entity): unknown;
- hasBoxCollider?(entity: Entity): boolean;
- removeBoxCollider?(entity: Entity): void;
- addCircleCollider?(entity: Entity, data: unknown): void;
- getCircleCollider?(entity: Entity): unknown;
- hasCircleCollider?(entity: Entity): boolean;
- removeCircleCollider?(entity: Entity): void;
- addCapsuleCollider?(entity: Entity, data: unknown): void;
- getCapsuleCollider?(entity: Entity): unknown;
- hasCapsuleCollider?(entity: Entity): boolean;
- removeCapsuleCollider?(entity: Entity): void;
- addBitmapText(entity: Entity, data: unknown): void;
- getBitmapText(entity: Entity): unknown;
+ hasRigidBody(entity: Entity): boolean;
+ getRigidBody(entity: Entity): RigidBody;
+ addRigidBody(entity: Entity, component: RigidBody): void;
+ removeRigidBody(entity: Entity): void;
hasBitmapText(entity: Entity): boolean;
+ getBitmapText(entity: Entity): BitmapText;
+ addBitmapText(entity: Entity, component: BitmapText): void;
removeBitmapText(entity: Entity): void;
+ hasSprite(entity: Entity): boolean;
+ getSprite(entity: Entity): Sprite;
+ addSprite(entity: Entity, component: Sprite): void;
+ removeSprite(entity: Entity): void;
+ hasParent(entity: Entity): boolean;
+ getParent(entity: Entity): Parent;
+ addParent(entity: Entity, component: Parent): void;
+ removeParent(entity: Entity): void;
+ hasChildren(entity: Entity): boolean;
+ getChildren(entity: Entity): Children;
+ addChildren(entity: Entity, component: Children): void;
+ removeChildren(entity: Entity): void;
+ hasCanvas(entity: Entity): boolean;
+ getCanvas(entity: Entity): Canvas;
+ addCanvas(entity: Entity, component: Canvas): void;
+ removeCanvas(entity: Entity): void;
+ hasCamera(entity: Entity): boolean;
+ getCamera(entity: Entity): Camera;
+ addCamera(entity: Entity, component: Camera): void;
+ removeCamera(entity: Entity): void;
setParent(child: Entity, parent: Entity): void;
- [key: string]: any;
+}
+
+/**
+ * @file wasm.ts
+ * @brief WASM module type definitions
+ */
+
+interface CppRegistry extends Registry {
+ delete(): void;
+ removeParent(entity: Entity): void;
+ [key: string]: Function | undefined;
}
interface CppResourceManager {
createTexture(width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean): number;
@@ -273,8 +416,8 @@ declare class World {
getAllEntities(): Entity[];
setParent(child: Entity, parent: Entity): void;
removeParent(entity: Entity): void;
- insert(entity: Entity, component: AnyComponentDef, data?: unknown): unknown;
- get(entity: Entity, component: AnyComponentDef): unknown;
+ insert<C extends AnyComponentDef>(entity: Entity, component: C, data?: Partial<ComponentData<C>>): ComponentData<C>;
+ get<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C>;
has(entity: Entity, component: AnyComponentDef): boolean;
remove(entity: Entity, component: AnyComponentDef): void;
private insertBuiltin;
@@ -337,7 +480,7 @@ type SystemParam = QueryDescriptor<readonly QueryArg[]> | ResDescriptor<unknown>
interface SystemDef {
readonly _id: symbol;
readonly _params: readonly SystemParam[];
- readonly _fn: (...args: unknown[]) => void;
+ readonly _fn: (...args: never[]) => void;
readonly _name: string;
}
@@ -346,9 +489,44 @@ interface SystemDef {
* @brief Unified render pipeline for runtime and editor
*/
+interface RenderParams {
+ registry: {
+ _cpp: CppRegistry;
+ };
+ viewProjection: Float32Array;
+ width: number;
+ height: number;
+ elapsed: number;
+}
+interface CameraRenderParams {
+ registry: {
+ _cpp: CppRegistry;
+ };
+ viewProjection: Float32Array;
+ viewportPixels: {
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+ };
+ clearFlags: number;
+ elapsed: number;
+}
type SpineRendererFn = (registry: {
_cpp: CppRegistry;
}, elapsed: number) => void;
+type MaskProcessorFn = (registry: CppRegistry, vp: Float32Array, viewportX: number, viewportY: number, viewportW: number, viewportH: number) => void;
+declare class RenderPipeline {
+ private spineRenderer_;
+ private maskProcessor_;
+ private lastWidth_;
+ private lastHeight_;
+ setSpineRenderer(fn: SpineRendererFn | null): void;
+ setMaskProcessor(fn: MaskProcessorFn | null): void;
+ render(params: RenderParams): void;
+ renderCamera(params: CameraRenderParams): void;
+ private executeDrawCallbacks;
+}
/**
* @file app.ts
@@ -377,6 +555,7 @@ declare class App {
addStartupSystem(system: SystemDef): this;
connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this;
get wasmModule(): ESEngineModule | null;
+ get pipeline(): RenderPipeline | null;
setSpineRenderer(fn: SpineRendererFn | null): void;
get world(): World;
setFixedTimestep(timestep: number): this;
diff --git a/desktop/public/sdk/esm/wasm.d.ts b/desktop/public/sdk/esm/wasm.d.ts
index aa8f9f362..d1fbd9072 100644
--- a/desktop/public/sdk/esm/wasm.d.ts
+++ b/desktop/public/sdk/esm/wasm.d.ts
@@ -3,75 +3,221 @@
* @brief Core type definitions for ESEngine SDK
*/
type Entity = number;
+interface Vec2 {
+ x: number;
+ y: number;
+}
+interface Vec3 {
+ x: number;
+ y: number;
+ z: number;
+}
+interface Vec4 {
+ x: number;
+ y: number;
+ z: number;
+ w: number;
+}
+interface Quat {
+ w: number;
+ x: number;
+ y: number;
+ z: number;
+}
/**
- * @file wasm.ts
- * @brief WASM module type definitions
+ * @file wasm.generated.ts
+ * @brief ESEngine WASM Bindings TypeScript Definitions
+ * @details Generated by EHT - DO NOT EDIT
*/
-interface CppRegistry {
+interface UVec2 {
+ x: number;
+ y: number;
+}
+interface BoxCollider {
+ halfExtents: Vec2;
+ offset: Vec2;
+ density: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+}
+interface CircleCollider {
+ radius: number;
+ offset: Vec2;
+ density: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+}
+interface CapsuleCollider {
+ radius: number;
+ halfHeight: number;
+ offset: Vec2;
+ density: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+}
+interface LocalTransform {
+ position: Vec3;
+ rotation: Quat;
+ scale: Vec3;
+}
+interface WorldTransform {
+ position: Vec3;
+ rotation: Quat;
+ scale: Vec3;
+}
+interface Velocity {
+ linear: Vec3;
+ angular: Vec3;
+}
+interface SpineAnimation {
+ skeletonPath: string;
+ atlasPath: string;
+ skin: string;
+ animation: string;
+ timeScale: number;
+ loop: boolean;
+ playing: boolean;
+ flipX: boolean;
+ flipY: boolean;
+ color: Vec4;
+ layer: number;
+ skeletonScale: number;
+ material: number;
+}
+interface RigidBody {
+ bodyType: number;
+ gravityScale: number;
+ linearDamping: number;
+ angularDamping: number;
+ fixedRotation: boolean;
+ bullet: boolean;
+ enabled: boolean;
+}
+interface BitmapText {
+ text: string;
+ color: Vec4;
+ fontSize: number;
+ align: number;
+ spacing: number;
+ layer: number;
+ font: number;
+}
+interface Sprite {
+ texture: number;
+ color: Vec4;
+ size: Vec2;
+ uvOffset: Vec2;
+ uvScale: Vec2;
+ layer: number;
+ flipX: boolean;
+ flipY: boolean;
+ material: number;
+}
+interface Parent {
+ entity: number;
+}
+interface Children {
+}
+interface Canvas {
+ designResolution: UVec2;
+ pixelsPerUnit: number;
+ scaleMode: number;
+ matchWidthOrHeight: number;
+ backgroundColor: Vec4;
+}
+interface Camera {
+ projectionType: number;
+ fov: number;
+ orthoSize: number;
+ nearPlane: number;
+ farPlane: number;
+ aspectRatio: number;
+ isActive: boolean;
+ priority: number;
+ viewportX: number;
+ viewportY: number;
+ viewportW: number;
+ viewportH: number;
+ clearFlags: number;
+}
+interface Registry {
create(): Entity;
destroy(entity: Entity): void;
valid(entity: Entity): boolean;
- delete(): void;
- addLocalTransform(entity: Entity, data: unknown): void;
- getLocalTransform(entity: Entity): unknown;
+ entityCount(): number;
+ hasBoxCollider(entity: Entity): boolean;
+ getBoxCollider(entity: Entity): BoxCollider;
+ addBoxCollider(entity: Entity, component: BoxCollider): void;
+ removeBoxCollider(entity: Entity): void;
+ hasCircleCollider(entity: Entity): boolean;
+ getCircleCollider(entity: Entity): CircleCollider;
+ addCircleCollider(entity: Entity, component: CircleCollider): void;
+ removeCircleCollider(entity: Entity): void;
+ hasCapsuleCollider(entity: Entity): boolean;
+ getCapsuleCollider(entity: Entity): CapsuleCollider;
+ addCapsuleCollider(entity: Entity, component: CapsuleCollider): void;
+ removeCapsuleCollider(entity: Entity): void;
hasLocalTransform(entity: Entity): boolean;
+ getLocalTransform(entity: Entity): LocalTransform;
+ addLocalTransform(entity: Entity, component: LocalTransform): void;
removeLocalTransform(entity: Entity): void;
- addWorldTransform(entity: Entity, data: unknown): void;
- getWorldTransform(entity: Entity): unknown;
hasWorldTransform(entity: Entity): boolean;
+ getWorldTransform(entity: Entity): WorldTransform;
+ addWorldTransform(entity: Entity, component: WorldTransform): void;
removeWorldTransform(entity: Entity): void;
- addSprite(entity: Entity, data: unknown): void;
- getSprite(entity: Entity): unknown;
- hasSprite(entity: Entity): boolean;
- removeSprite(entity: Entity): void;
- addCamera(entity: Entity, data: unknown): void;
- getCamera(entity: Entity): unknown;
- hasCamera(entity: Entity): boolean;
- removeCamera(entity: Entity): void;
- addCanvas(entity: Entity, data: unknown): void;
- getCanvas(entity: Entity): unknown;
- hasCanvas(entity: Entity): boolean;
- removeCanvas(entity: Entity): void;
- addVelocity(entity: Entity, data: unknown): void;
- getVelocity(entity: Entity): unknown;
hasVelocity(entity: Entity): boolean;
+ getVelocity(entity: Entity): Velocity;
+ addVelocity(entity: Entity, component: Velocity): void;
removeVelocity(entity: Entity): void;
- addParent(entity: Entity, data: unknown): void;
- getParent(entity: Entity): unknown;
- hasParent(entity: Entity): boolean;
- removeParent(entity: Entity): void;
- addChildren(entity: Entity, data: unknown): void;
- getChildren(entity: Entity): unknown;
- hasChildren(entity: Entity): boolean;
- removeChildren(entity: Entity): void;
- addSpineAnimation(entity: Entity, data: unknown): void;
- getSpineAnimation(entity: Entity): unknown;
hasSpineAnimation(entity: Entity): boolean;
+ getSpineAnimation(entity: Entity): SpineAnimation;
+ addSpineAnimation(entity: Entity, component: SpineAnimation): void;
removeSpineAnimation(entity: Entity): void;
- addRigidBody?(entity: Entity, data: unknown): void;
- getRigidBody?(entity: Entity): unknown;
- hasRigidBody?(entity: Entity): boolean;
- removeRigidBody?(entity: Entity): void;
- addBoxCollider?(entity: Entity, data: unknown): void;
- getBoxCollider?(entity: Entity): unknown;
- hasBoxCollider?(entity: Entity): boolean;
- removeBoxCollider?(entity: Entity): void;
- addCircleCollider?(entity: Entity, data: unknown): void;
- getCircleCollider?(entity: Entity): unknown;
- hasCircleCollider?(entity: Entity): boolean;
- removeCircleCollider?(entity: Entity): void;
- addCapsuleCollider?(entity: Entity, data: unknown): void;
- getCapsuleCollider?(entity: Entity): unknown;
- hasCapsuleCollider?(entity: Entity): boolean;
- removeCapsuleCollider?(entity: Entity): void;
- addBitmapText(entity: Entity, data: unknown): void;
- getBitmapText(entity: Entity): unknown;
+ hasRigidBody(entity: Entity): boolean;
+ getRigidBody(entity: Entity): RigidBody;
+ addRigidBody(entity: Entity, component: RigidBody): void;
+ removeRigidBody(entity: Entity): void;
hasBitmapText(entity: Entity): boolean;
+ getBitmapText(entity: Entity): BitmapText;
+ addBitmapText(entity: Entity, component: BitmapText): void;
removeBitmapText(entity: Entity): void;
+ hasSprite(entity: Entity): boolean;
+ getSprite(entity: Entity): Sprite;
+ addSprite(entity: Entity, component: Sprite): void;
+ removeSprite(entity: Entity): void;
+ hasParent(entity: Entity): boolean;
+ getParent(entity: Entity): Parent;
+ addParent(entity: Entity, component: Parent): void;
+ removeParent(entity: Entity): void;
+ hasChildren(entity: Entity): boolean;
+ getChildren(entity: Entity): Children;
+ addChildren(entity: Entity, component: Children): void;
+ removeChildren(entity: Entity): void;
+ hasCanvas(entity: Entity): boolean;
+ getCanvas(entity: Entity): Canvas;
+ addCanvas(entity: Entity, component: Canvas): void;
+ removeCanvas(entity: Entity): void;
+ hasCamera(entity: Entity): boolean;
+ getCamera(entity: Entity): Camera;
+ addCamera(entity: Entity, component: Camera): void;
+ removeCamera(entity: Entity): void;
setParent(child: Entity, parent: Entity): void;
- [key: string]: any;
+}
+
+/**
+ * @file wasm.ts
+ * @brief WASM module type definitions
+ */
+
+interface CppRegistry extends Registry {
+ delete(): void;
+ removeParent(entity: Entity): void;
+ [key: string]: Function | undefined;
}
interface CppResourceManager {
createTexture(width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean): number;
diff --git a/sdk/src/app.ts b/sdk/src/app.ts
index 9fa8c15a0..02687e0ee 100644
--- a/sdk/src/app.ts
+++ b/sdk/src/app.ts
@@ -119,6 +119,10 @@ export class App {
return this.module_;
}
+ get pipeline(): RenderPipeline | null {
+ return this.pipeline_;
+ }
+
setSpineRenderer(fn: SpineRendererFn | null): void {
this.pipeline_?.setSpineRenderer(fn);
}
@@ -325,13 +329,12 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): A
_params: [],
_fn: () => {
const { width, height } = getViewportSize();
+ if (width === 0 || height === 0) return;
const canvasEntity = module.registry_getCanvasEntity(cppRegistry);
if (canvasEntity >= 0) {
- const canvas = cppRegistry.getCanvas(canvasEntity) as {
- backgroundColor: { r: number; g: number; b: number; a: number };
- };
+ const canvas = cppRegistry.getCanvas(canvasEntity);
const bg = canvas.backgroundColor;
- Renderer.setClearColor(bg.r, bg.g, bg.b, bg.a);
+ Renderer.setClearColor(bg.x, bg.y, bg.z, bg.w);
}
const elapsed = (platformNow() - startTime) / 1000;
@@ -406,20 +409,10 @@ const IDENTITY = new Float32Array([
0, 0, 0, 1,
]);
-function findCanvasData(module: ESEngineModule, registry: CppRegistry): {
- designResolution: { x: number; y: number };
- scaleMode: number;
- matchWidthOrHeight: number;
- backgroundColor: { r: number; g: number; b: number; a: number };
-} | null {
+function findCanvasData(module: ESEngineModule, registry: CppRegistry) {
const entity = module.registry_getCanvasEntity(registry);
if (entity < 0) return null;
- return registry.getCanvas(entity) as {
- designResolution: { x: number; y: number };
- scaleMode: number;
- matchWidthOrHeight: number;
- backgroundColor: { r: number; g: number; b: number; a: number };
- };
+ return registry.getCanvas(entity);
}
function computeEffectiveOrthoSize(
@@ -458,6 +451,7 @@ interface CameraInfo {
}
function collectCameras(module: ESEngineModule, registry: CppRegistry, width: number, height: number): CameraInfo[] {
+ if (width === 0 || height === 0) return [];
const cameraEntities = module.registry_getCameraEntities(registry);
if (cameraEntities.length === 0) return [];
@@ -465,24 +459,8 @@ function collectCameras(module: ESEngineModule, registry: CppRegistry, width: nu
const cameras: CameraInfo[] = [];
for (const e of cameraEntities) {
- const camera = registry.getCamera(e) as {
- projectionType: number;
- fov: number;
- orthoSize: number;
- nearPlane: number;
- farPlane: number;
- isActive: boolean;
- priority: number;
- viewportX: number;
- viewportY: number;
- viewportW: number;
- viewportH: number;
- clearFlags: number;
- };
-
- const transform = registry.getLocalTransform(e) as {
- position: { x: number; y: number; z: number };
- };
+ const camera = registry.getCamera(e);
+ const transform = registry.getLocalTransform(e);
const vr = {
x: camera.viewportX,
@@ -537,22 +515,13 @@ function collectCameras(module: ESEngineModule, registry: CppRegistry, width: nu
}
function computeViewProjection(module: ESEngineModule, registry: CppRegistry, width: number, height: number): Float32Array {
+ if (width === 0 || height === 0) return IDENTITY;
const cameraEntities = module.registry_getCameraEntities(registry);
if (cameraEntities.length === 0) return IDENTITY;
const e = cameraEntities[0];
- const camera = registry.getCamera(e) as {
- projectionType: number;
- fov: number;
- orthoSize: number;
- nearPlane: number;
- farPlane: number;
- isActive: boolean;
- };
-
- const transform = registry.getLocalTransform(e) as {
- position: { x: number; y: number; z: number };
- };
+ const camera = registry.getCamera(e);
+ const transform = registry.getLocalTransform(e);
const aspect = width / height;
let projection: Float32Array;
diff --git a/sdk/src/commands.ts b/sdk/src/commands.ts
index f70ab6b38..3dc364b4c 100644
--- a/sdk/src/commands.ts
+++ b/sdk/src/commands.ts
@@ -26,7 +26,7 @@ export function Commands(): CommandsDescriptor {
interface SpawnComponentEntry {
component: AnyComponentDef;
- data: unknown;
+ data: any;
}
interface SpawnCommand {
@@ -44,7 +44,7 @@ interface InsertCommand {
type: 'insert';
entity: Entity;
component: AnyComponentDef;
- data: unknown;
+ data: any;
}
interface RemoveCommand {
diff --git a/sdk/src/globals.d.ts b/sdk/src/globals.d.ts
index d0459ad64..e864549aa 100644
--- a/sdk/src/globals.d.ts
+++ b/sdk/src/globals.d.ts
@@ -1,6 +1,6 @@
interface Window {
__esengine_registerComponent?: (name: string, defaults: Record<string, unknown>, isTag: boolean) => void;
- __esengine_componentRegistry?: Map<string, unknown>;
+ __esengine_componentRegistry?: Map<string, import('./component').ComponentDef<Record<string, unknown>>>;
__esengine_spineEvent?: (entity: number, eventData: unknown) => void;
__esengine_pendingSystems?: Array<{ schedule: number; system: unknown }>;
__esengine_componentSourceMap?: Map<string, string>;
diff --git a/sdk/src/preview/WebAssetProvider.ts b/sdk/src/preview/WebAssetProvider.ts
index d31dd973e..45774cff6 100644
--- a/sdk/src/preview/WebAssetProvider.ts
+++ b/sdk/src/preview/WebAssetProvider.ts
@@ -18,6 +18,7 @@ export class WebAssetProvider implements RuntimeAssetProvider {
async prefetch(sceneData: SceneData): Promise<void> {
const textRefs = new Set<string>();
const binaryRefs = new Set<string>();
+ const bmfontRefs = new Set<string>();
for (const entity of sceneData.entities) {
for (const comp of entity.components) {
@@ -34,6 +35,10 @@ export class WebAssetProvider implements RuntimeAssetProvider {
}
if (atlasPath) textRefs.add(atlasPath);
}
+ if (comp.type === 'BitmapText' && typeof comp.data.font === 'string' && comp.data.font) {
+ bmfontRefs.add(comp.data.font);
+ textRefs.add(comp.data.font);
+ }
if (typeof comp.data.material === 'string' && comp.data.material) {
textRefs.add(comp.data.material);
}
@@ -61,6 +66,32 @@ export class WebAssetProvider implements RuntimeAssetProvider {
}
await Promise.all(fetches);
+
+ const fntFetches: Promise<void>[] = [];
+ for (const ref of bmfontRefs) {
+ if (!ref.endsWith('.bmfont')) continue;
+ const text = this.textCache_.get(ref);
+ if (!text) continue;
+ try {
+ const json = JSON.parse(text);
+ const fntFile = json.type === 'label-atlas' ? json.generatedFnt : json.fntFile;
+ if (fntFile) {
+ const dir = ref.substring(0, ref.lastIndexOf('/'));
+ const fntRef = dir ? `${dir}/${fntFile}` : fntFile;
+ if (!this.textCache_.has(fntRef)) {
+ fntFetches.push(
+ fetch(this.resolveUrl(fntRef))
+ .then(r => r.text())
+ .then(t => { this.textCache_.set(fntRef, t); })
+ .catch(() => {})
+ );
+ }
+ }
+ } catch { /* ignore parse errors */ }
+ }
+ if (fntFetches.length > 0) {
+ await Promise.all(fntFetches);
+ }
}
readText(ref: string): string {
diff --git a/sdk/src/query.ts b/sdk/src/query.ts
index c3af93db6..b4d682990 100644
--- a/sdk/src/query.ts
+++ b/sdk/src/query.ts
@@ -21,7 +21,7 @@ export function Mut<T extends AnyComponentDef>(component: T): MutWrapper<T> {
}
export function isMutWrapper(value: unknown): value is MutWrapper<AnyComponentDef> {
- return typeof value === 'object' && value !== null && (value as any)._type === 'mut';
+ return typeof value === 'object' && value !== null && '_type' in value && value._type === 'mut';
}
type UnwrapMut<T> = T extends MutWrapper<infer C> ? C : T;
@@ -89,7 +89,7 @@ export type QueryResult<C extends readonly QueryArg[]> = [
interface PendingMutation {
entity: Entity;
component: AnyComponentDef;
- data: unknown;
+ data: any;
}
export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<QueryResult<C>> {
@@ -117,7 +117,7 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu
const result = new Array(compCount + 1);
let prevEntity: Entity | null = null;
- let prevMutData: Array<{ component: AnyComponentDef; data: unknown }> = [];
+ let prevMutData: Array<{ component: AnyComponentDef; data: any }> = [];
try {
for (const entity of entities) {
diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.ts
index 5b6c56564..2a1e7f8bf 100644
--- a/sdk/src/runtimeLoader.ts
+++ b/sdk/src/runtimeLoader.ts
@@ -3,7 +3,7 @@
* @brief Runtime scene loader for builder targets (WeChat, Playable, etc.)
*/
-import { Sprite, SpineAnimation, WorldTransform, type SpineAnimationData, type WorldTransformData } from './component';
+import { Sprite, SpineAnimation, BitmapText, WorldTransform, type SpineAnimationData, type WorldTransformData } from './component';
import { Material } from './material';
import { loadSceneData, type SceneData } from './scene';
import type { ESEngineModule } from './wasm';
@@ -96,7 +96,7 @@ function updateSpriteTextures(
if (comp.type === 'Sprite' && comp.data.texture && typeof comp.data.texture === 'string') {
const sprite = world.get(entity, Sprite);
if (sprite) {
- (sprite as Record<string, unknown>).texture = textureCache[comp.data.texture as string] || 0;
+ sprite.texture = textureCache[comp.data.texture as string] || 0;
world.insert(entity, Sprite, sprite);
}
}
@@ -321,6 +321,79 @@ function setupSpineRenderer(
});
}
+// =============================================================================
+// BitmapFont Helpers
+// =============================================================================
+
+async function loadBitmapFonts(
+ module: ESEngineModule,
+ sceneData: SceneData,
+ provider: RuntimeAssetProvider,
+): Promise<Record<string, number>> {
+ const cache: Record<string, number> = {};
+ for (const entity of sceneData.entities) {
+ for (const comp of entity.components) {
+ if (comp.type !== 'BitmapText' || !comp.data.font || typeof comp.data.font !== 'string') continue;
+ const ref = comp.data.font as string;
+ if (cache[ref] !== undefined) continue;
+ try {
+ let fntContent: string;
+ let fntDir: string;
+
+ if (ref.endsWith('.bmfont')) {
+ const json = JSON.parse(provider.readText(ref));
+ const fntFile = json.type === 'label-atlas' ? json.generatedFnt : json.fntFile;
+ if (!fntFile) { cache[ref] = 0; continue; }
+ const dir = ref.substring(0, ref.lastIndexOf('/'));
+ const fntRef = dir ? `${dir}/${fntFile}` : fntFile;
+ fntContent = provider.readText(fntRef);
+ fntDir = fntRef.substring(0, fntRef.lastIndexOf('/'));
+ } else {
+ fntContent = provider.readText(ref);
+ fntDir = ref.substring(0, ref.lastIndexOf('/'));
+ }
+
+ const pageMatch = fntContent.match(/file="([^"]+)"/);
+ if (!pageMatch) { cache[ref] = 0; continue; }
+
+ const texRef = fntDir ? `${fntDir}/${pageMatch[1]}` : pageMatch[1];
+ const pixels = provider.loadPixelsRaw
+ ? await provider.loadPixelsRaw(texRef)
+ : await provider.loadPixels(texRef);
+ const texHandle = createTextureFromPixels(module, pixels, false);
+
+ const rm = module.getResourceManager();
+ cache[ref] = rm.loadBitmapFont(fntContent, texHandle, pixels.width, pixels.height);
+ } catch {
+ cache[ref] = 0;
+ }
+ }
+ }
+ return cache;
+}
+
+function updateBitmapTextFonts(
+ world: App['world'],
+ sceneData: SceneData,
+ fontCache: Record<string, number>,
+ entityMap: Map<number, number>,
+): void {
+ for (const entityData of sceneData.entities) {
+ const entity = entityMap.get(entityData.id);
+ if (entity === undefined) continue;
+ for (const comp of entityData.components) {
+ if (comp.type !== 'BitmapText' || !comp.data.font || typeof comp.data.font !== 'string') continue;
+ const handle = fontCache[comp.data.font as string] || 0;
+ if (!handle) continue;
+ const bt = world.get(entity, BitmapText);
+ if (bt) {
+ bt.font = handle;
+ world.insert(entity, BitmapText, bt);
+ }
+ }
+ }
+}
+
// =============================================================================
// Material Helpers
// =============================================================================
@@ -374,13 +447,13 @@ function updateMaterials(
if (comp.type === 'Sprite') {
const sprite = world.get(entity, Sprite);
if (sprite) {
- (sprite as Record<string, unknown>).material = handle;
+ sprite.material = handle;
world.insert(entity, Sprite, sprite);
}
} else if (comp.type === 'SpineAnimation') {
const spine = world.get(entity, SpineAnimation);
if (spine) {
- (spine as Record<string, unknown>).material = handle;
+ spine.material = handle;
world.insert(entity, SpineAnimation, spine);
}
}
@@ -421,10 +494,12 @@ export async function loadRuntimeScene(
physicsPlugin.build(app);
}
+ const fontCache = await loadBitmapFonts(module, sceneData, provider);
const materialCache = loadMaterials(sceneData, provider);
const entityMap = loadSceneData(app.world, sceneData);
updateSpriteTextures(app.world, sceneData, textureCache, entityMap);
+ updateBitmapTextFonts(app.world, sceneData, fontCache, entityMap);
updateMaterials(app.world, sceneData, materialCache, entityMap);
if (spineModule && spineAPI) {
diff --git a/sdk/src/scene.ts b/sdk/src/scene.ts
index bf8506558..5dd8c709a 100644
--- a/sdk/src/scene.ts
+++ b/sdk/src/scene.ts
@@ -229,59 +229,59 @@ export async function loadSceneWithAssets(
}
export function loadComponent(world: World, entity: Entity, compData: SceneComponentData): void {
- const data = compData.data as unknown;
+ const data = compData.data;
switch (compData.type) {
case 'LocalTransform':
- world.insert(entity, LocalTransform, data as LocalTransformData);
+ world.insert(entity, LocalTransform, data as Partial<LocalTransformData>);
break;
case 'Sprite':
- world.insert(entity, Sprite, data as SpriteData);
+ world.insert(entity, Sprite, data as Partial<SpriteData>);
break;
case 'Camera':
- world.insert(entity, Camera, data as CameraData);
+ world.insert(entity, Camera, data as Partial<CameraData>);
break;
case 'Canvas':
- world.insert(entity, Canvas, data as CanvasData);
+ world.insert(entity, Canvas, data as Partial<CanvasData>);
break;
case 'Text':
- world.insert(entity, Text, data as TextData);
+ world.insert(entity, Text, data as Partial<TextData>);
break;
case 'BitmapText':
- world.insert(entity, BitmapText, data as BitmapTextData);
+ world.insert(entity, BitmapText, data as Partial<BitmapTextData>);
break;
case 'SpineAnimation':
- world.insert(entity, SpineAnimation, data as SpineAnimationData);
+ world.insert(entity, SpineAnimation, data as Partial<SpineAnimationData>);
break;
case 'UIRect': {
- const rectData = data as Record<string, any>;
+ const rectData = data as Record<string, unknown>;
if (rectData.anchor && !rectData.anchorMin) {
- rectData.anchorMin = { ...rectData.anchor };
- rectData.anchorMax = { ...rectData.anchor };
+ rectData.anchorMin = { ...(rectData.anchor as Record<string, unknown>) };
+ rectData.anchorMax = { ...(rectData.anchor as Record<string, unknown>) };
delete rectData.anchor;
}
- world.insert(entity, UIRect, rectData as UIRectData);
+ world.insert(entity, UIRect, rectData as Partial<UIRectData>);
break;
}
case 'UIMask':
- world.insert(entity, UIMask, data as UIMaskData);
+ world.insert(entity, UIMask, data as Partial<UIMaskData>);
break;
case 'Interactable':
- world.insert(entity, Interactable, data as InteractableData);
+ world.insert(entity, Interactable, data as Partial<InteractableData>);
break;
case 'Button':
- world.insert(entity, Button, data as ButtonData);
+ world.insert(entity, Button, data as Partial<ButtonData>);
break;
case 'RigidBody':
- world.insert(entity, RigidBody, data as RigidBodyData);
+ world.insert(entity, RigidBody, data as Partial<RigidBodyData>);
break;
case 'BoxCollider':
- world.insert(entity, BoxCollider, data as BoxColliderData);
+ world.insert(entity, BoxCollider, data as Partial<BoxColliderData>);
break;
case 'CircleCollider':
- world.insert(entity, CircleCollider, data as CircleColliderData);
+ world.insert(entity, CircleCollider, data as Partial<CircleColliderData>);
break;
case 'CapsuleCollider':
- world.insert(entity, CapsuleCollider, data as CapsuleColliderData);
+ world.insert(entity, CapsuleCollider, data as Partial<CapsuleColliderData>);
break;
default: {
const userComp = getUserComponent(compData.type);
@@ -298,7 +298,7 @@ export function loadComponent(world: World, entity: Entity, compData: SceneCompo
export function updateCameraAspectRatio(world: World, aspectRatio: number): void {
const cameraEntities = world.getEntitiesWithComponents([Camera]);
for (const entity of cameraEntities) {
- const camera = world.get(entity, Camera) as CameraData;
+ const camera = world.get(entity, Camera);
if (camera) {
camera.aspectRatio = aspectRatio;
world.insert(entity, Camera, camera);
@@ -309,7 +309,7 @@ export function updateCameraAspectRatio(world: World, aspectRatio: number): void
export function findEntityByName(world: World, name: string): Entity | null {
const entities = world.getEntitiesWithComponents([Name]);
for (const entity of entities) {
- const data = world.get(entity, Name) as NameData;
+ const data = world.get(entity, Name);
if (data && data.value === name) {
return entity;
}
diff --git a/sdk/src/system.ts b/sdk/src/system.ts
index b52d963d4..a5cbc8bc9 100644
--- a/sdk/src/system.ts
+++ b/sdk/src/system.ts
@@ -59,7 +59,7 @@ export type InferParams<P extends readonly SystemParam[]> = {
export interface SystemDef {
readonly _id: symbol;
readonly _params: readonly SystemParam[];
- readonly _fn: (...args: unknown[]) => void;
+ readonly _fn: (...args: never[]) => void;
readonly _name: string;
}
@@ -75,7 +75,7 @@ export function defineSystem<P extends readonly SystemParam[]>(
return {
_id: Symbol(`System_${id}_${options?.name ?? ''}`),
_params: params,
- _fn: fn as (...args: unknown[]) => void,
+ _fn: fn as (...args: never[]) => void,
_name: options?.name ?? `System_${id}`
};
}
@@ -126,7 +126,7 @@ export class SystemRunner {
args[i] = this.resolveParam(system._params[i]);
}
- system._fn(...args);
+ (system._fn as (...args: unknown[]) => void)(...args);
for (let i = 0; i < args.length; i++) {
if (args[i] instanceof CommandsInstance) {
diff --git a/sdk/src/ui/UIMaskPlugin.ts b/sdk/src/ui/UIMaskPlugin.ts
index d7094b7d3..eb40a1b81 100644
--- a/sdk/src/ui/UIMaskPlugin.ts
+++ b/sdk/src/ui/UIMaskPlugin.ts
@@ -1,6 +1,6 @@
import type { App, Plugin } from '../app';
import type { ESEngineModule, CppRegistry } from '../wasm';
-import type { MaskProcessorFn, RenderPipeline } from '../renderPipeline';
+import type { MaskProcessorFn } from '../renderPipeline';
import type { Entity } from '../types';
import type { World } from '../world';
import { WorldTransform, Parent } from '../component';
@@ -109,7 +109,7 @@ function processMasks(
export class UIMaskPlugin implements Plugin {
build(app: App): void {
if (!app.wasmModule) return;
- const pipeline = (app as any).pipeline_ as RenderPipeline | null;
+ const pipeline = app.pipeline;
if (!pipeline) return;
pipeline.setMaskProcessor(createMaskProcessor(app.wasmModule, app.world));
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index ebb0c335f..9a907f1fe 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -4,90 +4,17 @@
*/
import { Entity } from './types';
+import type { Registry as GeneratedRegistry } from './wasm.generated';
// =============================================================================
// C++ Registry Interface
// =============================================================================
-export interface CppRegistry {
- create(): Entity;
- destroy(entity: Entity): void;
- valid(entity: Entity): boolean;
+export interface CppRegistry extends GeneratedRegistry {
delete(): void;
-
- addLocalTransform(entity: Entity, data: unknown): void;
- getLocalTransform(entity: Entity): unknown;
- hasLocalTransform(entity: Entity): boolean;
- removeLocalTransform(entity: Entity): void;
-
- addWorldTransform(entity: Entity, data: unknown): void;
- getWorldTransform(entity: Entity): unknown;
- hasWorldTransform(entity: Entity): boolean;
- removeWorldTransform(entity: Entity): void;
-
- addSprite(entity: Entity, data: unknown): void;
- getSprite(entity: Entity): unknown;
- hasSprite(entity: Entity): boolean;
- removeSprite(entity: Entity): void;
-
- addCamera(entity: Entity, data: unknown): void;
- getCamera(entity: Entity): unknown;
- hasCamera(entity: Entity): boolean;
- removeCamera(entity: Entity): void;
-
- addCanvas(entity: Entity, data: unknown): void;
- getCanvas(entity: Entity): unknown;
- hasCanvas(entity: Entity): boolean;
- removeCanvas(entity: Entity): void;
-
- addVelocity(entity: Entity, data: unknown): void;
- getVelocity(entity: Entity): unknown;
- hasVelocity(entity: Entity): boolean;
- removeVelocity(entity: Entity): void;
-
- addParent(entity: Entity, data: unknown): void;
- getParent(entity: Entity): unknown;
- hasParent(entity: Entity): boolean;
removeParent(entity: Entity): void;
- addChildren(entity: Entity, data: unknown): void;
- getChildren(entity: Entity): unknown;
- hasChildren(entity: Entity): boolean;
- removeChildren(entity: Entity): void;
-
- addSpineAnimation(entity: Entity, data: unknown): void;
- getSpineAnimation(entity: Entity): unknown;
- hasSpineAnimation(entity: Entity): boolean;
- removeSpineAnimation(entity: Entity): void;
-
- addRigidBody?(entity: Entity, data: unknown): void;
- getRigidBody?(entity: Entity): unknown;
- hasRigidBody?(entity: Entity): boolean;
- removeRigidBody?(entity: Entity): void;
-
- addBoxCollider?(entity: Entity, data: unknown): void;
- getBoxCollider?(entity: Entity): unknown;
- hasBoxCollider?(entity: Entity): boolean;
- removeBoxCollider?(entity: Entity): void;
-
- addCircleCollider?(entity: Entity, data: unknown): void;
- getCircleCollider?(entity: Entity): unknown;
- hasCircleCollider?(entity: Entity): boolean;
- removeCircleCollider?(entity: Entity): void;
-
- addCapsuleCollider?(entity: Entity, data: unknown): void;
- getCapsuleCollider?(entity: Entity): unknown;
- hasCapsuleCollider?(entity: Entity): boolean;
- removeCapsuleCollider?(entity: Entity): void;
-
- addBitmapText(entity: Entity, data: unknown): void;
- getBitmapText(entity: Entity): unknown;
- hasBitmapText(entity: Entity): boolean;
- removeBitmapText(entity: Entity): void;
-
- setParent(child: Entity, parent: Entity): void;
-
- [key: string]: any;
+ [key: string]: Function | undefined;
}
// =============================================================================
diff --git a/sdk/src/world.ts b/sdk/src/world.ts
index d2bfb7a1c..e4e281644 100644
--- a/sdk/src/world.ts
+++ b/sdk/src/world.ts
@@ -4,23 +4,23 @@
*/
import { Entity } from './types';
-import { AnyComponentDef, ComponentDef, BuiltinComponentDef, isBuiltinComponent } from './component';
+import { AnyComponentDef, ComponentDef, ComponentData, BuiltinComponentDef, isBuiltinComponent } from './component';
import type { CppRegistry } from './wasm';
-function convertForWasm(obj: unknown): unknown {
- if (obj === null || obj === undefined || typeof obj !== 'object' || Array.isArray(obj)) {
- return obj;
- }
- const rec = obj as Record<string, unknown>;
- if ('r' in rec && 'g' in rec && 'b' in rec && 'a' in rec && !('x' in rec)) {
- return { x: rec.r, y: rec.g, z: rec.b, w: rec.a };
- }
+function convertForWasm(obj: Record<string, unknown>): Record<string, unknown> {
const result: Record<string, unknown> = {};
- for (const key of Object.keys(rec)) {
- const val = rec[key];
- result[key] = (val !== null && val !== undefined && typeof val === 'object' && !Array.isArray(val))
- ? convertForWasm(val)
- : val;
+ for (const key of Object.keys(obj)) {
+ const val = obj[key];
+ if (val !== null && val !== undefined && typeof val === 'object' && !Array.isArray(val)) {
+ const rec = val as Record<string, unknown>;
+ if ('r' in rec && 'g' in rec && 'b' in rec && 'a' in rec && !('x' in rec)) {
+ result[key] = { x: rec.r, y: rec.g, z: rec.b, w: rec.a };
+ } else {
+ result[key] = convertForWasm(rec);
+ }
+ } else {
+ result[key] = val;
+ }
}
return result;
}
@@ -105,18 +105,18 @@ export class World {
// Component Management
// =========================================================================
- insert(entity: Entity, component: AnyComponentDef, data?: unknown): unknown {
+ insert<C extends AnyComponentDef>(entity: Entity, component: C, data?: Partial<ComponentData<C>>): ComponentData<C> {
if (isBuiltinComponent(component)) {
- return this.insertBuiltin(entity, component, data);
+ return this.insertBuiltin(entity, component, data) as ComponentData<C>;
}
- return this.insertScript(entity, component as ComponentDef<any>, data);
+ return this.insertScript(entity, component as ComponentDef<any>, data) as ComponentData<C>;
}
- get(entity: Entity, component: AnyComponentDef): unknown {
+ get<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C> {
if (isBuiltinComponent(component)) {
- return this.getBuiltin(entity, component);
+ return this.getBuiltin(entity, component) as ComponentData<C>;
}
- return this.getScript(entity, component as ComponentDef<any>);
+ return this.getScript(entity, component as ComponentDef<any>) as ComponentData<C>;
}
has(entity: Entity, component: AnyComponentDef): boolean {
@@ -138,13 +138,21 @@ export class World {
// Builtin Component Operations (C++ Registry)
// =========================================================================
- private insertBuiltin(entity: Entity, component: BuiltinComponentDef<any>, data?: unknown): unknown {
- const merged = { ...component._default, ...(data as object) };
+ private insertBuiltin<T>(entity: Entity, component: BuiltinComponentDef<T>, data?: Partial<T>): T {
+ const filtered: Record<string, unknown> = {};
+ if (data !== null && data !== undefined && typeof data === 'object') {
+ for (const [k, v] of Object.entries(data as Record<string, unknown>)) {
+ if (v !== undefined) {
+ filtered[k] = v;
+ }
+ }
+ }
+ const merged = { ...component._default, ...filtered } as T;
if (this.cppRegistry_) {
- const adder = `add${component._cppName}` as keyof CppRegistry;
- const fn = this.cppRegistry_[adder] as (e: Entity, d: unknown) => void;
- fn.call(this.cppRegistry_, entity, convertForWasm(merged));
+ const adder = `add${component._cppName}`;
+ const fn = this.cppRegistry_[adder] as ((e: Entity, d: unknown) => void) | undefined;
+ fn?.call(this.cppRegistry_, entity, convertForWasm(merged as Record<string, unknown>));
}
return merged;
@@ -155,9 +163,9 @@ export class World {
throw new Error('C++ Registry not connected');
}
- const getter = `get${component._cppName}` as keyof CppRegistry;
- const fn = this.cppRegistry_[getter] as (e: Entity) => T;
- return fn.call(this.cppRegistry_, entity);
+ const getter = `get${component._cppName}`;
+ const fn = this.cppRegistry_[getter] as ((e: Entity) => T) | undefined;
+ return fn!.call(this.cppRegistry_, entity);
}
private hasBuiltin(entity: Entity, component: BuiltinComponentDef<any>): boolean {
@@ -165,9 +173,9 @@ export class World {
return false;
}
- const checker = `has${component._cppName}` as keyof CppRegistry;
- const fn = this.cppRegistry_[checker] as (e: Entity) => boolean;
- return fn.call(this.cppRegistry_, entity);
+ const checker = `has${component._cppName}`;
+ const fn = this.cppRegistry_[checker] as ((e: Entity) => boolean) | undefined;
+ return fn!.call(this.cppRegistry_, entity);
}
private removeBuiltin(entity: Entity, component: BuiltinComponentDef<any>): void {
@@ -175,9 +183,9 @@ export class World {
return;
}
- const remover = `remove${component._cppName}` as keyof CppRegistry;
- const fn = this.cppRegistry_[remover] as (e: Entity) => void;
- fn.call(this.cppRegistry_, entity);
+ const remover = `remove${component._cppName}`;
+ const fn = this.cppRegistry_[remover] as ((e: Entity) => void) | undefined;
+ fn!.call(this.cppRegistry_, entity);
}
// =========================================================================