Skip to content

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

feat: add BitmapText editor support with font loading and inspector UI

esengine2d8e77e52e4b
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.js
index 5f96de960..ebd6b2803 100644
--- a/desktop/public/sdk/cjs/esengine.wechat.js
+++ b/desktop/public/sdk/cjs/esengine.wechat.js
@@ -1,2 +1,2 @@
-"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function r(e,r){return t().fetch(e,r)}async function s(e){return t().readFile(e)}async function n(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,r){return t().createCanvas(e,r)}function a(){return t().now()}function l(e,t){return new Promise((r,s)=>{const n=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===n?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];r({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,r="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(r).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function c(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const r=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(r,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${r}": ${t}`)}}let u=null;function h(){return u||(u=wx.getFileSystemManager()),u}function d(e){return new Promise((t,r)=>{h().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function p(e,t="utf-8"){return new Promise((r,s)=>{h().readFile({filePath:e,encoding:t,success:e=>{r(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function f(e){return new Promise(t=>{h().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}let m=null,_=null;function g(e){return new Promise((t,r)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>r(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function x(e){const{width:t,height:r}=e,{ctx:s}=function(e,t){return m||(m=wx.createCanvas(),m.width=e,m.height=t,_=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:_}}(t,r);s.clearRect(0,0,t,r),s.drawImage(e,0,0);const n=s.getImageData(0,0,t,r);return{width:t,height:r,pixels:new Uint8Array(n.data.buffer)}}let y=!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 r=wx.createCanvas();return r.width=e,r.height=t,r}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{const r=t.touches[0];r&&e.onPointerDown(0,r.clientX,r.clientY)}),wx.onTouchMove(t=>{const r=t.touches[0];r&&e.onPointerMove(r.clientX,r.clientY)}),wx.onTouchEnd(()=>{e.onPointerUp(0)})}},v=4294967295;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}),T=b("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 M(e,t){const r=++E;return{_id:Symbol(`Component_${r}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function R(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function U(e,t){const r=R(),s=r.get(e);if(s)return s;const n=M(e,t);return r.set(e,n),B(e,t,!1),n}function F(e){return R().get(e)}function B(e,t,r){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,r)}function I(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function D(e){return!0===e._builtin}const W=I("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),k=I("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),z=I("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}),$=I("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}),L=I("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),H=I("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),O=I("Parent",{entity:0}),N=I("Children",{entities:[]}),V=I("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),j={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},G={LocalTransform:W,WorldTransform:k,Sprite:z,Camera:$,Canvas:L,Velocity:H,Parent:O,Children:N,SpineAnimation:V,RigidBody:S,BoxCollider:P,CircleCollider:C,CapsuleCollider:T};let X=0;function Y(e,t){const r=++X;return{_id:Symbol(`Resource_${r}_${t??""}`),_name:t??`Resource_${r}`,_default:e}}function q(e){return{_type:"res",_resource:e}}class K{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 J{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 K(this.get(e),t=>this.set(e,t))}}const Q=Y({delta:0,elapsed:0,frameCount:0},"Time");function Z(e){return"object"==typeof e&&null!==e&&"mut"===e._type}class ee{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return Z(e)?e._component:e}commitPending(){for(const e of this.pendingMutations_)this.world_.insert(e.entity,e.component,e.data);this.pendingMutations_=[]}*[Symbol.iterator](){const{_components:e,_mutIndices:t,_with:r,_without:s}=this.descriptor_,n=e.map(e=>this.getActualComponent(e)),o=[...n,...r],i=this.world_.getEntitiesWithComponents(o);let a=null,l=[];try{for(const e of i){if(null!==a)for(const e of l)this.world_.insert(a,e.component,e.data);l=[];let r=!1;for(const t of s)if(this.world_.has(e,t)){r=!0;break}if(r)continue;const o=n.map(t=>this.world_.get(e,t));for(const e of t)l.push({component:n[e],data:o[e]});a=e,yield[e,...o]}}finally{if(null!==a)for(const e of l)this.world_.insert(a,e.component,e.data)}}forEach(e){for(const[t,...r]of this)e(t,...r)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){return[...this]}}class te{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let r;return r=D(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:r}):this.commands_.queueInsert(this.entityRef_.entity,e,r),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class re{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new te(this,null);return this.spawned_.push(e),e}entity(e){return new te(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,r){this.pending_.push({type:"insert",entity:e,component:t,data:r})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const r=this.world_.spawn();t.entity=r;for(const t of e)this.world_.insert(r,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const r of e.components)this.world_.insert(t,r.component,r.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var se;exports.Schedule=void 0,(se=exports.Schedule||(exports.Schedule={}))[se.Startup=0]="Startup",se[se.First=1]="First",se[se.PreUpdate=2]="PreUpdate",se[se.Update=3]="Update",se[se.PostUpdate=4]="PostUpdate",se[se.Last=5]="Last",se[se.FixedPreUpdate=10]="FixedPreUpdate",se[se.FixedUpdate=11]="FixedUpdate",se[se.FixedPostUpdate=12]="FixedPostUpdate";let ne=0;function oe(e,t,r){const s=++ne;return{_id:Symbol(`System_${s}_${r?.name??""}`),_params:e,_fn:t,_name:r?.name??`System_${s}`}}function ie(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class ae{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let r=0;r<e._params.length;r++)t[r]=this.resolveParam(e._params[r]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof re&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new ee(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new re(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class le{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 ce=Y(new le,"Input");class ue{constructor(e){this.target_=e??null}build(e){const r=new le;e.insertResource(ce,r),t().bindInputEvents({onKeyDown(e){r.keysDown.has(e)||r.keysPressed.add(e),r.keysDown.add(e)},onKeyUp(e){r.keysDown.delete(e),r.keysReleased.add(e)},onPointerMove(e,t){r.mouseX=e,r.mouseY=t},onPointerDown(e,t,s){r.mouseX=t,r.mouseY=s,r.mouseButtons.add(e),r.mouseButtonsPressed.add(e)},onPointerUp(e){r.mouseButtons.delete(e),r.mouseButtonsReleased.add(e)},onWheel(e,t){r.scrollDeltaX+=e,r.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.First,oe([],()=>{r.keysPressed.clear(),r.keysReleased.clear(),r.mouseButtonsPressed.clear(),r.mouseButtonsReleased.clear(),r.scrollDeltaX=0,r.scrollDeltaY=0},{name:"InputClearSystem"}))}}const he=new ue;function de(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 r={};for(const e of Object.keys(t)){const s=t[e];r[e]=null==s||"object"!=typeof s||Array.isArray(s)?s:de(s)}return r}class pe{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,r){return D(t)?this.insertBuiltin(e,t,r):this.insertScript(e,t,r)}get(e,t){return D(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return D(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){D(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,r){const s={...t._default,...r};if(this.cppRegistry_){const r=`add${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e,de(s))}return s}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const r=`get${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const r=`has${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const r=`remove${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e)}insertScript(e,t,r){const s=t.create(r);return this.getStorage(t).set(e,s),s}getScript(e,t){const r=this.tsStorage_.get(t._id);if(!r)throw new Error(`Component not found: ${t._name}`);return r.get(e)}hasScript(e,t){const r=this.tsStorage_.get(t._id);return r?.has(e)??!1}removeScript(e,t){const r=this.tsStorage_.get(t._id);r?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=[];for(const r of this.entities_){let s=!0;for(const t of e)if(!this.has(r,t)){s=!1;break}s&&t.push(r)}return t}}var fe,me,_e;exports.TextAlign=void 0,(fe=exports.TextAlign||(exports.TextAlign={}))[fe.Left=0]="Left",fe[fe.Center=1]="Center",fe[fe.Right=2]="Right",exports.TextVerticalAlign=void 0,(me=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[me.Top=0]="Top",me[me.Middle=1]="Middle",me[me.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 ge=U("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2,dirty:!0});class xe{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const r=this.ctx,s=this.canvas;r.font=`${e.fontSize}px ${e.fontFamily}`;const n=t&&t.size.x>0&&t.size.y>0,o=n?t.size.x:0,i=n?t.size.y:0,a=e.wordWrap&&n;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),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(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),_=Math.round(255*e.color.g),g=Math.round(255*e.color.b),x=e.color.a;r.clearRect(0,0,s.width,s.height),r.font=`${e.fontSize}px ${e.fontFamily}`,r.textAlign=this.mapAlign(e.align),r.textBaseline="top",r.fillStyle=`rgba(${m}, ${_}, ${g}, ${x})`,n&&e.overflow===exports.TextOverflow.Clip&&(r.save(),r.beginPath(),r.rect(0,0,p,f),r.clip());const y=l.length*c;let w;if(n)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-y)/2;break;case exports.TextVerticalAlign.Bottom:w=f-y-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}r.fillText(t,s,v),v+=c}n&&e.overflow===exports.TextOverflow.Clip&&r.restore();const b=r.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 r=e;for(;r.length>0&&this.ctx.measureText(r+"...").width>t;)r=r.slice(0,-1);return r+"..."}renderForEntity(e,t,r){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const n=this.renderText(t,r);return this.cache.set(e,n),n}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const r=e.split("\n"),s=[];for(const e of r){if(!e){s.push("");continue}let r="";for(const n of e){const e=r+n;this.ctx.measureText(e).width>t&&r?(s.push(r),r=n):r=e}r&&s.push(r)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const r of e){const e=this.ctx.measureText(r),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const ye=U("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class we{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const r=new xe(t),s=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,oe([],()=>{const e=s.getEntitiesWithComponents([ge]);for(const t of e){const e=s.get(t,ge);if(!e.dirty)continue;s.has(t,z)||s.insert(t,z,{texture:v,size:{x:0,y:0},color:{r:1,g:1,b:1,a:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const n=s.has(t,ye)?s.get(t,ye):null,o=r.renderForEntity(t,e,n),i=s.get(t,z);i.texture=o.textureHandle,i.size={x:o.width,y:o.height},i.uvOffset={x:0,y:0},i.uvScale={x:1,y:1},s.insert(t,z,i),e.dirty=!1}}))}}const ve=new we;var be;function Se(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(be=exports.BlendMode||(exports.BlendMode={}))[be.Normal=0]="Normal",be[be.Additive=1]="Additive",be[be.Multiply=2]="Multiply",be[be.Screen=3]="Screen",be[be.PremultipliedAlpha=4]="PremultipliedAlpha";let Pe=null,Ce=null,Te=1;const Ae=new Map;function Ee(e){Pe=e,Ce=e.getResourceManager(),ze()}function Me(){0!==Be&&Pe&&(Pe._free(Be),Be=0),Ae.clear(),Te=1,Fe=!1,Ce=null,Pe=null}function Re(){if(!Ce)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ce}const Ue={createShader:(e,t)=>Re().createShader(e,t),releaseShader(e){e>0&&Re().releaseShader(e)},create(e){const t=Te++,r={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))r.uniforms.set(t,s);return Ae.set(t,r),t},get:e=>Ae.get(e),setUniform(e,t,r){const s=Ae.get(e);s&&s.uniforms.set(t,r)},getUniform(e,t){const r=Ae.get(e);return r?.uniforms.get(t)},setBlendMode(e,t){const r=Ae.get(e);r&&(r.blendMode=t)},getBlendMode(e){const t=Ae.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const r=Ae.get(e);r&&(r.depthTest=t)},getShader(e){const t=Ae.get(e);return t?.shader??0},release(e){Ae.delete(e)},isValid:e=>Ae.has(e),createFromAsset(e,t){const r={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)r[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?r[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(r[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:r,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ae.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const r=Te++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Ae.set(r,s),r},toAssetData(e,t){const r=Ae.get(e);if(!r)return null;const s={};for(const[e,t]of r.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:r.blendMode,depthTest:r.depthTest,properties:s}},getUniforms(e){const t=Ae.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Fe=!1,Be=0;const Ie=4096,De=new Map,We=new TextEncoder;function ke(e){const t=(0===Be&&Pe&&(Be=Pe._malloc(Ie)),Be);if(0===t||!Pe)return{ptr:0,count:0};let r=0,s=0;const n=Pe.HEAPU8,o=Pe.HEAPU32,i=Pe.HEAPF32;for(const[a,l]of e){if(r+128>Ie)break;let e=De.get(a);e||(e=We.encode(a),De.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+r>>2]=c,r+=4,n.set(e,t+r),r+=u;let 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+r>>2]=h,r+=4;for(let e=0;e<4;e++)i[t+r>>2]=d[e],r+=4;s++}return{ptr:t,count:s}}function ze(){if(!Pe||Fe)return;Pe.materialDataProvider=(e,t,r,s,n)=>{const o=Ae.get(e);if(!o)return Pe.HEAPU32[t>>2]=0,Pe.HEAPU32[r>>2]=0,Pe.HEAPU32[s>>2]=0,void(Pe.HEAPU32[n>>2]=0);Pe.HEAPU32[t>>2]=o.shader,Pe.HEAPU32[r>>2]=o.blendMode;const{ptr:i,count:a}=ke(o.uniforms);Pe.HEAPU32[s>>2]=i,Pe.HEAPU32[n>>2]=a},Fe=!0}const $e={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 Le{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const r=this.pending_.get(e);if(r)return r;const s=this.loadInternal(e);this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ue.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ue.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await o(t))throw new Error(`Material file not found: ${t}`);const r=await n(t);if(!r)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(r);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),a=await this.shaderLoader_.load(i);return{handle:Ue.createFromAsset(s,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const r=e.substring(0,e.lastIndexOf("/"));return r?`${r}/${t}`:t}}function He(e,t){const r=new Map;for(const s of t.entities){const t=e.spawn();r.set(s.id,t),e.insert(t,j,{value:s.name});for(const r of s.components)Ne(e,t,r)}for(const s of t.entities)if(null!==s.parent){const t=r.get(s.id),n=r.get(s.parent);void 0!==t&&void 0!==n&&e.setParent(t,n)}return r}async function Oe(e,t,r){const s=new Map,n=r?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();s.set(i.id,t),e.insert(t,j,{value:i.name});for(const s of i.components){if("Sprite"===s.type&&n){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:r?.assetBaseUrl?`${r.assetBaseUrl}/${t}`:`/${t}`;try{const r=await n.loadTexture(s);e.texture=r.handle,o.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("SpineAnimation"===s.type&&n){const e=s.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await n.loadSpine(t,o,r?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Ne(e,t,s)}}for(const r of t.entities)if(null!==r.parent){const t=s.get(r.id),n=s.get(r.parent);void 0!==t&&void 0!==n&&e.setParent(t,n)}if(n&&t.textureMetadata)for(const[e,r]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&r.sliceBorder&&n.setTextureMetadataByPath(t,r.sliceBorder)}return s}function Ne(e,t,r){const s=r.data;switch(r.type){case"LocalTransform":e.insert(t,W,s);break;case"Sprite":e.insert(t,z,s);break;case"Camera":e.insert(t,$,s);break;case"Canvas":e.insert(t,L,s);break;case"Text":e.insert(t,ge,s);break;case"SpineAnimation":e.insert(t,V,s);break;case"UIRect":e.insert(t,ye,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,T,s);break;default:{const n=F(r.type);n?e.insert(t,n,s):console.warn(`Unknown component type: ${r.type}`);break}}}class Ve{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const r=this.cache_.get(e);if(void 0!==r)return r;const s=this.pending_.get(e);if(s)return s;const n=t();this.pending_.set(e,n);try{const t=await n;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class je{constructor(e){this.textureCache_=new Ve,this.shaderCache_=new Ve,this.jsonCache_=new Ve,this.textCache_=new Ve,this.binaryCache_=new Ve,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.embedded_=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 Le(t)}registerEmbeddedAssets(e){for(const[t,r]of Object.entries(e))this.embedded_.set(t,r)}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const r of[!0,!1]){const s=this.textureCacheKey(e,r),n=this.textureCache_.get(s);n&&(t.releaseTexture(n.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);this.textureCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear()}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const r=this.textureCache_.get(this.textureCacheKey(e,!0));return!!r&&(this.setTextureMetadata(r.handle,t),!0)}async loadSpine(e,t,r){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const n=this.resolveUrl(t,r),o=await this.fetchText(n);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o);for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,r);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,r),c=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);return this.writeToVirtualFS(e,c)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(r):this.jsonCache_.getOrLoad(r,()=>this.fetchJson(r))}async loadText(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(r):this.textCache_.getOrLoad(r,()=>this.fetchText(r))}async loadBinary(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(r):this.binaryCache_.getOrLoad(r,()=>this.fetchBinary(r))}async loadScene(e,t){return Oe(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},r=[];if(e.textures)for(const s of e.textures)r.push(this.loadTexture(s).then(e=>{t.textures.set(s,e)}));if(e.materials)for(const s of e.materials)r.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}`;r.push(this.loadSpine(s.skeleton,s.atlas,s.baseUrl).then(r=>{t.spine.set(e,r)}))}if(e.json)for(const s of e.json)r.push(this.loadJson(s).then(e=>{t.json.set(s,e)}));if(e.text)for(const s of e.text)r.push(this.loadText(s).then(e=>{t.text.set(s,e)}));if(e.binary)for(const s of e.binary)r.push(this.loadBinary(s).then(e=>{t.binary.set(s,e)}));return await Promise.all(r),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const r=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(r,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const r=await this.loadImage(e);return this.createTextureFromImage(r,t)}async loadImage(e){const r=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(r)??r;return new Promise((r,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 r(e)}catch{}r(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=s})}createTextureFromImage(e,t){const{width:r,height:s}=e,n=this.getWebGL2Context();return n?this.createTextureWebGL2(n,e,r,s,t):this.createTextureFallback(e,r,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,r,s,n){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,n?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,r,s),width:r,height:s}}createTextureFallback(e,t,r,s){(this.canvas_.width<t||this.canvas_.height<r)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(r))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const n=this.ctx_.getImageData(0,0,t,r),o=new Uint8Array(n.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,r,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:r}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const r=e[t+3];if(r>0&&r<255){const s=255/r;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e;if(!await o(t))throw new Error(`Shader file not found: ${e}`);const r=await n(t);if(!r)throw new Error(`Failed to read shader file: ${e}`);const{vertex:s,fragment:i}=this.parseEsShader(r);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return Ue.createShader(s,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),r=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:r?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const r=await n(t);return JSON.parse(r)}const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):n(t)}const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):s(t)}const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const r=this.module_.FS;if(!r)return!1;try{return this.ensureVirtualDir(e),r.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const r=e.substring(0,e.lastIndexOf("/"));if(!r)return;const s=r.split("/").filter(e=>e);let n="";for(const e of s){n=n?`${n}/${e}`:e;try{t.analyzePath(n).exists||t.mkdir(n)}catch{try{t.mkdir(n)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const r=t??this.baseUrl;return r?`${r}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Ge=Y(null,"Assets");class Xe{build(e){const t=e.wasmModule;t?e.insertResource(Ge,new je(t)):console.warn("AssetPlugin: No WASM module available")}}const Ye=new Xe;let qe=null,Ke=0,Je=0,Qe=0;const Ze=new Float32Array(256);function et(e){qe=e,Ke=qe._malloc(64),Je=qe._malloc(64),Qe=qe._malloc(1024)}function tt(){qe&&(Ke&&(qe._free(Ke),Ke=0),Je&&(qe._free(Je),Je=0),Qe&&(qe._free(Qe),Qe=0)),qe=null}function rt(){if(!qe)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return qe}const st={r:1,g:1,b:1,a:1},nt={begin(e){const t=rt();t.HEAPF32.set(e,Ke/4),t.draw_begin(Ke)},end(){rt().draw_end()},line(e,t,r,s=1){rt().draw_line(e.x,e.y,t.x,t.y,r.r,r.g,r.b,r.a,s)},rect(e,t,r,s=!0){rt().draw_rect(e.x,e.y,t.x,t.y,r.r,r.g,r.b,r.a,s)},rectOutline(e,t,r,s=1){rt().draw_rectOutline(e.x,e.y,t.x,t.y,r.r,r.g,r.b,r.a,s)},circle(e,t,r,s=!0,n=32){rt().draw_circle(e.x,e.y,t,r.r,r.g,r.b,r.a,s,n)},circleOutline(e,t,r,s=1,n=32){rt().draw_circleOutline(e.x,e.y,t,r.r,r.g,r.b,r.a,s,n)},texture(e,t,r,s=st){rt().draw_texture(e.x,e.y,t.x,t.y,r,s.r,s.g,s.b,s.a)},textureRotated(e,t,r,s,n=st){rt().draw_textureRotated(e.x,e.y,t.x,t.y,r,s,n.r,n.g,n.b,n.a)},setLayer(e){rt().draw_setLayer(e)},setDepth(e){rt().draw_setDepth(e)},getDrawCallCount:()=>qe?qe.draw_getDrawCallCount():0,getPrimitiveCount:()=>qe?qe.draw_getPrimitiveCount():0,setBlendMode(e){rt().draw_setBlendMode(e)},setDepthTest(e){rt().draw_setDepthTest(e)},drawMesh(e,t,r){const s=rt();s.HEAPF32.set(r,Je/4),s.draw_mesh(e,t,Je)},drawMeshWithMaterial(e,t,r){const s=rt(),n=Ue.get(t);if(!n)return;if(nt.setBlendMode(n.blendMode),nt.setDepthTest(n.depthTest),0===n.uniforms.size)return void nt.drawMesh(e,n.shader,r);s.HEAPF32.set(r,Je/4);let o=0,i=0;for(const[e,t]of n.uniforms){const r=it(e);if(!(r<0)){if(Se(t))Ze[o++]=10,Ze[o++]=r,Ze[o++]=t.slot??i++,Ze[o++]=t.textureId;else if("number"==typeof t)Ze[o++]=1,Ze[o++]=r,Ze[o++]=t;else if(Array.isArray(t)){Ze[o++]=t.length,Ze[o++]=r;for(let e=0;e<t.length;e++)Ze[o++]=t[e]}else"w"in t?(Ze[o++]=4,Ze[o++]=r,Ze[o++]=t.x,Ze[o++]=t.y,Ze[o++]=t.z,Ze[o++]=t.w):"z"in t?(Ze[o++]=3,Ze[o++]=r,Ze[o++]=t.x,Ze[o++]=t.y,Ze[o++]=t.z):(Ze[o++]=2,Ze[o++]=r,Ze[o++]=t.x,Ze[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(Ze.subarray(0,o),Qe/4),s.draw_meshWithUniforms(e,n.shader,Je,Qe,o)):s.draw_mesh(e,n.shader,Je)}},ot={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 it(e){return ot[e]??-1}var at;exports.DataType=void 0,(at=exports.DataType||(exports.DataType={}))[at.Float=1]="Float",at[at.Float2=2]="Float2",at[at.Float3=3]="Float3",at[at.Float4=4]="Float4",at[at.Int=5]="Int",at[at.Int2=6]="Int2",at[at.Int3=7]="Int3",at[at.Int4=8]="Int4";let lt=null,ct=0,ut=0,ht=0;function dt(e){lt=e,ct=lt._malloc(262144),ut=lt._malloc(65536),ht=lt._malloc(256)}function pt(){lt&&(ct&&lt._free(ct),ut&&lt._free(ut),ht&&lt._free(ht),ct=0,ut=0,ht=0),lt=null}function ft(){if(!lt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return lt}const mt={create(e){const t=ft(),r=t.geometry_create();if(0===r)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,ct/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,ht,n).set(o),t.geometry_init(r,ct,s,ht,n,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,ut,s).set(e.indices),t.geometry_setIndices16(r,ut,s)}else{new Uint32Array(t.HEAPU8.buffer,ut,s).set(e.indices),t.geometry_setIndices32(r,ut,s)}}return r},updateVertices(e,t,r=0){const s=ft(),n=t.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);s.HEAPF32.set(t,ct/4),s.geometry_updateVertices(e,ct,n,r)},release(e){e>0&&ft().geometry_release(e)},isValid:e=>!(!lt||e<=0)&&lt.geometry_isValid(e),createQuad(e=1,t=1){const r=e/2,s=t/2;return mt.create({vertices:new Float32Array([-r,-s,0,0,r,-s,1,0,r,s,1,1,-r,s,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const r=[],s=[];r.push(0,0,.5,.5);for(let s=0;s<=t;s++){const n=s/t*Math.PI*2,o=Math.cos(n)*e,i=Math.sin(n)*e,a=(Math.cos(n)+1)/2,l=(Math.sin(n)+1)/2;r.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return mt.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,r=1/0,s=-1/0,n=-1/0;for(const o of e)t=Math.min(t,o.x),r=Math.min(r,o.y),s=Math.max(s,o.x),n=Math.max(n,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-r)/(n-r);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return mt.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 _t=null;function gt(e){_t=e}function xt(){_t&&wt.isInitialized()&&wt.shutdown(),_t=null}function yt(){if(!_t)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return _t}const wt={init:(e,t)=>yt().postprocess_init(e,t),shutdown(){yt().postprocess_shutdown()},resize(e,t){yt().postprocess_resize(e,t)},addPass:(e,t)=>yt().postprocess_addPass(e,t),removePass(e){yt().postprocess_removePass(e)},setEnabled(e,t){yt().postprocess_setPassEnabled(e,t)},isEnabled:e=>yt().postprocess_isPassEnabled(e),setUniform(e,t,r){yt().postprocess_setUniformFloat(e,t,r)},setUniformVec4(e,t,r){yt().postprocess_setUniformVec4(e,t,r.x,r.y,r.z,r.w)},begin(){yt().postprocess_begin()},end(){yt().postprocess_end()},getPassCount:()=>yt().postprocess_getPassCount(),isInitialized:()=>!!_t&&_t.postprocess_isInitialized(),setBypass(e){yt().postprocess_setBypass(e)},isBypassed:()=>!_t||_t.postprocess_isBypassed(),createBlur:()=>Ue.createShader(vt,"#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:()=>Ue.createShader(vt,"#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:()=>Ue.createShader(vt,"#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:()=>Ue.createShader(vt,"#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")},vt="#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 bt;exports.RenderStage=void 0,(bt=exports.RenderStage||(exports.RenderStage={}))[bt.Background=0]="Background",bt[bt.Opaque=1]="Opaque",bt[bt.Transparent=2]="Transparent",bt[bt.Overlay=3]="Overlay";let St=null,Pt=0;function Ct(e){St=e,Pt=St._malloc(64)}function Tt(){St&&Pt&&(St._free(Pt),Pt=0),St=null}const At={init(e,t){St?.renderer_init(e,t)},resize(e,t){St?.renderer_resize(e,t)},begin(e,t){St&&Pt&&(St.HEAPF32.set(e,Pt/4),St.renderer_begin(Pt,t??0))},flush(){St?.renderer_flush()},end(){St?.renderer_end()},submitSprites(e){St&&St.renderer_submitSprites(e._cpp)},submitSpine(e){St&&St.renderer_submitSpine?.(e._cpp)},setStage(e){St?.renderer_setStage(e)},createRenderTarget:(e,t,r=1)=>St?.renderer_createTarget(e,t,r)??0,releaseRenderTarget(e){St?.renderer_releaseTarget(e)},getTargetTexture:e=>St?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>St?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,r,s){St?.renderer_setClearColor?.(e,t,r,s)},setViewport(e,t,r,s){St?.renderer_setViewport(e,t,r,s)},setScissor(e,t,r,s,n){St?.renderer_setScissor(e,t,r,s,n)},clearBuffers(e){St?.renderer_clearBuffers(e)},getStats:()=>St?{drawCalls:St.renderer_getDrawCalls(),triangles:St.renderer_getTriangles(),sprites:St.renderer_getSprites(),spine:St.renderer_getSpine?.()??0,meshes:St.renderer_getMeshes(),culled:St.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let Et=null;function Mt(e){Et=e}function Rt(){Et=null}const Ut={enable(){Et?.gl_enableErrorCheck(!0)},disable(){Et?.gl_enableErrorCheck(!1)},check:e=>Et?.gl_checkErrors(e)??0,diagnose(){Et?.renderer_diagnose()}},Ft=new Map;function Bt(e){Ft.delete(e)}class It{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:r,width:s,height:n,elapsed:o}=e;At.resize(s,n),wt.isInitialized()&&wt.getPassCount()>0&&!wt.isBypassed()&&wt.resize(s,n),At.setViewport(0,0,s,n),At.clearBuffers(3),At.begin(r),At.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,o):At.submitSpine(t),At.flush(),this.executeDrawCallbacks(r,o),At.end()}renderCamera(e){const{registry:t,viewProjection:r,viewportPixels:s,clearFlags:n,elapsed:o}=e;At.setViewport(s.x,s.y,s.w,s.h),At.setScissor(s.x,s.y,s.w,s.h,!0),At.clearBuffers(n),At.setScissor(0,0,0,0,!1),At.begin(r),At.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,o):At.submitSpine(t),At.flush(),this.executeDrawCallbacks(r,o),At.end()}executeDrawCallbacks(e,t){const r=Ft;if(r.size>0){nt.begin(e);const s=[];for(const[e,n]of r.entries())try{n(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}nt.end();for(const e of s)Bt(e)}}}class Dt{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=a(),t=e-this.lastTime_;this.lastTime_=e;const r=t/1e3;for(this.updateTime(r),this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=r;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate);this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),requestAnimationFrame(this.mainLoop)},this.world_=new pe,this.resources_=new J;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Dt}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 ae(this.world_,this.resources_),this.resources_.insert(Q,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1,Rt(),Tt(),xt(),pt(),Me(),tt()}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(Q);t.delta=e,t.elapsed+=e,t.frameCount++}}const Wt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function kt(e,t,r,s,n){const o=e*t/r,i=e;switch(s){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=n;return Math.pow(o,1-e)*Math.pow(i,e)}}}function zt(e,t,r,s,n,o){const i=new Float32Array(16),a=t-e,l=s-r,c=o-n;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+r)/l,i[14]=-(o+n)/c,i[15]=1,i}function $t(e,t,r,s){const n=new Float32Array(16),o=1/Math.tan(e/2),i=r-s;return n[0]=o/t,n[5]=o,n[10]=(s+r)/i,n[11]=-1,n[14]=2*s*r/i,n}function Lt(e,t,r){const s=new Float32Array(16);return s[0]=1,s[5]=1,s[10]=1,s[15]=1,s[12]=-e,s[13]=-t,s[14]=-r,s}function Ht(e,t){const r=new Float32Array(16);for(let s=0;s<4;s++)for(let n=0;n<4;n++)r[4*n+s]=e[0+s]*t[4*n+0]+e[4+s]*t[4*n+1]+e[8+s]*t[4*n+2]+e[12+s]*t[4*n+3];return r}async function Ot(e,t){if(t)return t();return(0,(await import(e)).default)()}const Nt=Y({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Vt=Y(null,"PhysicsAPI");function jt(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Gt(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Xt{constructor(e,t={},r){this.wasmUrl_=e,this.factory_=r,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Nt,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,r=new Map,s=Ot(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const n=function(e){const t=e.world.getEntitiesWithComponents([L]);for(const r of t){const t=e.world.get(r,L);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/n,i=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,oe([q(Q)],a=>{const l=i.getEntitiesWithComponents([S,W,k]),c=new Set;for(const n of l){c.add(n);const a=i.get(n,S),l=i.get(n,k);if(t.has(n)){const e=r.get(n);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(n,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=jt(l.rotation);s._physics_createBody(n,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Yt(e,s,n),t.add(n),r.set(n,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===A.Kinematic){const e=jt(l.rotation);s._physics_setBodyTransform(n,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),r.delete(e));s._physics_step(a.delta),function(e,t,r){const s=t._physics_getDynamicBodyCount();if(0===s)return;const n=t._physics_getDynamicBodyTransforms(),o=n>>2;for(let n=0;n<s;n++){const s=o+4*n,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*r,l=t.HEAPF32[s+2]*r,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,W);if(!u)continue;let h=a,d=l,p=c;if(e.world.has(i,O)){const t=e.world.get(i,O);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,k)){const r=e.world.get(t.entity,k),s=jt(r.rotation),n=a-r.position.x,o=l-r.position.y,i=Math.cos(-s),u=Math.sin(-s);h=(n*i-o*u)/(0!==r.scale.x?r.scale.x:1),d=(n*u+o*i)/(0!==r.scale.y?r.scale.y:1),p=c-s}}u.position.x=h,u.position.y=d;const f=Gt(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,W,u)}}(e,s,n),function(e,t,r){t._physics_collectEvents();const s=[],n=t._physics_getCollisionEnterCount();if(n>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<n;o++){const n=e+6*o;s.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1],normalX:t.HEAPF32[n+2],normalY:t.HEAPF32[n+3],contactX:t.HEAPF32[n+4]*r,contactY:t.HEAPF32[n+5]*r})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let r=0;r<i;r++){const s=e+2*r;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let r=0;r<l;r++){const s=e+2*r;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let r=0;r<u;r++){const s=e+2*r;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Nt,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,n)},{name:"PhysicsSystem"})),e.__physicsModule=s,e.insertResource(Vt,qt._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=s}}function Yt(e,t,r){const s=e.world;if(s.has(r,P)){const e=s.get(r,P);return void t._physics_addBoxShape(r,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(r,C)){const e=s.get(r,C);return void t._physics_addCircleShape(r,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(r,T)){const e=s.get(r,T);t._physics_addCapsuleShape(r,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class qt{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(qt.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 Kt(e,t,r=!0){const s=e.getResourceManager(),n=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,n);const o=s.createTexture(t.width,t.height,n,t.pixels.length,1,r);return e._free(n),o}function Jt(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function Qt(e,t,r,s){const n=e.scale.x*t*(r?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,h=a+a,d=l+l,p=c+c,f=a*h,m=a*d,_=a*p,g=l*d,x=l*p,y=c*p,w=u*h,v=u*d,b=u*p;return new Float32Array([(1-(g+y))*n,(m+b)*n,(_-v)*n,0,(m-b)*o,(1-(f+y))*o,(x+w)*o,0,(_+v)*i,(x-w)*i,(1-(f+g))*i,0,e.position.x,e.position.y,e.position.z,1])}async function Zt(e,t,r,s,n,o,i){const a=await async function(e,t,r){const s={};for(const n of t.entities)for(const t of n.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const n=t.data.texture;if(void 0!==s[n])continue;try{s[n]=Kt(e,await r.loadPixels(n))}catch{s[n]=0}}return s}(t,r,s);!function(e,t,r){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const n=r[e];if(n&&n>0){const r=t.textureMetadata[e];if(r?.sliceBorder){const e=r.sliceBorder;s.setTextureMetadata(n,e.left,e.right,e.top,e.bottom)}}}}(t,r,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,r,s,n){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=n.resolvePath(i),c=n.resolvePath(a);try{const s=n.readText(a),u=l.endsWith(".skel");let 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),r=(new TextEncoder).encode(e);d=r.length,h=t._malloc(d+1),t.HEAPU8.set(r,h),t.HEAPU8[h+d]=0}const p=r.loadSkeleton(h,d,s,s.length,u);if(t._free(h),p<0)continue;o[i]=p;const f=Jt(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const s=m+"/"+f[t];try{const o=n.loadPixelsRaw?await n.loadPixelsRaw(s):await n.loadPixels(s),i=Kt(e,o,!1),a=e.getResourceManager().getTextureGLId(i);r.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,n,c,r,s)),o){new Xt("",{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 r={},s={};for(const n of e.entities)for(const e of n.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const n=e.data.material;if(void 0===r[n])try{const e=JSON.parse(t.readText(n));if(!e.vertexSource||!e.fragmentSource){r[n]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=Ue.createShader(e.vertexSource,e.fragmentSource),s[o]=i),r[n]=Ue.createFromAsset(e,i)}catch{r[n]=0}}return r}(r,s),h=He(e.world,r);if(function(e,t,r,s){for(const n of t.entities){const t=s.get(n.id);if(void 0!==t)for(const s of n.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const n=e.get(t,z);n&&(n.texture=r[s.data.texture]||0,e.insert(t,z,n))}}}(e.world,r,a,h),function(e,t,r,s){for(const n of t.entities){const t=s.get(n.id);if(void 0!==t)for(const s of n.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const n=r[s.data.material]||0;if(n)if("Sprite"===s.type){const r=e.get(t,z);r&&(r.material=n,e.insert(t,z,r))}else if("SpineAnimation"===s.type){const r=e.get(t,V);r&&(r.material=n,e.insert(t,V,r))}}}}(e.world,r,u,h),n&&c){const s=function(e,t,r,s){const n={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=r[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(n[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return n}(c,r,l,h);!function(e,t,r,s,n){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in n){const o=Number(e),i=n[e],a=c.has(o,V)?c.get(o,V):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&s.update(i,l*h);let d=0;if(c.has(o,k)){const e=Qt(c.get(o,k),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const p=s.getMeshBatchCount(i);for(let e=0;e<p;e++){const n=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!n||!o)continue;const a=8*n*4,l=2*o,c=r._malloc(a),u=r._malloc(l),h=r._malloc(4),p=r._malloc(4);s.getMeshBatchData(i,e,c,u,h,p);const f=r.HEAPU32[h>>2],m=r.HEAPU32[p>>2],_=new Float32Array(r.HEAPF32.buffer,c,8*n),g=new Uint16Array(r.HEAPU8.buffer,u,o),x=t._malloc(a),y=t._malloc(l);t.HEAPF32.set(_,x>>2),new Uint16Array(t.HEAPU8.buffer,y,o).set(g),t.renderer_submitTriangles(x,n,y,o,f,m,d),t._free(x),t._free(y),r._free(c),r._free(u),r._free(h),r._free(p)}d&&t._free(d)}})}(e,t,n,c,s)}}class er{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,r=new Set;for(const s of e.entities)for(const e of s.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,n=e.data.atlasPath;s&&(s.endsWith(".skel")?r.add(s):t.add(s)),n&&t.add(n)}"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 r)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),r=await fetch(t),s=await r.blob(),n=await createImageBitmap(s),o=new OffscreenCanvas(n.width,n.height).getContext("2d");o.drawImage(n,0,0);const i=o.getImageData(0,0,n.width,n.height);return n.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const tr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),r=At.createRenderTarget(e.width,e.height,t);return{_handle:r,textureId:At.getTargetTexture(r),width:e.width,height:e.height}},release(e){At.releaseRenderTarget(e._handle)},resize:(e,t,r)=>(At.releaseRenderTarget(e._handle),tr.create({width:t,height:r,depth:!0})),begin(e,t){At.begin(t,e._handle)},end(){At.end()},getDepthTexture:e=>At.getTargetDepthTexture(e._handle)};let rr=!1;var sr;y||(y=!0,void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const r="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},n=await l(r,s);return{ok:n.ok,status:n.status,statusText:n.statusText,headers:new Headers(n.headers),json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:r}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return c(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),r=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);n<128?r[s++]=n:n<2048?(r[s++]=192|n>>6,r[s++]=128|63&n):n>=55296&&n<=56319?(n=e.charCodeAt(++t)-56320+(n-55296<<10)+65536,r[s++]=240|n>>18,r[s++]=128|n>>12&63,r[s++]=128|n>>6&63,r[s++]=128|63&n):(r[s++]=224|n>>12,r[s++]=128|n>>6&63,r[s++]=128|63&n)}return r.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let r="";for(let e=0;e<t.length;){const s=t[e];if(s<128)r+=String.fromCharCode(s),e++;else if(192==(224&s))r+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))r+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const n=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;r+=String.fromCharCode(55296+(n>>10),56320+(1023&n)),e+=4}}return r}})}(),console.log("[ESEngine] WeChat platform initialized")),e=sr=w,console.log(`[ESEngine] Platform: ${sr.name}`),exports.App=Dt,exports.AssetPlugin=Xe,exports.AssetServer=je,exports.Assets=Ge,exports.AsyncCache=Ve,exports.BodyType=A,exports.BoxCollider=P,exports.Camera=$,exports.Canvas=L,exports.CapsuleCollider=T,exports.Children=N,exports.CircleCollider=C,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=re,exports.Draw=nt,exports.EntityCommands=te,exports.GLDebug=Ut,exports.Geometry=mt,exports.INVALID_ENTITY=0,exports.INVALID_TEXTURE=v,exports.Input=ce,exports.InputPlugin=ue,exports.InputState=le,exports.LocalTransform=W,exports.Material=Ue,exports.MaterialLoader=Le,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=j,exports.Parent=O,exports.Physics=qt,exports.PhysicsEvents=Nt,exports.PhysicsPlugin=Xt,exports.PostProcess=wt,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 r(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new er(this.baseUrl_);await s.prefetch(t);let n=null;const o=this.app_.__spineInitPromise;if(o){n=(await o).controller.raw}await Zt(this.app_,this.app_.wasmModule,t,s,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 r=e.getEntitiesWithComponents([$]);for(const s of r){if(e.get(s,$).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,r=1920/1080;const s=e.getEntitiesWithComponents([L]);for(const n of s){const s=e.get(n,L);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,r=s.designResolution.x/s.designResolution.y;break}}const n=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(n,W,o);const i={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:r,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3};e.insert(n,$,i)}}},exports.Query=function(...e){return function(e,t=[],r=[]){const s=[];return e.forEach((e,t)=>{Z(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:r}}(e)},exports.QueryInstance=ee,exports.RenderPipeline=It,exports.RenderTexture=tr,exports.Renderer=At,exports.Res=q,exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.RigidBody=S,exports.ShaderSources=$e,exports.SpineAnimation=V,exports.Sprite=z,exports.SystemRunner=ae,exports.Text=ge,exports.TextPlugin=we,exports.TextRenderer=xe,exports.Time=Q,exports.UIRect=ye,exports.Velocity=H,exports.WebAssetProvider=er,exports.World=pe,exports.WorldTransform=k,exports.addStartupSystem=function(e){ie().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){ie().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){ie().push({schedule:e,system:t})},exports.assetPlugin=Ye,exports.clearDrawCallbacks=function(){Ft.clear()},exports.clearUserComponents=function(){R().clear()},exports.color=(e=1,t=1,r=1,s=1)=>({r:e,g:t,b:r,a:s}),exports.createWebApp=function(e,t){const r=Dt.new(),s=new e.Registry;r.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),et(e),Ee(e),dt(e),gt(e),Ct(e),Mt(e);const n=new It;r.pipeline_=n;let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),l={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:r}=i(),l=e.registry_getCanvasEntity(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;At.setClearColor(e.r,e.g,e.b,e.a)}const c=(a()-o)/1e3;At.resize(t,r),wt.isInitialized()&&wt.getPassCount()>0&&!wt.isBypassed()&&wt.resize(t,r);const u=function(e,t,r,s){const n=e.registry_getCameraEntities(t);if(0===n.length)return[];const o=function(e,t){const r=e.registry_getCanvasEntity(t);return r<0?null:t.getCanvas(r)}(e,t),i=[];for(const e of n){const n=t.getCamera(e),a=t.getLocalTransform(e),l={x:n.viewportX,y:n.viewportY,w:n.viewportW,h:n.viewportH},c=l.w*r/(l.h*s);let u;if(1===n.projectionType){let e=n.orthoSize;if(o){e=kt(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}const t=e*c;u=zt(-t,t,-e,e,-n.farPlane,n.farPlane)}else u=$t(n.fov*Math.PI/180,c,n.nearPlane,n.farPlane);const h=Lt(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:Ht(u,h),viewportRect:l,clearFlags:n.clearFlags,priority:n.priority})}return i.sort((e,t)=>e.priority-t.priority),i}(e,s,t,r);if(0===u.length)n.render({registry:{_cpp:s},viewProjection:Wt,width:t,height:r,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)*r),l=Math.round(o.w*t),u=Math.round(o.h*r);n.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}At.setViewport(0,0,t,r)}}};return r.addSystemToSchedule(exports.Schedule.Last,l),r.addPlugin(Ye),r.addPlugin(he),r.addPlugin(ve),r},exports.defineComponent=U,exports.defineResource=Y,exports.defineSystem=oe,exports.defineTag=function(e){const t=R(),r=t.get(e);if(r)return r;const s=M(e,{});return t.set(e,s),B(e,{},!0),s},exports.findEntityByName=function(e,t){const r=e.getEntitiesWithComponents([j]);for(const s of r){const r=e.get(s,j);if(r&&r.value===t)return s}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const r of t)e.addSystemToSchedule(r.schedule,r.system);t.length=0}},exports.getComponentDefaults=function(e){const t=G[e];if(t)return{...t._default};const r=F(e);return r?{...r._default}:null},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=F,exports.initDrawAPI=et,exports.initGLDebugAPI=Mt,exports.initGeometryAPI=dt,exports.initMaterialAPI=Ee,exports.initPostProcessAPI=gt,exports.initRendererAPI=Ct,exports.inputPlugin=he,exports.isBuiltinComponent=D,exports.isEditor=function(){return rr},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!rr},exports.isTextureRef=Se,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=Ne,exports.loadPhysicsModule=Ot,exports.loadRuntimeScene=Zt,exports.loadSceneData=He,exports.loadSceneWithAssets=Oe,exports.platformFetch=r,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,r){return t().instantiateWasm(e,r)},exports.platformReadFile=s,exports.platformReadTextFile=n,exports.quat=(e=1,t=0,r=0,s=0)=>({w:e,x:t,y:r,z:s}),exports.registerDrawCallback=function(e,t){Ft.set(e,t)},exports.registerEmbeddedAssets=function(e,t){const r=e.getResource(Ge);r&&r.registerEmbeddedAssets(t)},exports.registerMaterialCallback=ze,exports.setEditorMode=function(e){rr=e},exports.shutdownDrawAPI=tt,exports.shutdownGLDebugAPI=Rt,exports.shutdownGeometryAPI=pt,exports.shutdownMaterialAPI=Me,exports.shutdownPostProcessAPI=xt,exports.shutdownRendererAPI=Tt,exports.textPlugin=ve,exports.unregisterDrawCallback=Bt,exports.updateCameraAspectRatio=function(e,t){const r=e.getEntitiesWithComponents([$]);for(const s of r){const r=e.get(s,$);r&&(r.aspectRatio=t,e.insert(s,$,r))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,r=0)=>({x:e,y:t,z:r}),exports.vec4=(e=0,t=0,r=0,s=1)=>({x:e,y:t,z:r,w:s}),exports.wxFileExists=f,exports.wxFileExistsSync=function(e){const t=h();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=x,exports.wxLoadImage=g,exports.wxLoadImagePixels=async function(e){return x(await g(e))},exports.wxReadFile=d,exports.wxReadTextFile=p,exports.wxWriteFile=function(e,t){return new Promise((r,s)=>{h().writeFile({filePath:e,data:t,success:()=>r(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};
+"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function r(e,r){return t().fetch(e,r)}async function s(e){return t().readFile(e)}async function n(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,r){return t().createCanvas(e,r)}function a(){return t().now()}function l(e,t){return new Promise((r,s)=>{const n=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===n?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];r({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,r="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(r).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function c(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const r=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(r,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${r}": ${t}`)}}let u=null;function h(){return u||(u=wx.getFileSystemManager()),u}function d(e){return new Promise((t,r)=>{h().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function p(e,t="utf-8"){return new Promise((r,s)=>{h().readFile({filePath:e,encoding:t,success:e=>{r(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function f(e){return new Promise(t=>{h().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}let m=null,_=null;function g(e){return new Promise((t,r)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>r(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function x(e){const{width:t,height:r}=e,{ctx:s}=function(e,t){return m||(m=wx.createCanvas(),m.width=e,m.height=t,_=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:_}}(t,r);s.clearRect(0,0,t,r),s.drawImage(e,0,0);const n=s.getImageData(0,0,t,r);return{width:t,height:r,pixels:new Uint8Array(n.data.buffer)}}let y=!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 r=wx.createCanvas();return r.width=e,r.height=t,r}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{const r=t.touches[0];r&&e.onPointerDown(0,r.clientX,r.clientY)}),wx.onTouchMove(t=>{const r=t.touches[0];r&&e.onPointerMove(r.clientX,r.clientY)}),wx.onTouchEnd(()=>{e.onPointerUp(0)})}},v=4294967295;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}),T=b("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 M(e,t){const r=++E;return{_id:Symbol(`Component_${r}_${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 r=R(),s=r.get(e);if(s)return s;const n=M(e,t);return r.set(e,n),U(e,t,!1),n}function B(e){return R().get(e)}function U(e,t,r){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,r)}function I(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function D(e){return!0===e._builtin}const W=I("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),k=I("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),z=I("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}),$=I("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}),L=I("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),H=I("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),O=I("Parent",{entity:0}),N=I("Children",{entities:[]}),V=I("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:0}),j=I("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),G={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},X={LocalTransform:W,WorldTransform:k,Sprite:z,Camera:$,Canvas:L,Velocity:H,Parent:O,Children:N,BitmapText:V,SpineAnimation:j,RigidBody:S,BoxCollider:P,CircleCollider:C,CapsuleCollider:T};let Y=0;function q(e,t){const r=++Y;return{_id:Symbol(`Resource_${r}_${t??""}`),_name:t??`Resource_${r}`,_default:e}}function K(e){return{_type:"res",_resource:e}}class J{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 Q{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 J(this.get(e),t=>this.set(e,t))}}const Z=q({delta:0,elapsed:0,frameCount:0},"Time");function ee(e){return"object"==typeof e&&null!==e&&"mut"===e._type}class te{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>ee(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with)}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,r=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),n=r.length,o=e.length>0,i=t.length>0;let a=null,l=[];try{for(const c of s){if(null!==a&&o){for(let e=0;e<l.length;e++){const t=l[e];this.world_.insert(a,t.component,t.data)}l.length=0}if(i){let e=!1;for(let r=0;r<t.length;r++)if(this.world_.has(c,t[r])){e=!0;break}if(e)continue}const s=new Array(n+1);s[0]=c;for(let e=0;e<n;e++)s[e+1]=this.world_.get(c,r[e]);if(o){for(let t=0;t<e.length;t++){const n=e[t];l.push({component:r[n],data:s[n+1]})}a=c}yield s}}finally{if(null!==a&&o)for(let e=0;e<l.length;e++){const t=l[e];this.world_.insert(a,t.component,t.data)}}}forEach(e){for(const[t,...r]of this)e(t,...r)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){return[...this]}}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 r;return r=D(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:r}):this.commands_.queueInsert(this.entityRef_.entity,e,r),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class se{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,r){this.pending_.push({type:"insert",entity:e,component:t,data:r})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const r=this.world_.spawn();t.entity=r;for(const t of e)this.world_.insert(r,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const r of e.components)this.world_.insert(t,r.component,r.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var ne;exports.Schedule=void 0,(ne=exports.Schedule||(exports.Schedule={}))[ne.Startup=0]="Startup",ne[ne.First=1]="First",ne[ne.PreUpdate=2]="PreUpdate",ne[ne.Update=3]="Update",ne[ne.PostUpdate=4]="PostUpdate",ne[ne.Last=5]="Last",ne[ne.FixedPreUpdate=10]="FixedPreUpdate",ne[ne.FixedUpdate=11]="FixedUpdate",ne[ne.FixedPostUpdate=12]="FixedPostUpdate";let oe=0;function ie(e,t,r){const s=++oe;return{_id:Symbol(`System_${s}_${r?.name??""}`),_params:e,_fn:t,_name:r?.name??`System_${s}`}}function ae(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class le{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let r=0;r<e._params.length;r++)t[r]=this.resolveParam(e._params[r]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof se&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new te(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new se(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class ce{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 ue=q(new ce,"Input");class he{constructor(e){this.target_=e??null}build(e){const r=new ce;e.insertResource(ue,r),t().bindInputEvents({onKeyDown(e){r.keysDown.has(e)||r.keysPressed.add(e),r.keysDown.add(e)},onKeyUp(e){r.keysDown.delete(e),r.keysReleased.add(e)},onPointerMove(e,t){r.mouseX=e,r.mouseY=t},onPointerDown(e,t,s){r.mouseX=t,r.mouseY=s,r.mouseButtons.add(e),r.mouseButtonsPressed.add(e)},onPointerUp(e){r.mouseButtons.delete(e),r.mouseButtonsReleased.add(e)},onWheel(e,t){r.scrollDeltaX+=e,r.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.First,ie([],()=>{r.keysPressed.clear(),r.keysReleased.clear(),r.mouseButtonsPressed.clear(),r.mouseButtonsReleased.clear(),r.scrollDeltaX=0,r.scrollDeltaY=0},{name:"InputClearSystem"}))}}const de=new he;function pe(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 r={};for(const e of Object.keys(t)){const s=t[e];r[e]=null==s||"object"!=typeof s||Array.isArray(s)?s:pe(s)}return r}class fe{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,r){return D(t)?this.insertBuiltin(e,t,r):this.insertScript(e,t,r)}get(e,t){return D(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return D(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){D(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,r){const s={...t._default,...r};if(this.cppRegistry_){const r=`add${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e,pe(s))}return s}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const r=`get${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const r=`has${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const r=`remove${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e)}insertScript(e,t,r){const s=t.create(r);return this.getStorage(t).set(e,s),s}getScript(e,t){const r=this.tsStorage_.get(t._id);if(!r)throw new Error(`Component not found: ${t._name}`);return r.get(e)}hasScript(e,t){const r=this.tsStorage_.get(t._id);return r?.has(e)??!1}removeScript(e,t){const r=this.tsStorage_.get(t._id);r?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();let t=null,r=1/0;for(const s of e)if(!D(s)){const e=this.tsStorage_.get(s._id),n=e?e.size:0;n<r&&(r=n,t=e??null)}const s=[],n=t?t.keys():this.entities_;for(const t of n){let r=!0;for(const s of e)if(!this.has(t,s)){r=!1;break}r&&s.push(t)}return s}}var me,_e,ge;exports.TextAlign=void 0,(me=exports.TextAlign||(exports.TextAlign={}))[me.Left=0]="Left",me[me.Center=1]="Center",me[me.Right=2]="Right",exports.TextVerticalAlign=void 0,(_e=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[_e.Top=0]="Top",_e[_e.Middle=1]="Middle",_e[_e.Bottom=2]="Bottom",exports.TextOverflow=void 0,(ge=exports.TextOverflow||(exports.TextOverflow={}))[ge.Visible=0]="Visible",ge[ge.Clip=1]="Clip",ge[ge.Ellipsis=2]="Ellipsis";const xe=F("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 ye{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const r=this.ctx,s=this.canvas;r.font=`${e.fontSize}px ${e.fontFamily}`;const n=t&&t.size.x>0&&t.size.y>0,o=n?t.size.x:0,i=n?t.size.y:0,a=e.wordWrap&&n;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),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(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),_=Math.round(255*e.color.g),g=Math.round(255*e.color.b),x=e.color.a;r.clearRect(0,0,s.width,s.height),r.font=`${e.fontSize}px ${e.fontFamily}`,r.textAlign=this.mapAlign(e.align),r.textBaseline="top",r.fillStyle=`rgba(${m}, ${_}, ${g}, ${x})`,n&&e.overflow===exports.TextOverflow.Clip&&(r.save(),r.beginPath(),r.rect(0,0,p,f),r.clip());const y=l.length*c;let w;if(n)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-y)/2;break;case exports.TextVerticalAlign.Bottom:w=f-y-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}r.fillText(t,s,v),v+=c}n&&e.overflow===exports.TextOverflow.Clip&&r.restore();const b=r.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 r=e;for(;r.length>0&&this.ctx.measureText(r+"...").width>t;)r=r.slice(0,-1);return r+"..."}renderForEntity(e,t,r){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const n=this.renderText(t,r);return this.cache.set(e,n),n}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[r,s]of this.cache)e(r)||(t.releaseTexture(s.textureHandle),this.cache.delete(r))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const r=e.split("\n"),s=[];for(const e of r){if(!e){s.push("");continue}let r="";for(const n of e){const e=r+n;this.ctx.measureText(e).width>t&&r?(s.push(r),r=n):r=e}r&&s.push(r)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const r of e){const e=this.ctx.measureText(r),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const we=F("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},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 r=new ye(t),s=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,ie([],()=>{r.cleanupOrphaned(e=>s.valid(e)&&s.has(e,xe));const e=s.getEntitiesWithComponents([xe]);for(const t of e){const e=s.get(t,xe);if(!e.dirty)continue;s.has(t,z)||s.insert(t,z,{texture:v,size:{x:0,y:0},color:{r:1,g:1,b:1,a:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const n=s.has(t,we)?s.get(t,we):null,o=r.renderForEntity(t,e,n),i=s.get(t,z);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,z,i),e.dirty=!1}}))}}const be=new ve;var Se;function Pe(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(Se=exports.BlendMode||(exports.BlendMode={}))[Se.Normal=0]="Normal",Se[Se.Additive=1]="Additive",Se[Se.Multiply=2]="Multiply",Se[Se.Screen=3]="Screen",Se[Se.PremultipliedAlpha=4]="PremultipliedAlpha";let Ce=null,Te=null,Ae=1;const Ee=new Map;function Me(e){Ce=e,Te=e.getResourceManager(),$e()}function Re(){0!==Ie&&Ce&&(Ce._free(Ie),Ie=0),Ee.clear(),Ae=1,Ue=!1,Te=null,Ce=null}function Fe(){if(!Te)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Te}const Be={createShader:(e,t)=>Fe().createShader(e,t),releaseShader(e){e>0&&Fe().releaseShader(e)},create(e){const t=Ae++,r={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))r.uniforms.set(t,s);return Ee.set(t,r),t},get:e=>Ee.get(e),setUniform(e,t,r){const s=Ee.get(e);s&&s.uniforms.set(t,r)},getUniform(e,t){const r=Ee.get(e);return r?.uniforms.get(t)},setBlendMode(e,t){const r=Ee.get(e);r&&(r.blendMode=t)},getBlendMode(e){const t=Ee.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const r=Ee.get(e);r&&(r.depthTest=t)},getShader(e){const t=Ee.get(e);return t?.shader??0},release(e){Ee.delete(e)},isValid:e=>Ee.has(e),createFromAsset(e,t){const r={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)r[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?r[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(r[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:r,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ee.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const r=Ae++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Ee.set(r,s),r},toAssetData(e,t){const r=Ee.get(e);if(!r)return null;const s={};for(const[e,t]of r.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:r.blendMode,depthTest:r.depthTest,properties:s}},getUniforms(e){const t=Ee.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ue=!1,Ie=0;const De=4096,We=new Map;let ke=null;function ze(e){const t=(0===Ie&&Ce&&(Ie=Ce._malloc(De)),Ie);if(0===t||!Ce)return{ptr:0,count:0};let r=0,s=0;const n=Ce.HEAPU8,o=Ce.HEAPU32,i=Ce.HEAPF32;for(const[a,l]of e){if(r+128>De)break;let e=We.get(a);e||(ke||(ke=new TextEncoder),e=ke.encode(a),We.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+r>>2]=c,r+=4,n.set(e,t+r),r+=u;let 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+r>>2]=h,r+=4;for(let e=0;e<4;e++)i[t+r>>2]=d[e],r+=4;s++}return{ptr:t,count:s}}function $e(){if(!Ce||Ue)return;Ce.materialDataProvider=(e,t,r,s,n)=>{const o=Ee.get(e);if(!o)return Ce.HEAPU32[t>>2]=0,Ce.HEAPU32[r>>2]=0,Ce.HEAPU32[s>>2]=0,void(Ce.HEAPU32[n>>2]=0);Ce.HEAPU32[t>>2]=o.shader,Ce.HEAPU32[r>>2]=o.blendMode;const{ptr:i,count:a}=ze(o.uniforms);Ce.HEAPU32[s>>2]=i,Ce.HEAPU32[n>>2]=a},Ue=!0}const Le={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 He{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const r=this.pending_.get(e);if(r)return r;const s=this.loadInternal(e);this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Be.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Be.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await o(t))throw new Error(`Material file not found: ${t}`);const r=await n(t);if(!r)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(r);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),a=await this.shaderLoader_.load(i);return{handle:Be.createFromAsset(s,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const r=e.substring(0,e.lastIndexOf("/"));return r?`${r}/${t}`:t}}function Oe(e,t){const r=new Map;for(const s of t.entities){const t=e.spawn();r.set(s.id,t),e.insert(t,G,{value:s.name});for(const r of s.components)Ve(e,t,r)}for(const s of t.entities)if(null!==s.parent){const t=r.get(s.id),n=r.get(s.parent);void 0!==t&&void 0!==n&&e.setParent(t,n)}return r}async function Ne(e,t,r){const s=new Map,n=r?.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&&n){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:r?.assetBaseUrl?`${r.assetBaseUrl}/${t}`:`/${t}`;try{const r=await n.loadTexture(s);e.texture=r.handle,o.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("BitmapText"===s.type&&n){const e=s.data;if("string"==typeof e.font&&e.font)try{const t=await n.loadBitmapFont(e.font,r?.assetBaseUrl);e.font=t}catch(t){console.warn(`Failed to load bitmap font: ${e.font}`,t),e.font=0}}if("SpineAnimation"===s.type&&n){const e=s.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await n.loadSpine(t,o,r?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Ve(e,t,s)}}for(const r of t.entities)if(null!==r.parent){const t=s.get(r.id),n=s.get(r.parent);void 0!==t&&void 0!==n&&e.setParent(t,n)}if(n&&t.textureMetadata)for(const[e,r]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&r.sliceBorder&&n.setTextureMetadataByPath(t,r.sliceBorder)}return s}function Ve(e,t,r){const s=r.data;switch(r.type){case"LocalTransform":e.insert(t,W,s);break;case"Sprite":e.insert(t,z,s);break;case"Camera":e.insert(t,$,s);break;case"Canvas":e.insert(t,L,s);break;case"Text":e.insert(t,xe,s);break;case"BitmapText":e.insert(t,V,s);break;case"SpineAnimation":e.insert(t,j,s);break;case"UIRect":e.insert(t,we,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,T,s);break;default:{const n=B(r.type);n?e.insert(t,n,s):console.warn(`Unknown component type: ${r.type}`);break}}}class je{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const r=this.cache_.get(e);if(void 0!==r)return r;const s=this.pending_.get(e);if(s)return s;const n=t();this.pending_.set(e,n);try{const t=await n;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class Ge{constructor(e){this.textureCache_=new je,this.shaderCache_=new je,this.jsonCache_=new je,this.textCache_=new je,this.binaryCache_=new je,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new je,this.embedded_=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 He(t)}registerEmbeddedAssets(e){for(const[t,r]of Object.entries(e))this.embedded_.set(t,r)}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const r of[!0,!1]){const s=this.textureCacheKey(e,r),n=this.textureCache_.get(s);n&&(t.releaseTexture(n.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);this.textureCache_.clear(),this.fontCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const r=this.textureCache_.get(this.textureCacheKey(e,!0));return!!r&&(this.setTextureMetadata(r.handle,t),!0)}async loadSpine(e,t,r){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const n=this.resolveUrl(t,r),o=await this.fetchText(n);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o);for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,r);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,r),c=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);return this.writeToVirtualFS(e,c)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const r=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(r,async()=>e.endsWith(".bmfont")?this.loadBmfontAsset(r):this.loadFntFile(r))}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),r=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const n=r?`${r}/${s}`:s;return this.loadFntFile(n)}async loadFntFile(e){const t=await this.fetchText(e),r=t.match(/file="([^"]+)"/);if(!r)throw new Error(`No page texture found in .fnt file: ${e}`);const s=r[1],n=e.substring(0,e.lastIndexOf("/")),o=n?`${n}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(r):this.jsonCache_.getOrLoad(r,()=>this.fetchJson(r))}async loadText(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(r):this.textCache_.getOrLoad(r,()=>this.fetchText(r))}async loadBinary(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(r):this.binaryCache_.getOrLoad(r,()=>this.fetchBinary(r))}async loadScene(e,t){return Ne(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},r=[];if(e.textures)for(const s of e.textures)r.push(this.loadTexture(s).then(e=>{t.textures.set(s,e)}));if(e.materials)for(const s of e.materials)r.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}`;r.push(this.loadSpine(s.skeleton,s.atlas,s.baseUrl).then(r=>{t.spine.set(e,r)}))}if(e.json)for(const s of e.json)r.push(this.loadJson(s).then(e=>{t.json.set(s,e)}));if(e.text)for(const s of e.text)r.push(this.loadText(s).then(e=>{t.text.set(s,e)}));if(e.binary)for(const s of e.binary)r.push(this.loadBinary(s).then(e=>{t.binary.set(s,e)}));return await Promise.all(r),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const r=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(r,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const r=await this.loadImage(e);return this.createTextureFromImage(r,t)}async loadImage(e){const r=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(r)??r;return new Promise((r,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 r(e)}catch{}r(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=s})}createTextureFromImage(e,t){const{width:r,height:s}=e,n=this.getWebGL2Context();return n?this.createTextureWebGL2(n,e,r,s,t):this.createTextureFallback(e,r,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,r,s,n){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,n?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,r,s),width:r,height:s}}createTextureFallback(e,t,r,s){(this.canvas_.width<t||this.canvas_.height<r)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(r))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const n=this.ctx_.getImageData(0,0,t,r),o=new Uint8Array(n.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,r,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:r}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const r=e[t+3];if(r>0&&r<255){const s=255/r;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e;if(!await o(t))throw new Error(`Shader file not found: ${e}`);const r=await n(t);if(!r)throw new Error(`Failed to read shader file: ${e}`);const{vertex:s,fragment:i}=this.parseEsShader(r);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return Be.createShader(s,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),r=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:r?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const r=await n(t);return JSON.parse(r)}const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):n(t)}const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):s(t)}const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const r=this.module_.FS;if(!r)return!1;try{return this.ensureVirtualDir(e),r.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const r=e.substring(0,e.lastIndexOf("/"));if(!r)return;const s=r.split("/").filter(e=>e);let n="";for(const e of s){n=n?`${n}/${e}`:e;try{t.analyzePath(n).exists||t.mkdir(n)}catch{try{t.mkdir(n)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const r=t??this.baseUrl;return r?`${r}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Xe=q(null,"Assets");class Ye{build(e){const t=e.wasmModule;t?e.insertResource(Xe,new Ge(t)):console.warn("AssetPlugin: No WASM module available")}}const qe=new Ye;let Ke=null,Je=0,Qe=0,Ze=0;const et=new Float32Array(256);function tt(e){Ke=e,Je=Ke._malloc(64),Qe=Ke._malloc(64),Ze=Ke._malloc(1024)}function rt(){Ke&&(Je&&(Ke._free(Je),Je=0),Qe&&(Ke._free(Qe),Qe=0),Ze&&(Ke._free(Ze),Ze=0)),Ke=null}function st(){if(!Ke)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Ke}const nt={r:1,g:1,b:1,a:1},ot={begin(e){const t=st();t.HEAPF32.set(e,Je/4),t.draw_begin(Je)},end(){st().draw_end()},line(e,t,r,s=1){st().draw_line(e.x,e.y,t.x,t.y,r.r,r.g,r.b,r.a,s)},rect(e,t,r,s=!0){st().draw_rect(e.x,e.y,t.x,t.y,r.r,r.g,r.b,r.a,s)},rectOutline(e,t,r,s=1){st().draw_rectOutline(e.x,e.y,t.x,t.y,r.r,r.g,r.b,r.a,s)},circle(e,t,r,s=!0,n=32){st().draw_circle(e.x,e.y,t,r.r,r.g,r.b,r.a,s,n)},circleOutline(e,t,r,s=1,n=32){st().draw_circleOutline(e.x,e.y,t,r.r,r.g,r.b,r.a,s,n)},texture(e,t,r,s=nt){st().draw_texture(e.x,e.y,t.x,t.y,r,s.r,s.g,s.b,s.a)},textureRotated(e,t,r,s,n=nt){st().draw_textureRotated(e.x,e.y,t.x,t.y,r,s,n.r,n.g,n.b,n.a)},setLayer(e){st().draw_setLayer(e)},setDepth(e){st().draw_setDepth(e)},getDrawCallCount:()=>Ke?Ke.draw_getDrawCallCount():0,getPrimitiveCount:()=>Ke?Ke.draw_getPrimitiveCount():0,setBlendMode(e){st().draw_setBlendMode(e)},setDepthTest(e){st().draw_setDepthTest(e)},drawMesh(e,t,r){const s=st();s.HEAPF32.set(r,Qe/4),s.draw_mesh(e,t,Qe)},drawMeshWithMaterial(e,t,r){const s=st(),n=Be.get(t);if(!n)return;if(ot.setBlendMode(n.blendMode),ot.setDepthTest(n.depthTest),0===n.uniforms.size)return void ot.drawMesh(e,n.shader,r);s.HEAPF32.set(r,Qe/4);let o=0,i=0;for(const[e,t]of n.uniforms){const r=at(e);if(!(r<0)){if(Pe(t))et[o++]=10,et[o++]=r,et[o++]=t.slot??i++,et[o++]=t.textureId;else if("number"==typeof t)et[o++]=1,et[o++]=r,et[o++]=t;else if(Array.isArray(t)){et[o++]=t.length,et[o++]=r;for(let e=0;e<t.length;e++)et[o++]=t[e]}else"w"in t?(et[o++]=4,et[o++]=r,et[o++]=t.x,et[o++]=t.y,et[o++]=t.z,et[o++]=t.w):"z"in t?(et[o++]=3,et[o++]=r,et[o++]=t.x,et[o++]=t.y,et[o++]=t.z):(et[o++]=2,et[o++]=r,et[o++]=t.x,et[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(et.subarray(0,o),Ze/4),s.draw_meshWithUniforms(e,n.shader,Qe,Ze,o)):s.draw_mesh(e,n.shader,Qe)}},it={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 at(e){return it[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 ct=null,ut=0,ht=0,dt=0;function pt(e){ct=e,ut=ct._malloc(262144),ht=ct._malloc(65536),dt=ct._malloc(256)}function ft(){ct&&(ut&&ct._free(ut),ht&&ct._free(ht),dt&&ct._free(dt),ut=0,ht=0,dt=0),ct=null}function mt(){if(!ct)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ct}const _t={create(e){const t=mt(),r=t.geometry_create();if(0===r)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,ut/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,dt,n).set(o),t.geometry_init(r,ut,s,dt,n,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,ht,s).set(e.indices),t.geometry_setIndices16(r,ht,s)}else{new Uint32Array(t.HEAPU8.buffer,ht,s).set(e.indices),t.geometry_setIndices32(r,ht,s)}}return r},updateVertices(e,t,r=0){const s=mt(),n=t.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);s.HEAPF32.set(t,ut/4),s.geometry_updateVertices(e,ut,n,r)},release(e){e>0&&mt().geometry_release(e)},isValid:e=>!(!ct||e<=0)&&ct.geometry_isValid(e),createQuad(e=1,t=1){const r=e/2,s=t/2;return _t.create({vertices:new Float32Array([-r,-s,0,0,r,-s,1,0,r,s,1,1,-r,s,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const r=[],s=[];r.push(0,0,.5,.5);for(let s=0;s<=t;s++){const n=s/t*Math.PI*2,o=Math.cos(n)*e,i=Math.sin(n)*e,a=(Math.cos(n)+1)/2,l=(Math.sin(n)+1)/2;r.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return _t.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,r=1/0,s=-1/0,n=-1/0;for(const o of e)t=Math.min(t,o.x),r=Math.min(r,o.y),s=Math.max(s,o.x),n=Math.max(n,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-r)/(n-r);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return _t.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 gt=null;function xt(e){gt=e}function yt(){gt&&vt.isInitialized()&&vt.shutdown(),gt=null}function wt(){if(!gt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return gt}const vt={init:(e,t)=>wt().postprocess_init(e,t),shutdown(){wt().postprocess_shutdown()},resize(e,t){wt().postprocess_resize(e,t)},addPass:(e,t)=>wt().postprocess_addPass(e,t),removePass(e){wt().postprocess_removePass(e)},setEnabled(e,t){wt().postprocess_setPassEnabled(e,t)},isEnabled:e=>wt().postprocess_isPassEnabled(e),setUniform(e,t,r){wt().postprocess_setUniformFloat(e,t,r)},setUniformVec4(e,t,r){wt().postprocess_setUniformVec4(e,t,r.x,r.y,r.z,r.w)},begin(){wt().postprocess_begin()},end(){wt().postprocess_end()},getPassCount:()=>wt().postprocess_getPassCount(),isInitialized:()=>!!gt&&gt.postprocess_isInitialized(),setBypass(e){wt().postprocess_setBypass(e)},isBypassed:()=>!gt||gt.postprocess_isBypassed(),createBlur:()=>Be.createShader(bt,"#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:()=>Be.createShader(bt,"#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:()=>Be.createShader(bt,"#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:()=>Be.createShader(bt,"#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")},bt="#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 St;exports.RenderStage=void 0,(St=exports.RenderStage||(exports.RenderStage={}))[St.Background=0]="Background",St[St.Opaque=1]="Opaque",St[St.Transparent=2]="Transparent",St[St.Overlay=3]="Overlay";let Pt=null,Ct=0;function Tt(e){Pt=e,Ct=Pt._malloc(64)}function At(){Pt&&Ct&&(Pt._free(Ct),Ct=0),Pt=null}const Et={init(e,t){Pt?.renderer_init(e,t)},resize(e,t){Pt?.renderer_resize(e,t)},begin(e,t){Pt&&Ct&&(Pt.HEAPF32.set(e,Ct/4),Pt.renderer_begin(Ct,t??0))},flush(){Pt?.renderer_flush()},end(){Pt?.renderer_end()},submitSprites(e){Pt&&Pt.renderer_submitSprites(e._cpp)},submitBitmapText(e){Pt&&Pt.renderer_submitBitmapText(e._cpp)},submitSpine(e){Pt&&Pt.renderer_submitSpine?.(e._cpp)},setStage(e){Pt?.renderer_setStage(e)},createRenderTarget:(e,t,r=1)=>Pt?.renderer_createTarget(e,t,r)??0,releaseRenderTarget(e){Pt?.renderer_releaseTarget(e)},getTargetTexture:e=>Pt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Pt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,r,s){Pt?.renderer_setClearColor?.(e,t,r,s)},setViewport(e,t,r,s){Pt?.renderer_setViewport(e,t,r,s)},setScissor(e,t,r,s,n){Pt?.renderer_setScissor(e,t,r,s,n)},clearBuffers(e){Pt?.renderer_clearBuffers(e)},getStats:()=>Pt?{drawCalls:Pt.renderer_getDrawCalls(),triangles:Pt.renderer_getTriangles(),sprites:Pt.renderer_getSprites(),text:Pt.renderer_getText(),spine:Pt.renderer_getSpine?.()??0,meshes:Pt.renderer_getMeshes(),culled:Pt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Mt=null;function Rt(e){Mt=e}function Ft(){Mt=null}const Bt={enable(){Mt?.gl_enableErrorCheck(!0)},disable(){Mt?.gl_enableErrorCheck(!1)},check:e=>Mt?.gl_checkErrors(e)??0,diagnose(){Mt?.renderer_diagnose()}},Ut=new Map;function It(e){Ut.delete(e)}class Dt{constructor(){this.spineRenderer_=null,this.lastWidth_=0,this.lastHeight_=0}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:r,width:s,height:n,elapsed:o}=e;s===this.lastWidth_&&n===this.lastHeight_||(Et.resize(s,n),vt.isInitialized()&&vt.getPassCount()>0&&vt.resize(s,n),this.lastWidth_=s,this.lastHeight_=n),Et.setViewport(0,0,s,n),Et.clearBuffers(3),Et.begin(r),Et.submitSprites(t),Et.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Et.submitSpine(t),Et.flush(),this.executeDrawCallbacks(r,o),Et.end()}renderCamera(e){const{registry:t,viewProjection:r,viewportPixels:s,clearFlags:n,elapsed:o}=e;Et.setViewport(s.x,s.y,s.w,s.h),Et.setScissor(s.x,s.y,s.w,s.h,!0),Et.clearBuffers(n),Et.setScissor(0,0,0,0,!1),Et.begin(r),Et.submitSprites(t),Et.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Et.submitSpine(t),Et.flush(),this.executeDrawCallbacks(r,o),Et.end()}executeDrawCallbacks(e,t){const r=Ut;if(r.size>0){ot.begin(e);const s=[];for(const[e,n]of r.entries())try{n(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}ot.end();for(const e of s)It(e)}}}class Wt{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=a(),t=e-this.lastTime_;this.lastTime_=e;const r=t/1e3;for(this.updateTime(r),this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=r;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate);this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),requestAnimationFrame(this.mainLoop)},this.world_=new fe,this.resources_=new Q;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Wt}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 le(this.world_,this.resources_),this.resources_.insert(Z,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1,Ft(),At(),yt(),ft(),Re(),rt()}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(Z);t.delta=e,t.elapsed+=e,t.frameCount++}}const kt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function zt(e,t,r,s,n){const o=e*t/r,i=e;switch(s){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=n;return Math.pow(o,1-e)*Math.pow(i,e)}}}function $t(e,t,r,s,n,o){const i=new Float32Array(16),a=t-e,l=s-r,c=o-n;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+r)/l,i[14]=-(o+n)/c,i[15]=1,i}function Lt(e,t,r,s){const n=new Float32Array(16),o=1/Math.tan(e/2),i=r-s;return n[0]=o/t,n[5]=o,n[10]=(s+r)/i,n[11]=-1,n[14]=2*s*r/i,n}function Ht(e,t,r){const s=new Float32Array(16);return s[0]=1,s[5]=1,s[10]=1,s[15]=1,s[12]=-e,s[13]=-t,s[14]=-r,s}function Ot(e,t){const r=new Float32Array(16);for(let s=0;s<4;s++)for(let n=0;n<4;n++)r[4*n+s]=e[0+s]*t[4*n+0]+e[4+s]*t[4*n+1]+e[8+s]*t[4*n+2]+e[12+s]*t[4*n+3];return r}async function Nt(e,t){if(t)return t();return(0,(await import(e)).default)()}const Vt=q({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),jt=q(null,"PhysicsAPI");function Gt(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Xt(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Yt{constructor(e,t={},r){this.wasmUrl_=e,this.factory_=r,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Vt,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,r=new Map,s=Nt(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const n=function(e){const t=e.world.getEntitiesWithComponents([L]);for(const r of t){const t=e.world.get(r,L);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/n,i=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,ie([K(Z)],a=>{const l=i.getEntitiesWithComponents([S,W,k]),c=new Set;for(const n of l){c.add(n);const a=i.get(n,S),l=i.get(n,k);if(t.has(n)){const e=r.get(n);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(n,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=Gt(l.rotation);s._physics_createBody(n,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),qt(e,s,n),t.add(n),r.set(n,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===A.Kinematic){const e=Gt(l.rotation);s._physics_setBodyTransform(n,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),r.delete(e));s._physics_step(a.delta),function(e,t,r){const s=t._physics_getDynamicBodyCount();if(0===s)return;const n=t._physics_getDynamicBodyTransforms(),o=n>>2;for(let n=0;n<s;n++){const s=o+4*n,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*r,l=t.HEAPF32[s+2]*r,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,W);if(!u)continue;let h=a,d=l,p=c;if(e.world.has(i,O)){const t=e.world.get(i,O);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,k)){const r=e.world.get(t.entity,k),s=Gt(r.rotation),n=a-r.position.x,o=l-r.position.y,i=Math.cos(-s),u=Math.sin(-s);h=(n*i-o*u)/(0!==r.scale.x?r.scale.x:1),d=(n*u+o*i)/(0!==r.scale.y?r.scale.y:1),p=c-s}}u.position.x=h,u.position.y=d;const f=Xt(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,W,u)}}(e,s,n),function(e,t,r){t._physics_collectEvents();const s=[],n=t._physics_getCollisionEnterCount();if(n>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<n;o++){const n=e+6*o;s.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1],normalX:t.HEAPF32[n+2],normalY:t.HEAPF32[n+3],contactX:t.HEAPF32[n+4]*r,contactY:t.HEAPF32[n+5]*r})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let r=0;r<i;r++){const s=e+2*r;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let r=0;r<l;r++){const s=e+2*r;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let r=0;r<u;r++){const s=e+2*r;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Vt,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,n)},{name:"PhysicsSystem"})),e.__physicsModule=s,e.insertResource(jt,Kt._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=s}}function qt(e,t,r){const s=e.world;if(s.has(r,P)){const e=s.get(r,P);return void t._physics_addBoxShape(r,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(r,C)){const e=s.get(r,C);return void t._physics_addCircleShape(r,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(r,T)){const e=s.get(r,T);t._physics_addCapsuleShape(r,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Kt{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(Kt.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 Jt(e,t,r=!0){const s=e.getResourceManager(),n=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,n);const o=s.createTexture(t.width,t.height,n,t.pixels.length,1,r);return e._free(n),o}function Qt(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function Zt(e,t,r,s){const n=e.scale.x*t*(r?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,h=a+a,d=l+l,p=c+c,f=a*h,m=a*d,_=a*p,g=l*d,x=l*p,y=c*p,w=u*h,v=u*d,b=u*p;return new Float32Array([(1-(g+y))*n,(m+b)*n,(_-v)*n,0,(m-b)*o,(1-(f+y))*o,(x+w)*o,0,(_+v)*i,(x-w)*i,(1-(f+g))*i,0,e.position.x,e.position.y,e.position.z,1])}async function er(e,t,r,s,n,o,i){const a=await async function(e,t,r){const s={};for(const n of t.entities)for(const t of n.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const n=t.data.texture;if(void 0!==s[n])continue;try{s[n]=Jt(e,await r.loadPixels(n))}catch{s[n]=0}}return s}(t,r,s);!function(e,t,r){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const n=r[e];if(n&&n>0){const r=t.textureMetadata[e];if(r?.sliceBorder){const e=r.sliceBorder;s.setTextureMetadata(n,e.left,e.right,e.top,e.bottom)}}}}(t,r,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,r,s,n){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=n.resolvePath(i),c=n.resolvePath(a);try{const s=n.readText(a),u=l.endsWith(".skel");let 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),r=(new TextEncoder).encode(e);d=r.length,h=t._malloc(d+1),t.HEAPU8.set(r,h),t.HEAPU8[h+d]=0}const p=r.loadSkeleton(h,d,s,s.length,u);if(t._free(h),p<0)continue;o[i]=p;const f=Qt(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const s=m+"/"+f[t];try{const o=n.loadPixelsRaw?await n.loadPixelsRaw(s):await n.loadPixels(s),i=Jt(e,o,!1),a=e.getResourceManager().getTextureGLId(i);r.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,n,c,r,s)),o){new Yt("",{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 r={},s={};for(const n of e.entities)for(const e of n.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const n=e.data.material;if(void 0===r[n])try{const e=JSON.parse(t.readText(n));if(!e.vertexSource||!e.fragmentSource){r[n]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=Be.createShader(e.vertexSource,e.fragmentSource),s[o]=i),r[n]=Be.createFromAsset(e,i)}catch{r[n]=0}}return r}(r,s),h=Oe(e.world,r);if(function(e,t,r,s){for(const n of t.entities){const t=s.get(n.id);if(void 0!==t)for(const s of n.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const n=e.get(t,z);n&&(n.texture=r[s.data.texture]||0,e.insert(t,z,n))}}}(e.world,r,a,h),function(e,t,r,s){for(const n of t.entities){const t=s.get(n.id);if(void 0!==t)for(const s of n.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const n=r[s.data.material]||0;if(n)if("Sprite"===s.type){const r=e.get(t,z);r&&(r.material=n,e.insert(t,z,r))}else if("SpineAnimation"===s.type){const r=e.get(t,j);r&&(r.material=n,e.insert(t,j,r))}}}}(e.world,r,u,h),n&&c){const s=function(e,t,r,s){const n={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=r[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(n[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return n}(c,r,l,h);!function(e,t,r,s,n){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in n){const o=Number(e),i=n[e],a=c.has(o,j)?c.get(o,j):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&s.update(i,l*h);let d=0;if(c.has(o,k)){const e=Zt(c.get(o,k),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const p=s.getMeshBatchCount(i);for(let e=0;e<p;e++){const n=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!n||!o)continue;const a=8*n*4,l=2*o,c=r._malloc(a),u=r._malloc(l),h=r._malloc(4),p=r._malloc(4);s.getMeshBatchData(i,e,c,u,h,p);const f=r.HEAPU32[h>>2],m=r.HEAPU32[p>>2],_=new Float32Array(r.HEAPF32.buffer,c,8*n),g=new Uint16Array(r.HEAPU8.buffer,u,o),x=t._malloc(a),y=t._malloc(l);t.HEAPF32.set(_,x>>2),new Uint16Array(t.HEAPU8.buffer,y,o).set(g),t.renderer_submitTriangles(x,n,y,o,f,m,d),t._free(x),t._free(y),r._free(c),r._free(u),r._free(h),r._free(p)}d&&t._free(d)}})}(e,t,n,c,s)}}class tr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,r=new Set;for(const s of e.entities)for(const e of s.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,n=e.data.atlasPath;s&&(s.endsWith(".skel")?r.add(s):t.add(s)),n&&t.add(n)}"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 r)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),r=await fetch(t),s=await r.blob(),n=await createImageBitmap(s),o=new OffscreenCanvas(n.width,n.height).getContext("2d");o.drawImage(n,0,0);const i=o.getImageData(0,0,n.width,n.height);return n.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const rr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),r=Et.createRenderTarget(e.width,e.height,t);return{_handle:r,textureId:Et.getTargetTexture(r),width:e.width,height:e.height}},release(e){Et.releaseRenderTarget(e._handle)},resize:(e,t,r)=>(Et.releaseRenderTarget(e._handle),rr.create({width:t,height:r,depth:!0})),begin(e,t){Et.begin(t,e._handle)},end(){Et.end()},getDepthTexture:e=>Et.getTargetDepthTexture(e._handle)};let sr=!1;var nr;y||(y=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const r="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},n=await l(r,s);return{ok:n.ok,status:n.status,statusText:n.statusText,headers:new Headers(n.headers),json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:r}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return c(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),r=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);n<128?r[s++]=n:n<2048?(r[s++]=192|n>>6,r[s++]=128|63&n):n>=55296&&n<=56319?(n=e.charCodeAt(++t)-56320+(n-55296<<10)+65536,r[s++]=240|n>>18,r[s++]=128|n>>12&63,r[s++]=128|n>>6&63,r[s++]=128|63&n):(r[s++]=224|n>>12,r[s++]=128|n>>6&63,r[s++]=128|63&n)}return r.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let r="";for(let e=0;e<t.length;){const s=t[e];if(s<128)r+=String.fromCharCode(s),e++;else if(192==(224&s))r+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))r+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const n=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;r+=String.fromCharCode(55296+(n>>10),56320+(1023&n)),e+=4}}return r}})}(),console.log("[ESEngine] WeChat platform initialized")),e=nr=w,console.log(`[ESEngine] Platform: ${nr.name}`),exports.App=Wt,exports.AssetPlugin=Ye,exports.AssetServer=Ge,exports.Assets=Xe,exports.AsyncCache=je,exports.BitmapText=V,exports.BodyType=A,exports.BoxCollider=P,exports.Camera=$,exports.Canvas=L,exports.CapsuleCollider=T,exports.Children=N,exports.CircleCollider=C,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=se,exports.Draw=ot,exports.EntityCommands=re,exports.GLDebug=Bt,exports.Geometry=_t,exports.INVALID_ENTITY=0,exports.INVALID_FONT=0,exports.INVALID_TEXTURE=v,exports.Input=ue,exports.InputPlugin=he,exports.InputState=ce,exports.LocalTransform=W,exports.Material=Be,exports.MaterialLoader=He,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=G,exports.Parent=O,exports.Physics=Kt,exports.PhysicsEvents=Vt,exports.PhysicsPlugin=Yt,exports.PostProcess=vt,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 r(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new tr(this.baseUrl_);await s.prefetch(t);let n=null;const o=this.app_.__spineInitPromise;if(o){n=(await o).controller.raw}await er(this.app_,this.app_.wasmModule,t,s,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 r=e.getEntitiesWithComponents([$]);for(const s of r){if(e.get(s,$).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,r=1920/1080;const s=e.getEntitiesWithComponents([L]);for(const n of s){const s=e.get(n,L);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,r=s.designResolution.x/s.designResolution.y;break}}const n=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(n,W,o);const i={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:r,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3};e.insert(n,$,i)}}},exports.Query=function(...e){return function(e,t=[],r=[]){const s=[];return e.forEach((e,t)=>{ee(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:r}}(e)},exports.QueryInstance=te,exports.RenderPipeline=Dt,exports.RenderTexture=rr,exports.Renderer=Et,exports.Res=K,exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.RigidBody=S,exports.ShaderSources=Le,exports.SpineAnimation=j,exports.Sprite=z,exports.SystemRunner=le,exports.Text=xe,exports.TextPlugin=ve,exports.TextRenderer=ye,exports.Time=Z,exports.UIRect=we,exports.Velocity=H,exports.WebAssetProvider=tr,exports.World=fe,exports.WorldTransform=k,exports.addStartupSystem=function(e){ae().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){ae().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){ae().push({schedule:e,system:t})},exports.assetPlugin=qe,exports.clearDrawCallbacks=function(){Ut.clear()},exports.clearUserComponents=function(){R().clear()},exports.color=(e=1,t=1,r=1,s=1)=>({r:e,g:t,b:r,a:s}),exports.createWebApp=function(e,t){const r=Wt.new(),s=new e.Registry;r.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),tt(e),Me(e),pt(e),xt(e),Tt(e),Rt(e);const n=new Dt;r.pipeline_=n;let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),l={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:r}=i(),l=e.registry_getCanvasEntity(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;Et.setClearColor(e.r,e.g,e.b,e.a)}const c=(a()-o)/1e3;Et.resize(t,r),vt.isInitialized()&&vt.getPassCount()>0&&!vt.isBypassed()&&vt.resize(t,r);const u=function(e,t,r,s){const n=e.registry_getCameraEntities(t);if(0===n.length)return[];const o=function(e,t){const r=e.registry_getCanvasEntity(t);return r<0?null:t.getCanvas(r)}(e,t),i=[];for(const e of n){const n=t.getCamera(e),a=t.getLocalTransform(e),l={x:n.viewportX,y:n.viewportY,w:n.viewportW,h:n.viewportH},c=l.w*r/(l.h*s);let u;if(1===n.projectionType){let e=n.orthoSize;if(o){e=zt(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}const t=e*c;u=$t(-t,t,-e,e,-n.farPlane,n.farPlane)}else u=Lt(n.fov*Math.PI/180,c,n.nearPlane,n.farPlane);const h=Ht(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:Ot(u,h),viewportRect:l,clearFlags:n.clearFlags,priority:n.priority})}return i.sort((e,t)=>e.priority-t.priority),i}(e,s,t,r);if(0===u.length)n.render({registry:{_cpp:s},viewProjection:kt,width:t,height:r,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)*r),l=Math.round(o.w*t),u=Math.round(o.h*r);n.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}Et.setViewport(0,0,t,r)}}};return r.addSystemToSchedule(exports.Schedule.Last,l),r.addPlugin(qe),r.addPlugin(de),r.addPlugin(be),r},exports.defineComponent=F,exports.defineResource=q,exports.defineSystem=ie,exports.defineTag=function(e){const t=R(),r=t.get(e);if(r)return r;const s=M(e,{});return t.set(e,s),U(e,{},!0),s},exports.findEntityByName=function(e,t){const r=e.getEntitiesWithComponents([G]);for(const s of r){const r=e.get(s,G);if(r&&r.value===t)return s}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const r of t)e.addSystemToSchedule(r.schedule,r.system);t.length=0}},exports.getComponentDefaults=function(e){const t=X[e];if(t)return{...t._default};const r=B(e);return r?{...r._default}:null},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=B,exports.initDrawAPI=tt,exports.initGLDebugAPI=Rt,exports.initGeometryAPI=pt,exports.initMaterialAPI=Me,exports.initPostProcessAPI=xt,exports.initRendererAPI=Tt,exports.inputPlugin=de,exports.isBuiltinComponent=D,exports.isEditor=function(){return sr},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!sr},exports.isTextureRef=Pe,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=Ve,exports.loadPhysicsModule=Nt,exports.loadRuntimeScene=er,exports.loadSceneData=Oe,exports.loadSceneWithAssets=Ne,exports.platformFetch=r,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,r){return t().instantiateWasm(e,r)},exports.platformReadFile=s,exports.platformReadTextFile=n,exports.quat=(e=1,t=0,r=0,s=0)=>({w:e,x:t,y:r,z:s}),exports.registerDrawCallback=function(e,t){Ut.set(e,t)},exports.registerEmbeddedAssets=function(e,t){const r=e.getResource(Xe);r&&r.registerEmbeddedAssets(t)},exports.registerMaterialCallback=$e,exports.setEditorMode=function(e){sr=e},exports.shutdownDrawAPI=rt,exports.shutdownGLDebugAPI=Ft,exports.shutdownGeometryAPI=ft,exports.shutdownMaterialAPI=Re,exports.shutdownPostProcessAPI=yt,exports.shutdownRendererAPI=At,exports.textPlugin=be,exports.unregisterDrawCallback=It,exports.updateCameraAspectRatio=function(e,t){const r=e.getEntitiesWithComponents([$]);for(const s of r){const r=e.get(s,$);r&&(r.aspectRatio=t,e.insert(s,$,r))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,r=0)=>({x:e,y:t,z:r}),exports.vec4=(e=0,t=0,r=0,s=1)=>({x:e,y:t,z:r,w:s}),exports.wxFileExists=f,exports.wxFileExistsSync=function(e){const t=h();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=x,exports.wxLoadImage=g,exports.wxLoadImagePixels=async function(e){return x(await g(e))},exports.wxReadFile=d,exports.wxReadTextFile=p,exports.wxWriteFile=function(e,t){return new Promise((r,s)=>{h().writeFile({filePath:e,data:t,success:()=>r(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};
//# sourceMappingURL=index.wechat.cjs.js.map
diff --git a/desktop/public/sdk/cjs/index.wechat.js b/desktop/public/sdk/cjs/index.wechat.js
index ee6ef7352..d9848cd9b 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 r(){return e?.name??null}function s(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(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,r)=>{const s=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===s?"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];n({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,n="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(n).buffer)}})},fail:e=>{r(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 _=null;function m(){return _||(_=wx.getFileSystemManager()),_}function g(e){return new Promise((t,n)=>{m().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,r)=>{m().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function w(e){return new Promise(t=>{m().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function x(e){const t=m();try{return t.accessSync(e),!0}catch{return!1}}function v(e,t){return new Promise((n,r)=>{m().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{r(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}let b=null,P=null;function S(e){return new Promise((t,n)=>{const r=wx.createImage();r.onload=()=>t(r),r.onerror=t=>n(new Error(`Failed to load image: ${e}, ${t}`)),r.src=e})}function C(e){const{width:t,height:n}=e,{ctx:r}=function(e,t){return b||(b=wx.createCanvas(),b.width=e,b.height=t,P=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:P}}(t,n);r.clearRect(0,0,t,n),r.drawImage(e,0,0);const s=r.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(s.data.buffer)}}async function E(e){return C(await S(e))}let T=!1;const A=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return g(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)})}},M=0,R=4294967295,U=(e=0,t=0)=>({x:e,y:t}),F=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),B=(e=0,t=0,n=0,r=1)=>({x:e,y:t,z:n,w:r}),I=(e=1,t=1,n=1,r=1)=>({r:e,g:t,b:n,a:r}),W=(e=1,t=0,n=0,r=0)=>({w:e,x:t,y:n,z:r});function k(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const D=k("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),z=k("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),$=k("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),L=k("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),H={Static:0,Kinematic:1,Dynamic:2};let O=0;function N(e,t){const n=++O;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function j(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function V(e,t){const n=j(),r=n.get(e);if(r)return r;const s=N(e,t);return n.set(e,s),q(e,t,!1),s}function X(e){const t=j(),n=t.get(e);if(n)return n;const r=N(e,{});return t.set(e,r),q(e,{},!0),r}function G(e){return j().get(e)}function Y(){j().clear()}function q(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 J(e){return!0===e._builtin}const Q=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}}),Z=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}}),ee=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}),te=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}),ne=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}}),se=K("Parent",{entity:0}),ie=K("Children",{entities:[]}),oe=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}),ae={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},ce={LocalTransform:Q,WorldTransform:Z,Sprite:ee,Camera:te,Canvas:ne,Velocity:re,Parent:se,Children:ie,SpineAnimation:oe,RigidBody:D,BoxCollider:z,CircleCollider:$,CapsuleCollider:L};function le(e){const t=ce[e];if(t)return{...t._default};const n=G(e);return n?{...n._default}:null}let ue=0;function he(e,t){const n=++ue;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function de(e){return{_type:"res",_resource:e}}function fe(e){return{_type:"res_mut",_resource:e}}class pe{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}}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 pe(this.get(e),t=>this.set(e,t))}}const me=he({delta:0,elapsed:0,frameCount:0},"Time");function ge(e){return{_type:"mut",_component:e}}function ye(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function we(...e){return function(e,t=[],n=[]){const r=[];return e.forEach((e,t)=>{ye(e)&&r.push(t)}),{_type:"query",_components:e,_mutIndices:r,_with:t,_without:n}}(e)}class xe{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return ye(e)?e._component:e}commitPending(){for(const e of this.pendingMutations_)this.world_.insert(e.entity,e.component,e.data);this.pendingMutations_=[]}*[Symbol.iterator](){const{_components:e,_mutIndices:t,_with:n,_without:r}=this.descriptor_,s=e.map(e=>this.getActualComponent(e)),i=[...s,...n],o=this.world_.getEntitiesWithComponents(i);let a=null,c=[];try{for(const e of o){if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data);c=[];let n=!1;for(const t of r)if(this.world_.has(e,t)){n=!0;break}if(n)continue;const i=s.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:s[e],data:i[e]});a=e,yield[e,...i]}}finally{if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.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(){return[...this]}}function ve(){return{_type:"commands"}}class be{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=J(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Pe{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new be(this,null);return this.spawned_.push(e),e}entity(e){return new be(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];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 Se;!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"}(Se||(Se={}));let Ce=0;function Ee(e,t,n){const r=++Ce;return{_id:Symbol(`System_${r}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${r}`}}function Te(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Ae(e){Te().push({schedule:Se.Update,system:e})}function Me(e){Te().push({schedule:Se.Startup,system:e})}function Re(e,t){Te().push({schedule:e,system:t})}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 Pe&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new xe(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Pe(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Fe{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const Be=he(new Fe,"Input");class Ie{constructor(e){this.target_=e??null}build(e){const n=new Fe;e.insertResource(Be,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,r){n.mouseX=t,n.mouseY=r,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(Se.First,Ee([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const We=new Ie;function ke(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 r=t[e];n[e]=null==r||"object"!=typeof r||Array.isArray(r)?r:ke(r)}return n}class De{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}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 J(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return J(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return J(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){J(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const r={...t._default,...n};if(this.cppRegistry_){const n=`add${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e,ke(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 r=t.create(n);return this.getStorage(t).set(e,r),r}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e)}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();const t=[];for(const n of this.entities_){let r=!0;for(const t of e)if(!this.has(n,t)){r=!1;break}r&&t.push(n)}return t}}var ze,$e,Le;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(ze||(ze={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}($e||($e={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Le||(Le={}));const He=V("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:ze.Left,verticalAlign:$e.Top,wordWrap:!0,overflow:Le.Visible,lineHeight:1.2,dirty:!0});class Oe{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,r=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const s=t&&t.size.x>0&&t.size.y>0,i=s?t.size.x:0,o=s?t.size.y:0,a=e.wordWrap&&s;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=s?Math.ceil(i):h+2*u,p=s?Math.ceil(o):d+2*u;if(s&&e.overflow===Le.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}if(r.width<f||r.height<p){const e=Math.max(r.width,this.nextPowerOf2(f)),t=Math.max(r.height,this.nextPowerOf2(p));r.width=e,r.height=t}const _=Math.round(255*e.color.r),m=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,r.width,r.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${_}, ${m}, ${g}, ${y})`,s&&e.overflow===Le.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=c.length*l;let x;if(s)switch(e.verticalAlign){case $e.Top:x=u;break;case $e.Middle:x=(p-w)/2;break;case $e.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let r;switch(e.align){case ze.Left:r=u;break;case ze.Center:r=f/2;break;case ze.Right:r=f-u;break;default:r=u}n.fillText(t,r,v),v+=l}s&&e.overflow===Le.Clip&&n.restore();const b=n.getImageData(0,0,f,p),P=new Uint8Array(b.data.buffer),S=this.module.getResourceManager(),C=this.module._malloc(P.length);this.module.HEAPU8.set(P,C);const E=S.createTexture(f,p,C,P.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 r=this.cache.get(e);if(r){this.module.getResourceManager().releaseTexture(r.textureHandle)}const s=this.renderText(t,n);return this.cache.set(e,s),s}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)}}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"),r=[];for(const e of n){if(!e){r.push("");continue}let n="";for(const s of e){const e=n+s;this.ctx.measureText(e).width>t&&n?(r.push(n),n=s):n=e}n&&r.push(n)}return r.length>0?r:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),r=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,r)}return t}mapAlign(e){switch(e){case ze.Left:return"left";case ze.Center:return"center";case ze.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const Ne=V("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class je{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Oe(t),r=e.world;e.addSystemToSchedule(Se.PreUpdate,Ee([],()=>{const e=r.getEntitiesWithComponents([He]);for(const t of e){const e=r.get(t,He);if(!e.dirty)continue;r.has(t,ee)||r.insert(t,ee,{texture:R,size:{x:0,y:0},color:{r:1,g:1,b:1,a:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const s=r.has(t,Ne)?r.get(t,Ne):null,i=n.renderForEntity(t,e,s),o=r.get(t,ee);o.texture=i.textureHandle,o.size={x:i.width,y:i.height},o.uvOffset={x:0,y:0},o.uvScale={x:1,y:1},r.insert(t,ee,o),e.dirty=!1}}))}}const Ve=new je;var Xe;function Ge(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"}(Xe||(Xe={}));let Ye=null,qe=null,Ke=1;const Je=new Map;function Qe(e){Ye=e,qe=e.getResourceManager(),ct()}function Ze(){0!==rt&&Ye&&(Ye._free(rt),rt=0),Je.clear(),Ke=1,nt=!1,qe=null,Ye=null}function et(){if(!qe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return qe}const tt={createShader:(e,t)=>et().createShader(e,t),releaseShader(e){e>0&&et().releaseShader(e)},create(e){const t=Ke++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Xe.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,r]of Object.entries(e.uniforms))n.uniforms.set(t,r);return Je.set(t,n),t},get:e=>Je.get(e),setUniform(e,t,n){const r=Je.get(e);r&&r.uniforms.set(t,n)},getUniform(e,t){const n=Je.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Je.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Je.get(e);return t?.blendMode??Xe.Normal},setDepthTest(e,t){const n=Je.get(e);n&&(n.depthTest=t)},getShader(e){const t=Je.get(e);return t?.shader??0},release(e){Je.delete(e)},isValid:e=>Je.has(e),createFromAsset(e,t){const n={};for(const[t,r]of Object.entries(e.properties))if("number"==typeof r)n[t]=r;else if("object"==typeof r&&null!==r){const e=r;"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??Xe.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Je.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Ke++,r={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Je.set(n,r),n},toAssetData(e,t){const n=Je.get(e);if(!n)return null;const r={};for(const[e,t]of n.uniforms)r[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:r}},getUniforms(e){const t=Je.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let nt=!1,rt=0;const st=4096,it=new Map,ot=new TextEncoder;function at(e){const t=(0===rt&&Ye&&(rt=Ye._malloc(st)),rt);if(0===t||!Ye)return{ptr:0,count:0};let n=0,r=0;const s=Ye.HEAPU8,i=Ye.HEAPU32,o=Ye.HEAPF32;for(const[a,c]of e){if(n+128>st)break;let e=it.get(a);e||(e=ot.encode(a),it.set(a,e));const l=e.length,u=4*Math.ceil(l/4);i[t+n>>2]=l,n+=4,s.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof c)h=0,d[0]=c;else if(Array.isArray(c)){h=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(h=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(h=2,d=[c.x,c.y,c.z,0]):"y"in c&&(h=1,d=[c.x,c.y,0,0]);i[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=d[e],n+=4;r++}return{ptr:t,count:r}}function ct(){if(!Ye||nt)return;Ye.materialDataProvider=(e,t,n,r,s)=>{const i=Je.get(e);if(!i)return Ye.HEAPU32[t>>2]=0,Ye.HEAPU32[n>>2]=0,Ye.HEAPU32[r>>2]=0,void(Ye.HEAPU32[s>>2]=0);Ye.HEAPU32[t>>2]=i.shader,Ye.HEAPU32[n>>2]=i.blendMode;const{ptr:o,count:a}=at(i.uniforms);Ye.HEAPU32[r>>2]=o,Ye.HEAPU32[s>>2]=a},nt=!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 ut{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 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&&(tt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())tt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const n=await c(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const r=JSON.parse(n);if("material"!==r.type)throw new Error(`Invalid material file type: ${r.type}`);const s=this.resolveShaderPath(e,r.shader),i=await this.shaderLoader_.load(s);return{handle:tt.createFromAsset(r,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function ht(e,t){const n=new Map;for(const r of t.entities){const t=e.spawn();n.set(r.id,t),e.insert(t,ae,{value:r.name});for(const n of r.components)ft(e,t,n)}for(const r of t.entities)if(null!==r.parent){const t=n.get(r.id),s=n.get(r.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}return n}async function dt(e,t,n){const r=new Map,s=n?.assetServer,i=new Map;for(const o of t.entities){const t=e.spawn();r.set(o.id,t),e.insert(t,ae,{value:o.name});for(const r of o.components){if("Sprite"===r.type&&s){const e=r.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,r=t.startsWith("data:")?t:n?.assetBaseUrl?`${n.assetBaseUrl}/${t}`:`/${t}`;try{const n=await s.loadTexture(r);e.texture=n.handle,i.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 s.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("SpineAnimation"===r.type&&s){const e=r.data,t=e.skeletonPath,i=e.atlasPath;if(t&&i){const e=await s.loadSpine(t,i,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}ft(e,t,r)}}for(const n of t.entities)if(null!==n.parent){const t=r.get(n.id),s=r.get(n.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}function ft(e,t,n){const r=n.data;switch(n.type){case"LocalTransform":e.insert(t,Q,r);break;case"Sprite":e.insert(t,ee,r);break;case"Camera":e.insert(t,te,r);break;case"Canvas":e.insert(t,ne,r);break;case"Text":e.insert(t,He,r);break;case"SpineAnimation":e.insert(t,oe,r);break;case"UIRect":e.insert(t,Ne,r);break;case"RigidBody":e.insert(t,D,r);break;case"BoxCollider":e.insert(t,z,r);break;case"CircleCollider":e.insert(t,$,r);break;case"CapsuleCollider":e.insert(t,L,r);break;default:{const s=G(n.type);s?e.insert(t,s,r):console.warn(`Unknown component type: ${n.type}`);break}}}function pt(e,t){const n=e.getEntitiesWithComponents([te]);for(const r of n){const n=e.get(r,te);n&&(n.aspectRatio=t,e.insert(r,te,n))}}function _t(e,t){const n=e.getEntitiesWithComponents([ae]);for(const r of n){const n=e.get(r,ae);if(n&&n.value===t)return r}return null}class mt{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 r=this.pending_.get(e);if(r)return r;const s=t();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)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class gt{constructor(e){this.textureCache_=new mt,this.shaderCache_=new mt,this.jsonCache_=new mt,this.textCache_=new mt,this.binaryCache_=new mt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.embedded_=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 ut(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 r=this.textureCacheKey(e,n),s=this.textureCache_.get(r);s&&(t.releaseTexture(s.handle),this.textureCache_.delete(r))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);this.textureCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.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 r=`${e}:${t}`;if(this.loadedSpines_.has(r))return{success:!0};try{const s=this.resolveUrl(t,n),i=await this.fetchText(s);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i);for(const e of a){const t=o?`${o}/${e}`:e,r=this.resolveUrl(t,n);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 c=this.resolveUrl(e,n),l=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);return this.writeToVirtualFS(e,l)?(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 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 dt(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 r of e.textures)n.push(this.loadTexture(r).then(e=>{t.textures.set(r,e)}));if(e.materials)for(const r of e.materials)n.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}`;n.push(this.loadSpine(r.skeleton,r.atlas,r.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const r of e.json)n.push(this.loadJson(r).then(e=>{t.json.set(r,e)}));if(e.text)for(const r of e.text)n.push(this.loadText(r).then(e=>{t.text.set(r,e)}));if(e.binary)for(const r of e.binary)n.push(this.loadBinary(r).then(e=>{t.binary.set(r,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,r=this.embedded_.get(n)??n;return new Promise((n,s)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(i)},i.onerror=()=>s(new Error(`Failed to load image: ${e}`)),i.src=r})}createTextureFromImage(e,t){const{width:n,height:r}=e,s=this.getWebGL2Context();return s?this.createTextureWebGL2(s,e,n,r,t):this.createTextureFallback(e,n,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,n,r,s){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,s?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 o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,r),width:n,height:r}}createTextureFallback(e,t,n,r){(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 s=this.ctx_.getImageData(0,0,t,n),i=new Uint8Array(s.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,n,a,i.length,1,r);return this.module_._free(a),{handle:c,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 r=255/n;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 l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:s}=this.parseEsShader(n);if(!r||!s)throw new Error(`Invalid shader format: ${e}`);return tt.createShader(r,s)}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 c(t);return JSON.parse(n)}const n=await o(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):c(t)}const n=await o(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 o(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 r=n.split("/").filter(e=>e);let s="";for(const e of r){s=s?`${s}/${e}`:e;try{t.analyzePath(s).exists||t.mkdir(s)}catch{try{t.mkdir(s)}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 yt=he(null,"Assets");class wt{build(e){const t=e.wasmModule;t?e.insertResource(yt,new gt(t)):console.warn("AssetPlugin: No WASM module available")}}const xt=new wt;function vt(e,t){const n=e.getResource(yt);n&&n.registerEmbeddedAssets(t)}let bt=null,Pt=0,St=0,Ct=0;const Et=new Float32Array(256);function Tt(e){bt=e,Pt=bt._malloc(64),St=bt._malloc(64),Ct=bt._malloc(1024)}function At(){bt&&(Pt&&(bt._free(Pt),Pt=0),St&&(bt._free(St),St=0),Ct&&(bt._free(Ct),Ct=0)),bt=null}function Mt(){if(!bt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return bt}const Rt={r:1,g:1,b:1,a:1},Ut={begin(e){const t=Mt();t.HEAPF32.set(e,Pt/4),t.draw_begin(Pt)},end(){Mt().draw_end()},line(e,t,n,r=1){Mt().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,r)},rect(e,t,n,r=!0){Mt().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,r)},rectOutline(e,t,n,r=1){Mt().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,r)},circle(e,t,n,r=!0,s=32){Mt().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,r,s)},circleOutline(e,t,n,r=1,s=32){Mt().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,r,s)},texture(e,t,n,r=Rt){Mt().draw_texture(e.x,e.y,t.x,t.y,n,r.r,r.g,r.b,r.a)},textureRotated(e,t,n,r,s=Rt){Mt().draw_textureRotated(e.x,e.y,t.x,t.y,n,r,s.r,s.g,s.b,s.a)},setLayer(e){Mt().draw_setLayer(e)},setDepth(e){Mt().draw_setDepth(e)},getDrawCallCount:()=>bt?bt.draw_getDrawCallCount():0,getPrimitiveCount:()=>bt?bt.draw_getPrimitiveCount():0,setBlendMode(e){Mt().draw_setBlendMode(e)},setDepthTest(e){Mt().draw_setDepthTest(e)},drawMesh(e,t,n){const r=Mt();r.HEAPF32.set(n,St/4),r.draw_mesh(e,t,St)},drawMeshWithMaterial(e,t,n){const r=Mt(),s=tt.get(t);if(!s)return;if(Ut.setBlendMode(s.blendMode),Ut.setDepthTest(s.depthTest),0===s.uniforms.size)return void Ut.drawMesh(e,s.shader,n);r.HEAPF32.set(n,St/4);let i=0,o=0;for(const[e,t]of s.uniforms){const n=Bt(e);if(!(n<0)){if(Ge(t))Et[i++]=10,Et[i++]=n,Et[i++]=t.slot??o++,Et[i++]=t.textureId;else if("number"==typeof t)Et[i++]=1,Et[i++]=n,Et[i++]=t;else if(Array.isArray(t)){Et[i++]=t.length,Et[i++]=n;for(let e=0;e<t.length;e++)Et[i++]=t[e]}else"w"in t?(Et[i++]=4,Et[i++]=n,Et[i++]=t.x,Et[i++]=t.y,Et[i++]=t.z,Et[i++]=t.w):"z"in t?(Et[i++]=3,Et[i++]=n,Et[i++]=t.x,Et[i++]=t.y,Et[i++]=t.z):(Et[i++]=2,Et[i++]=n,Et[i++]=t.x,Et[i++]=t.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==i?(r.HEAPF32.set(Et.subarray(0,i),Ct/4),r.draw_meshWithUniforms(e,s.shader,St,Ct,i)):r.draw_mesh(e,s.shader,St)}},Ft={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 Bt(e){return Ft[e]??-1}var It;!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"}(It||(It={}));let Wt=null,kt=0,Dt=0,zt=0;function $t(e){Wt=e,kt=Wt._malloc(262144),Dt=Wt._malloc(65536),zt=Wt._malloc(256)}function Lt(){Wt&&(kt&&Wt._free(kt),Dt&&Wt._free(Dt),zt&&Wt._free(zt),kt=0,Dt=0,zt=0),Wt=null}function Ht(){if(!Wt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Wt}const Ot={create(e){const t=Ht(),n=t.geometry_create();if(0===n)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,kt/4);const s=e.layout.length,i=new Int32Array(s);for(let t=0;t<s;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,zt,s).set(i),t.geometry_init(n,kt,r,zt,s,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,Dt,r).set(e.indices),t.geometry_setIndices16(n,Dt,r)}else{new Uint32Array(t.HEAPU8.buffer,Dt,r).set(e.indices),t.geometry_setIndices32(n,Dt,r)}}return n},updateVertices(e,t,n=0){const r=Ht(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);r.HEAPF32.set(t,kt/4),r.geometry_updateVertices(e,kt,s,n)},release(e){e>0&&Ht().geometry_release(e)},isValid:e=>!(!Wt||e<=0)&&Wt.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,r=t/2;return Ot.create({vertices:new Float32Array([-n,-r,0,0,n,-r,1,0,n,r,1,1,-n,r,0,1]),layout:[{name:"a_position",type:It.Float2},{name:"a_texCoord",type:It.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],r=[];n.push(0,0,.5,.5);for(let r=0;r<=t;r++){const s=r/t*Math.PI*2,i=Math.cos(s)*e,o=Math.sin(s)*e,a=(Math.cos(s)+1)/2,c=(Math.sin(s)+1)/2;n.push(i,o,a,c)}for(let e=1;e<=t;e++)r.push(0,e,e+1);return Ot.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:It.Float2},{name:"a_texCoord",type:It.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,n=1/0,r=-1/0,s=-1/0;for(const i of e)t=Math.min(t,i.x),n=Math.min(n,i.y),r=Math.max(r,i.x),s=Math.max(s,i.y);const i=[];for(const o of e){const e=(o.x-t)/(r-t),a=(o.y-n)/(s-n);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return Ot.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:It.Float2},{name:"a_texCoord",type:It.Float2}],indices:new Uint16Array(o)})}};let Nt=null;function jt(e){Nt=e}function Vt(){Nt&&Gt.isInitialized()&&Gt.shutdown(),Nt=null}function Xt(){if(!Nt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Nt}const Gt={init:(e,t)=>Xt().postprocess_init(e,t),shutdown(){Xt().postprocess_shutdown()},resize(e,t){Xt().postprocess_resize(e,t)},addPass:(e,t)=>Xt().postprocess_addPass(e,t),removePass(e){Xt().postprocess_removePass(e)},setEnabled(e,t){Xt().postprocess_setPassEnabled(e,t)},isEnabled:e=>Xt().postprocess_isPassEnabled(e),setUniform(e,t,n){Xt().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Xt().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Xt().postprocess_begin()},end(){Xt().postprocess_end()},getPassCount:()=>Xt().postprocess_getPassCount(),isInitialized:()=>!!Nt&&Nt.postprocess_isInitialized(),setBypass(e){Xt().postprocess_setBypass(e)},isBypassed:()=>!Nt||Nt.postprocess_isBypassed(),createBlur:()=>tt.createShader(Yt,"#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:()=>tt.createShader(Yt,"#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:()=>tt.createShader(Yt,"#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:()=>tt.createShader(Yt,"#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")},Yt="#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 qt;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(qt||(qt={}));let Kt=null,Jt=0;function Qt(e){Kt=e,Jt=Kt._malloc(64)}function Zt(){Kt&&Jt&&(Kt._free(Jt),Jt=0),Kt=null}const en={init(e,t){Kt?.renderer_init(e,t)},resize(e,t){Kt?.renderer_resize(e,t)},begin(e,t){Kt&&Jt&&(Kt.HEAPF32.set(e,Jt/4),Kt.renderer_begin(Jt,t??0))},flush(){Kt?.renderer_flush()},end(){Kt?.renderer_end()},submitSprites(e){Kt&&Kt.renderer_submitSprites(e._cpp)},submitSpine(e){Kt&&Kt.renderer_submitSpine?.(e._cpp)},setStage(e){Kt?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Kt?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Kt?.renderer_releaseTarget(e)},getTargetTexture:e=>Kt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Kt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,r){Kt?.renderer_setClearColor?.(e,t,n,r)},setViewport(e,t,n,r){Kt?.renderer_setViewport(e,t,n,r)},setScissor(e,t,n,r,s){Kt?.renderer_setScissor(e,t,n,r,s)},clearBuffers(e){Kt?.renderer_clearBuffers(e)},getStats:()=>Kt?{drawCalls:Kt.renderer_getDrawCalls(),triangles:Kt.renderer_getTriangles(),sprites:Kt.renderer_getSprites(),spine:Kt.renderer_getSpine?.()??0,meshes:Kt.renderer_getMeshes(),culled:Kt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let tn=null;function nn(e){tn=e}function rn(){tn=null}const sn={enable(){tn?.gl_enableErrorCheck(!0)},disable(){tn?.gl_enableErrorCheck(!1)},check:e=>tn?.gl_checkErrors(e)??0,diagnose(){tn?.renderer_diagnose()}},on=new Map;function an(e,t){on.set(e,t)}function cn(e){on.delete(e)}function ln(){on.clear()}class un{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:n,width:r,height:s,elapsed:i}=e;en.resize(r,s),Gt.isInitialized()&&Gt.getPassCount()>0&&!Gt.isBypassed()&&Gt.resize(r,s),en.setViewport(0,0,r,s),en.clearBuffers(3),en.begin(n),en.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,i):en.submitSpine(t),en.flush(),this.executeDrawCallbacks(n,i),en.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:r,clearFlags:s,elapsed:i}=e;en.setViewport(r.x,r.y,r.w,r.h),en.setScissor(r.x,r.y,r.w,r.h,!0),en.clearBuffers(s),en.setScissor(0,0,0,0,!1),en.begin(n),en.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,i):en.submitSpine(t),en.flush(),this.executeDrawCallbacks(n,i),en.end()}executeDrawCallbacks(e,t){const n=on;if(n.size>0){Ut.begin(e);const r=[];for(const[e,s]of n.entries())try{s(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),r.push(e)}Ut.end();for(const e of r)cn(e)}}}class hn{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(Se.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Se.FixedPreUpdate),this.runSchedule(Se.FixedUpdate),this.runSchedule(Se.FixedPostUpdate);this.runSchedule(Se.PreUpdate),this.runSchedule(Se.Update),this.runSchedule(Se.PostUpdate),this.runSchedule(Se.Last),requestAnimationFrame(this.mainLoop)},this.world_=new De,this.resources_=new _e;for(const e of Object.values(Se))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new hn}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(Se.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Se.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(me,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Se.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,rn(),Zt(),Vt(),Lt(),Ze(),At()}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(me);t.delta=e,t.elapsed+=e,t.frameCount++}}function dn(e,t){const n=hn.new(),r=new e.Registry;n.connectCpp(r,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Tt(e),Qe(e),$t(e),jt(e),Qt(e),nn(e);const s=new un;n.pipeline_=s;let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),a={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=o(),a=e.registry_getCanvasEntity(r);if(a>=0){const e=r.getCanvas(a).backgroundColor;en.setClearColor(e.r,e.g,e.b,e.a)}const c=(d()-i)/1e3;en.resize(t,n),Gt.isInitialized()&&Gt.getPassCount()>0&&!Gt.isBypassed()&&Gt.resize(t,n);const l=function(e,t,n,r){const s=e.registry_getCameraEntities(t);if(0===s.length)return[];const i=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),o=[];for(const e of s){const s=t.getCamera(e),a=t.getLocalTransform(e),c={x:s.viewportX,y:s.viewportY,w:s.viewportW,h:s.viewportH},l=c.w*n/(c.h*r);let u;if(1===s.projectionType){let e=s.orthoSize;if(i){e=_n(i.designResolution.y/2,i.designResolution.x/i.designResolution.y,l,i.scaleMode,i.matchWidthOrHeight)}const t=e*l;u=mn(-t,t,-e,e,-s.farPlane,s.farPlane)}else u=gn(s.fov*Math.PI/180,l,s.nearPlane,s.farPlane);const h=yn(a.position.x,a.position.y,a.position.z);o.push({entity:e,viewProjection:wn(u,h),viewportRect:c,clearFlags:s.clearFlags,priority:s.priority})}return o.sort((e,t)=>e.priority-t.priority),o}(e,r,t,n);if(0===l.length)s.render({registry:{_cpp:r},viewProjection:pn,width:t,height:n,elapsed:c});else{for(const e of l){const i=e.viewportRect,o=Math.round(i.x*t),a=Math.round((1-i.y-i.h)*n),l=Math.round(i.w*t),u=Math.round(i.h*n);s.renderCamera({registry:{_cpp:r},viewProjection:e.viewProjection,viewportPixels:{x:o,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}en.setViewport(0,0,t,n)}}};return n.addSystemToSchedule(Se.Last,a),n.addPlugin(xt),n.addPlugin(We),n.addPlugin(Ve),n}function fn(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 pn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function _n(e,t,n,r,s){const i=e*t/n,o=e;switch(r){case 0:return i;case 1:default:return o;case 2:return Math.max(i,o);case 3:return Math.min(i,o);case 4:{const e=s;return Math.pow(i,1-e)*Math.pow(o,e)}}}function mn(e,t,n,r,s,i){const o=new Float32Array(16),a=t-e,c=r-n,l=i-s;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(r+n)/c,o[14]=-(i+s)/l,o[15]=1,o}function gn(e,t,n,r){const s=new Float32Array(16),i=1/Math.tan(e/2),o=n-r;return s[0]=i/t,s[5]=i,s[10]=(r+n)/o,s[11]=-1,s[14]=2*r*n/o,s}function yn(e,t,n){const r=new Float32Array(16);return r[0]=1,r[5]=1,r[10]=1,r[15]=1,r[12]=-e,r[13]=-t,r[14]=-n,r}function wn(e,t){const n=new Float32Array(16);for(let r=0;r<4;r++)for(let s=0;s<4;s++)n[4*s+r]=e[0+r]*t[4*s+0]+e[4+r]*t[4*s+1]+e[8+r]*t[4*s+2]+e[12+r]*t[4*s+3];return n}async function xn(e,t){if(t)return t();return(0,(await import(e)).default)()}const vn=he({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),bn=he(null,"PhysicsAPI");function Pn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Sn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Cn{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(vn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,r=xn(this.wasmUrl_,this.factory_).then(r=>{r._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const s=function(e){const t=e.world.getEntitiesWithComponents([ne]);for(const n of t){const t=e.world.get(n,ne);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/s,o=e.world;e.addSystemToSchedule(Se.PostUpdate,Ee([de(me)],a=>{const c=o.getEntitiesWithComponents([D,Q,Z]),l=new Set;for(const s of c){l.add(s);const a=o.get(s,D),c=o.get(s,Z);if(t.has(s)){const e=n.get(s);!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(s,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 o=Pn(c.rotation);r._physics_createBody(s,a.bodyType,c.position.x*i,c.position.y*i,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),En(e,r,s),t.add(s),n.set(s,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===H.Kinematic){const e=Pn(c.rotation);r._physics_setBodyTransform(s,c.position.x*i,c.position.y*i,e)}}for(const e of t)l.has(e)||(r._physics_destroyBody(e),t.delete(e),n.delete(e));r._physics_step(a.delta),function(e,t,n){const r=t._physics_getDynamicBodyCount();if(0===r)return;const s=t._physics_getDynamicBodyTransforms(),i=s>>2;for(let s=0;s<r;s++){const r=i+4*s,o=t.HEAPU32[r],a=t.HEAPF32[r+1]*n,c=t.HEAPF32[r+2]*n,l=t.HEAPF32[r+3];if(!e.world.valid(o))continue;const u=e.world.get(o,Q);if(!u)continue;let h=a,d=c,f=l;if(e.world.has(o,se)){const t=e.world.get(o,se);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,Z)){const n=e.world.get(t.entity,Z),r=Pn(n.rotation),s=a-n.position.x,i=c-n.position.y,o=Math.cos(-r),u=Math.sin(-r);h=(s*o-i*u)/(0!==n.scale.x?n.scale.x:1),d=(s*u+i*o)/(0!==n.scale.y?n.scale.y:1),f=l-r}}u.position.x=h,u.position.y=d;const p=Sn(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(o,Q,u)}}(e,r,s),function(e,t,n){t._physics_collectEvents();const r=[],s=t._physics_getCollisionEnterCount();if(s>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<s;i++){const s=e+6*i;r.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1],normalX:t.HEAPF32[s+2],normalY:t.HEAPF32[s+3],contactX:t.HEAPF32[s+4]*n,contactY:t.HEAPF32[s+5]*n})}}const i=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<o;n++){const r=e+2*n;i.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1]})}}const a=[],c=t._physics_getSensorEnterCount();if(c>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<c;n++){const r=e+2*n;a.push({sensorEntity:t.HEAPU32[r],visitorEntity:t.HEAPU32[r+1]})}}const l=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const r=e+2*n;l.push({sensorEntity:t.HEAPU32[r],visitorEntity:t.HEAPU32[r+1]})}}e.insertResource(vn,{collisionEnters:r,collisionExits:i,sensorEnters:a,sensorExits:l})}(e,r,s)},{name:"PhysicsSystem"})),e.__physicsModule=r,e.insertResource(bn,Tn._fromModule(r)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=r}}function En(e,t,n){const r=e.world;if(r.has(n,z)){const e=r.get(n,z);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(r.has(n,$)){const e=r.get(n,$);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(r.has(n,L)){const e=r.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 Tn{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(Tn.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 An(e,t,n=!0){const r=e.getResourceManager(),s=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,s);const i=r.createTexture(t.width,t.height,s,t.pixels.length,1,n);return e._free(s),i}function Mn(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 Rn(e,t,n,r){const s=e.scale.x*t*(n?-1:1),i=e.scale.y*t*(r?-1:1),o=e.scale.z,a=e.rotation.x,c=e.rotation.y,l=e.rotation.z,u=e.rotation.w,h=a+a,d=c+c,f=l+l,p=a*h,_=a*d,m=a*f,g=c*d,y=c*f,w=l*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(g+w))*s,(_+b)*s,(m-v)*s,0,(_-b)*i,(1-(p+w))*i,(y+x)*i,0,(m+v)*o,(y-x)*o,(1-(p+g))*o,0,e.position.x,e.position.y,e.position.z,1])}async function Un(e,t,n,r,s,i,o){const a=await async function(e,t,n){const r={};for(const s of t.entities)for(const t of s.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const s=t.data.texture;if(void 0!==r[s])continue;try{r[s]=An(e,await n.loadPixels(s))}catch{r[s]=0}}return r}(t,n,r);!function(e,t,n){if(!t.textureMetadata)return;const r=e.getResourceManager();for(const e in t.textureMetadata){const s=n[e];if(s&&s>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;r.setTextureMetadata(s,e.left,e.right,e.top,e.bottom)}}}}(t,n,a);let c={},l=null;if(s&&(l=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"])}}(s),c=await async function(e,t,n,r,s){const i={};for(const o of r.entities)for(const r of o.components){if("SpineAnimation"!==r.type||!r.data)continue;const o=r.data.skeletonPath,a=r.data.atlasPath;if(!o||!a)continue;const c=s.resolvePath(o),l=s.resolvePath(a);try{const r=s.readText(a),u=c.endsWith(".skel");let h,d;if(u){const e=s.readBinary(o);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=s.readText(o),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,r,r.length,u);if(t._free(h),f<0)continue;i[o]=f;const p=Mn(r),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<p.length;t++){const r=_+"/"+p[t];try{const i=s.loadPixelsRaw?await s.loadPixelsRaw(r):await s.loadPixels(r),o=An(e,i,!1),a=e.getResourceManager().getTextureGLId(o);n.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,s,l,n,r)),i){new Cn("",{gravity:o?.gravity??{x:0,y:-9.81},fixedTimestep:o?.fixedTimestep??1/60,subStepCount:o?.subStepCount??4},()=>Promise.resolve(i)).build(e)}const u=function(e,t){const n={},r={};for(const s of e.entities)for(const e of s.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const s=e.data.material;if(void 0===n[s])try{const e=JSON.parse(t.readText(s));if(!e.vertexSource||!e.fragmentSource){n[s]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=r[i];o||(o=tt.createShader(e.vertexSource,e.fragmentSource),r[i]=o),n[s]=tt.createFromAsset(e,o)}catch{n[s]=0}}return n}(n,r),h=ht(e.world,n);if(function(e,t,n,r){for(const s of t.entities){const t=r.get(s.id);if(void 0!==t)for(const r of s.components)if("Sprite"===r.type&&r.data.texture&&"string"==typeof r.data.texture){const s=e.get(t,ee);s&&(s.texture=n[r.data.texture]||0,e.insert(t,ee,s))}}}(e.world,n,a,h),function(e,t,n,r){for(const s of t.entities){const t=r.get(s.id);if(void 0!==t)for(const r of s.components){if(!r.data||"string"!=typeof r.data.material||!r.data.material)continue;const s=n[r.data.material]||0;if(s)if("Sprite"===r.type){const n=e.get(t,ee);n&&(n.material=s,e.insert(t,ee,n))}else if("SpineAnimation"===r.type){const n=e.get(t,oe);n&&(n.material=s,e.insert(t,oe,n))}}}}(e.world,n,u,h),s&&l){const r=function(e,t,n,r){const s={};for(const i of t.entities)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=n[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const c=r.get(i.id);void 0!==c&&(s[c]=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 s}(l,n,c,h);!function(e,t,n,r,s){let i=0;e.setSpineRenderer((o,a)=>{let c=a-i;i=a,(c<=0||c>.5)&&(c=1/60);const l=e.world;for(const e in s){const i=Number(e),o=s[e],a=l.has(i,oe)?l.get(i,oe):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&r.update(o,c*h);let d=0;if(l.has(i,Z)){const e=Rn(l.get(i,Z),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=r.getMeshBatchCount(o);for(let e=0;e<f;e++){const s=r.getMeshBatchVertexCount(o,e),i=r.getMeshBatchIndexCount(o,e);if(!s||!i)continue;const a=8*s*4,c=2*i,l=n._malloc(a),u=n._malloc(c),h=n._malloc(4),f=n._malloc(4);r.getMeshBatchData(o,e,l,u,h,f);const p=n.HEAPU32[h>>2],_=n.HEAPU32[f>>2],m=new Float32Array(n.HEAPF32.buffer,l,8*s),g=new Uint16Array(n.HEAPU8.buffer,u,i),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(m,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(g),t.renderer_submitTriangles(y,s,w,i,p,_,d),t._free(y),t._free(w),n._free(l),n._free(u),n._free(h),n._free(f)}d&&t._free(d)}})}(e,t,s,l,r)}}class Fn{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 r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const r=e.data.skeletonPath,s=e.data.atlasPath;r&&(r.endsWith(".skel")?n.add(r):t.add(r)),s&&t.add(s)}"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)}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),r=await n.blob(),s=await createImageBitmap(r),i=new OffscreenCanvas(s.width,s.height).getContext("2d");i.drawImage(s,0,0);const o=i.getImageData(0,0,s.width,s.height);return s.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class Bn{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 o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new Fn(this.baseUrl_);await n.prefetch(t);let r=null;const s=this.app_.__spineInitPromise;if(s){r=(await s).controller.raw}await Un(this.app_,this.app_.wasmModule,t,n,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([te]);for(const r of n){if(e.get(r,te).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const r=e.getEntitiesWithComponents([ne]);for(const s of r){const r=e.get(s,ne);if(r.designResolution){const e=r.pixelsPerUnit||100;t=r.designResolution.y/2/e,n=r.designResolution.x/r.designResolution.y;break}}const s=e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(s,Q,i);const o={isActive:!0,projectionType:0,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(s,te,o)}}}const In={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=en.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:en.getTargetTexture(n),width:e.width,height:e.height}},release(e){en.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(en.releaseRenderTarget(e._handle),In.create({width:t,height:n,depth:!0})),begin(e,t){en.begin(t,e._handle)},end(){en.end()},getDepthTexture:e=>en.getTargetDepthTexture(e._handle)};let Wn=!1;function kn(e){Wn=e}function Dn(){return Wn}function zn(){return!Wn}var $n;T||(T=!0,void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),r={method:t?.method??"GET",headers:t?.headers,body:t?.body},s=await f(n,r);return{ok:s.ok,status:s.status,statusText:s.statusText,headers:new Headers(s.headers),json:()=>s.json(),text:()=>s.text(),arrayBuffer:()=>s.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 r=0;for(let t=0;t<e.length;t++){let s=e.charCodeAt(t);s<128?n[r++]=s:s<2048?(n[r++]=192|s>>6,n[r++]=128|63&s):s>=55296&&s<=56319?(s=e.charCodeAt(++t)-56320+(s-55296<<10)+65536,n[r++]=240|s>>18,n[r++]=128|s>>12&63,n[r++]=128|s>>6&63,n[r++]=128|63&s):(n[r++]=224|s>>12,n[r++]=128|s>>6&63,n[r++]=128|63&s)}return n.subarray(0,r)}}),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 r=t[e];if(r<128)n+=String.fromCharCode(r),e++;else if(192==(224&r))n+=String.fromCharCode((31&r)<<6|63&t[e+1]),e+=2;else if(224==(240&r))n+=String.fromCharCode((15&r)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const s=((7&r)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(s>>10),56320+(1023&s)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=$n=A,console.log(`[ESEngine] Platform: ${$n.name}`);export{hn as App,wt as AssetPlugin,gt as AssetServer,yt as Assets,mt as AsyncCache,Xe as BlendMode,H as BodyType,z as BoxCollider,te as Camera,ne as Canvas,L as CapsuleCollider,ie as Children,$ as CircleCollider,ve as Commands,Pe as CommandsInstance,It as DataType,Ut as Draw,be as EntityCommands,sn as GLDebug,Ot as Geometry,M as INVALID_ENTITY,R as INVALID_TEXTURE,Be as Input,Ie as InputPlugin,Fe as InputState,Q as LocalTransform,tt as Material,ut as MaterialLoader,ge as Mut,ae as Name,se as Parent,Tn as Physics,vn as PhysicsEvents,Cn as PhysicsPlugin,Gt as PostProcess,Bn as PreviewPlugin,we as Query,xe as QueryInstance,un as RenderPipeline,qt as RenderStage,In as RenderTexture,en as Renderer,de as Res,fe as ResMut,D as RigidBody,Se as Schedule,lt as ShaderSources,oe as SpineAnimation,ee as Sprite,Ue as SystemRunner,He as Text,ze as TextAlign,Le as TextOverflow,je as TextPlugin,Oe as TextRenderer,$e as TextVerticalAlign,me as Time,Ne as UIRect,re as Velocity,Fn as WebAssetProvider,De as World,Z as WorldTransform,Me as addStartupSystem,Ae as addSystem,Re as addSystemToSchedule,xt as assetPlugin,ln as clearDrawCallbacks,Y as clearUserComponents,I as color,dn as createWebApp,V as defineComponent,he as defineResource,Ee as defineSystem,X as defineTag,_t as findEntityByName,fn as flushPendingSystems,le as getComponentDefaults,t as getPlatform,r as getPlatformType,G as getUserComponent,Tt as initDrawAPI,nn as initGLDebugAPI,$t as initGeometryAPI,Qe as initMaterialAPI,jt as initPostProcessAPI,Qt as initRendererAPI,We as inputPlugin,J as isBuiltinComponent,Dn as isEditor,n as isPlatformInitialized,zn as isRuntime,Ge as isTextureRef,s as isWeChat,i as isWeb,ft as loadComponent,xn as loadPhysicsModule,Un as loadRuntimeScene,ht as loadSceneData,dt as loadSceneWithAssets,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,W as quat,an as registerDrawCallback,vt as registerEmbeddedAssets,ct as registerMaterialCallback,kn as setEditorMode,At as shutdownDrawAPI,rn as shutdownGLDebugAPI,Lt as shutdownGeometryAPI,Ze as shutdownMaterialAPI,Vt as shutdownPostProcessAPI,Zt as shutdownRendererAPI,Ve as textPlugin,cn as unregisterDrawCallback,pt as updateCameraAspectRatio,U as vec2,F as vec3,B as vec4,w as wxFileExists,x as wxFileExistsSync,C as wxGetImagePixels,S as wxLoadImage,E as wxLoadImagePixels,g 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 r(){return e?.name??null}function s(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(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,r)=>{const s=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===s?"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];n({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,n="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(n).buffer)}})},fail:e=>{r(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 _=null;function m(){return _||(_=wx.getFileSystemManager()),_}function g(e){return new Promise((t,n)=>{m().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,r)=>{m().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function w(e){return new Promise(t=>{m().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function x(e){const t=m();try{return t.accessSync(e),!0}catch{return!1}}function b(e,t){return new Promise((n,r)=>{m().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{r(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}let v=null,S=null;function P(e){return new Promise((t,n)=>{const r=wx.createImage();r.onload=()=>t(r),r.onerror=t=>n(new Error(`Failed to load image: ${e}, ${t}`)),r.src=e})}function C(e){const{width:t,height:n}=e,{ctx:r}=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);r.clearRect(0,0,t,n),r.drawImage(e,0,0);const s=r.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(s.data.buffer)}}async function E(e){return C(await P(e))}let T=!1;const A=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return g(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)})}},M=0,R=4294967295,F=0,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,r=1)=>({x:e,y:t,z:n,w:r}),W=(e=1,t=1,n=1,r=1)=>({r:e,g:t,b:n,a:r}),k=(e=1,t=0,n=0,r=0)=>({w:e,x:t,y:n,z:r});function D(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const z=D("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),$=D("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),H=D("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),L=D("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),O={Static:0,Kinematic:1,Dynamic:2};let N=0;function j(e,t){const n=++N;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function V(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function X(e,t){const n=V(),r=n.get(e);if(r)return r;const s=j(e,t);return n.set(e,s),K(e,t,!1),s}function G(e){const t=V(),n=t.get(e);if(n)return n;const r=j(e,{});return t.set(e,r),K(e,{},!0),r}function Y(e){return V().get(e)}function q(){V().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}),re=J("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),se=J("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),ie=J("Parent",{entity:0}),oe=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:0}),ce=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}),le={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},ue={LocalTransform:Z,WorldTransform:ee,Sprite:te,Camera:ne,Canvas:re,Velocity:se,Parent:ie,Children:oe,BitmapText:ae,SpineAnimation:ce,RigidBody:z,BoxCollider:$,CircleCollider:H,CapsuleCollider:L};function he(e){const t=ue[e];if(t)return{...t._default};const n=Y(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 _e(e){return{_type:"res_mut",_resource:e}}class me{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 ge{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 me(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 be(...e){return function(e,t=[],n=[]){const r=[];return e.forEach((e,t)=>{xe(e)&&r.push(t)}),{_type:"query",_components:e,_mutIndices:r,_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_,r=this.world_.getEntitiesWithComponents(this.allRequired_),s=n.length,i=e.length>0,o=t.length>0;let a=null,c=[];try{for(const l of r){if(null!==a&&i){for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(a,t.component,t.data)}c.length=0}if(o){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(l,t[n])){e=!0;break}if(e)continue}const r=new Array(s+1);r[0]=l;for(let e=0;e<s;e++)r[e+1]=this.world_.get(l,n[e]);if(i){for(let t=0;t<e.length;t++){const s=e[t];c.push({component:n[s],data:r[s+1]})}a=l}yield r}}finally{if(null!==a&&i)for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(a,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(){return[...this]}}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 Ae(e,t,n){const r=++Te;return{_id:Symbol(`System_${r}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${r}`}}function Me(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Re(e){Me().push({schedule:Ee.Update,system:e})}function Fe(e){Me().push({schedule:Ee.Startup,system:e})}function Ue(e,t){Me().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 We=fe(new Ie,"Input");class ke{constructor(e){this.target_=e??null}build(e){const n=new Ie;e.insertResource(We,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,r){n.mouseX=t,n.mouseY=r,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.First,Ae([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const De=new ke;function ze(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 r=t[e];n[e]=null==r||"object"!=typeof r||Array.isArray(r)?r:ze(r)}return n}class $e{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}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 r={...t._default,...n};if(this.cppRegistry_){const n=`add${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e,ze(r))}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const n=`get${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const n=`has${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const n=`remove${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e)}insertScript(e,t,n){const r=t.create(n);return this.getStorage(t).set(e,r),r}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e)}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 r of e)if(!Q(r)){const e=this.tsStorage_.get(r._id),s=e?e.size:0;s<n&&(n=s,t=e??null)}const r=[],s=t?t.keys():this.entities_;for(const t of s){let n=!0;for(const r of e)if(!this.has(t,r)){n=!1;break}n&&r.push(t)}return r}}var He,Le,Oe;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(He||(He={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Le||(Le={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Oe||(Oe={}));const Ne=X("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 je{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,r=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const s=t&&t.size.x>0&&t.size.y>0,i=s?t.size.x:0,o=s?t.size.y:0,a=e.wordWrap&&s;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=s?Math.ceil(i):h+2*u,p=s?Math.ceil(o):d+2*u;if(s&&e.overflow===Oe.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}if(r.width<f||r.height<p){const e=Math.max(r.width,this.nextPowerOf2(f)),t=Math.max(r.height,this.nextPowerOf2(p));r.width=e,r.height=t}const _=Math.round(255*e.color.r),m=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,r.width,r.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${_}, ${m}, ${g}, ${y})`,s&&e.overflow===Oe.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=c.length*l;let x;if(s)switch(e.verticalAlign){case Le.Top:x=u;break;case Le.Middle:x=(p-w)/2;break;case Le.Bottom:x=p-w-u;break;default:x=u}else x=u;let b=x;for(const t of c){let r;switch(e.align){case He.Left:r=u;break;case He.Center:r=f/2;break;case He.Right:r=f-u;break;default:r=u}n.fillText(t,r,b),b+=l}s&&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 r=this.cache.get(e);if(r){this.module.getResourceManager().releaseTexture(r.textureHandle)}const s=this.renderText(t,n);return this.cache.set(e,s),s}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,r]of this.cache)e(n)||(t.releaseTexture(r.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"),r=[];for(const e of n){if(!e){r.push("");continue}let n="";for(const s of e){const e=n+s;this.ctx.measureText(e).width>t&&n?(r.push(n),n=s):n=e}n&&r.push(n)}return r.length>0?r:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),r=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,r)}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 Ve=X("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class Xe{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new je(t),r=e.world;e.addSystemToSchedule(Ee.PreUpdate,Ae([],()=>{n.cleanupOrphaned(e=>r.valid(e)&&r.has(e,Ne));const e=r.getEntitiesWithComponents([Ne]);for(const t of e){const e=r.get(t,Ne);if(!e.dirty)continue;r.has(t,te)||r.insert(t,te,{texture:R,size:{x:0,y:0},color:{r:1,g:1,b:1,a:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const s=r.has(t,Ve)?r.get(t,Ve):null,i=n.renderForEntity(t,e,s),o=r.get(t,te);o.texture=i.textureHandle,o.size.x=i.width,o.size.y=i.height,o.uvOffset.x=0,o.uvOffset.y=0,o.uvScale.x=1,o.uvScale.y=1,r.insert(t,te,o),e.dirty=!1}}))}}const Ge=new Xe;var Ye;function qe(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}!function(e){e[e.Normal=0]="Normal",e[e.Additive=1]="Additive",e[e.Multiply=2]="Multiply",e[e.Screen=3]="Screen",e[e.PremultipliedAlpha=4]="PremultipliedAlpha"}(Ye||(Ye={}));let Ke=null,Je=null,Qe=1;const Ze=new Map;function et(e){Ke=e,Je=e.getResourceManager(),ut()}function tt(){0!==it&&Ke&&(Ke._free(it),it=0),Ze.clear(),Qe=1,st=!1,Je=null,Ke=null}function nt(){if(!Je)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Je}const rt={createShader:(e,t)=>nt().createShader(e,t),releaseShader(e){e>0&&nt().releaseShader(e)},create(e){const t=Qe++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Ye.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,r]of Object.entries(e.uniforms))n.uniforms.set(t,r);return Ze.set(t,n),t},get:e=>Ze.get(e),setUniform(e,t,n){const r=Ze.get(e);r&&r.uniforms.set(t,n)},getUniform(e,t){const n=Ze.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Ze.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Ze.get(e);return t?.blendMode??Ye.Normal},setDepthTest(e,t){const n=Ze.get(e);n&&(n.depthTest=t)},getShader(e){const t=Ze.get(e);return t?.shader??0},release(e){Ze.delete(e)},isValid:e=>Ze.has(e),createFromAsset(e,t){const n={};for(const[t,r]of Object.entries(e.properties))if("number"==typeof r)n[t]=r;else if("object"==typeof r&&null!==r){const e=r;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??Ye.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ze.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Qe++,r={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Ze.set(n,r),n},toAssetData(e,t){const n=Ze.get(e);if(!n)return null;const r={};for(const[e,t]of n.uniforms)r[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:r}},getUniforms(e){const t=Ze.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let st=!1,it=0;const ot=4096,at=new Map;let ct=null;function lt(e){const t=(0===it&&Ke&&(it=Ke._malloc(ot)),it);if(0===t||!Ke)return{ptr:0,count:0};let n=0,r=0;const s=Ke.HEAPU8,i=Ke.HEAPU32,o=Ke.HEAPF32;for(const[a,c]of e){if(n+128>ot)break;let e=at.get(a);e||(ct||(ct=new TextEncoder),e=ct.encode(a),at.set(a,e));const l=e.length,u=4*Math.ceil(l/4);i[t+n>>2]=l,n+=4,s.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof c)h=0,d[0]=c;else if(Array.isArray(c)){h=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(h=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(h=2,d=[c.x,c.y,c.z,0]):"y"in c&&(h=1,d=[c.x,c.y,0,0]);i[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=d[e],n+=4;r++}return{ptr:t,count:r}}function ut(){if(!Ke||st)return;Ke.materialDataProvider=(e,t,n,r,s)=>{const i=Ze.get(e);if(!i)return Ke.HEAPU32[t>>2]=0,Ke.HEAPU32[n>>2]=0,Ke.HEAPU32[r>>2]=0,void(Ke.HEAPU32[s>>2]=0);Ke.HEAPU32[t>>2]=i.shader,Ke.HEAPU32[n>>2]=i.blendMode;const{ptr:o,count:a}=lt(i.uniforms);Ke.HEAPU32[r>>2]=o,Ke.HEAPU32[s>>2]=a},st=!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 dt{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 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&&(rt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())rt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const n=await c(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const r=JSON.parse(n);if("material"!==r.type)throw new Error(`Invalid material file type: ${r.type}`);const s=this.resolveShaderPath(e,r.shader),i=await this.shaderLoader_.load(s);return{handle:rt.createFromAsset(r,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function ft(e,t){const n=new Map;for(const r of t.entities){const t=e.spawn();n.set(r.id,t),e.insert(t,le,{value:r.name});for(const n of r.components)_t(e,t,n)}for(const r of t.entities)if(null!==r.parent){const t=n.get(r.id),s=n.get(r.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}return n}async function pt(e,t,n){const r=new Map,s=n?.assetServer,i=new Map;for(const o of t.entities){const t=e.spawn();r.set(o.id,t),e.insert(t,le,{value:o.name});for(const r of o.components){if("Sprite"===r.type&&s){const e=r.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,r=t.startsWith("data:")?t:n?.assetBaseUrl?`${n.assetBaseUrl}/${t}`:`/${t}`;try{const n=await s.loadTexture(r);e.texture=n.handle,i.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 s.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"===r.type&&s){const e=r.data;if("string"==typeof e.font&&e.font)try{const t=await s.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"===r.type&&s){const e=r.data,t=e.skeletonPath,i=e.atlasPath;if(t&&i){const e=await s.loadSpine(t,i,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}_t(e,t,r)}}for(const n of t.entities)if(null!==n.parent){const t=r.get(n.id),s=r.get(n.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}function _t(e,t,n){const r=n.data;switch(n.type){case"LocalTransform":e.insert(t,Z,r);break;case"Sprite":e.insert(t,te,r);break;case"Camera":e.insert(t,ne,r);break;case"Canvas":e.insert(t,re,r);break;case"Text":e.insert(t,Ne,r);break;case"BitmapText":e.insert(t,ae,r);break;case"SpineAnimation":e.insert(t,ce,r);break;case"UIRect":e.insert(t,Ve,r);break;case"RigidBody":e.insert(t,z,r);break;case"BoxCollider":e.insert(t,$,r);break;case"CircleCollider":e.insert(t,H,r);break;case"CapsuleCollider":e.insert(t,L,r);break;default:{const s=Y(n.type);s?e.insert(t,s,r):console.warn(`Unknown component type: ${n.type}`);break}}}function mt(e,t){const n=e.getEntitiesWithComponents([ne]);for(const r of n){const n=e.get(r,ne);n&&(n.aspectRatio=t,e.insert(r,ne,n))}}function gt(e,t){const n=e.getEntitiesWithComponents([le]);for(const r of n){const n=e.get(r,le);if(n&&n.value===t)return r}return null}class yt{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 r=this.pending_.get(e);if(r)return r;const s=t();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)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class wt{constructor(e){this.textureCache_=new yt,this.shaderCache_=new yt,this.jsonCache_=new yt,this.textCache_=new yt,this.binaryCache_=new yt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new yt,this.embedded_=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 dt(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 r=this.textureCacheKey(e,n),s=this.textureCache_.get(r);s&&(t.releaseTexture(s.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 n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}async loadSpine(e,t,n){const r=`${e}:${t}`;if(this.loadedSpines_.has(r))return{success:!0};try{const s=this.resolveUrl(t,n),i=await this.fetchText(s);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i);for(const e of a){const t=o?`${o}/${e}`:e,r=this.resolveUrl(t,n);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 c=this.resolveUrl(e,n),l=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);return this.writeToVirtualFS(e,l)?(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 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("/")),r="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!r)throw new Error("Invalid bmfont asset: no fnt file specified");const s=n?`${n}/${r}`:r;return this.loadFntFile(s)}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 r=n[1],s=e.substring(0,e.lastIndexOf("/")),i=s?`${s}/${r}`:r,o=await this.loadTextureRaw(i);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.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 pt(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 r of e.textures)n.push(this.loadTexture(r).then(e=>{t.textures.set(r,e)}));if(e.materials)for(const r of e.materials)n.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}`;n.push(this.loadSpine(r.skeleton,r.atlas,r.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const r of e.json)n.push(this.loadJson(r).then(e=>{t.json.set(r,e)}));if(e.text)for(const r of e.text)n.push(this.loadText(r).then(e=>{t.text.set(r,e)}));if(e.binary)for(const r of e.binary)n.push(this.loadBinary(r).then(e=>{t.binary.set(r,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,r=this.embedded_.get(n)??n;return new Promise((n,s)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(i)},i.onerror=()=>s(new Error(`Failed to load image: ${e}`)),i.src=r})}createTextureFromImage(e,t){const{width:n,height:r}=e,s=this.getWebGL2Context();return s?this.createTextureWebGL2(s,e,n,r,t):this.createTextureFallback(e,n,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,n,r,s){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,s?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 o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,r),width:n,height:r}}createTextureFallback(e,t,n,r){(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 s=this.ctx_.getImageData(0,0,t,n),i=new Uint8Array(s.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,n,a,i.length,1,r);return this.module_._free(a),{handle:c,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 r=255/n;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 l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:s}=this.parseEsShader(n);if(!r||!s)throw new Error(`Invalid shader format: ${e}`);return rt.createShader(r,s)}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 c(t);return JSON.parse(n)}const n=await o(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):c(t)}const n=await o(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 o(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 r=n.split("/").filter(e=>e);let s="";for(const e of r){s=s?`${s}/${e}`:e;try{t.analyzePath(s).exists||t.mkdir(s)}catch{try{t.mkdir(s)}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 xt=fe(null,"Assets");class bt{build(e){const t=e.wasmModule;t?e.insertResource(xt,new wt(t)):console.warn("AssetPlugin: No WASM module available")}}const vt=new bt;function St(e,t){const n=e.getResource(xt);n&&n.registerEmbeddedAssets(t)}let Pt=null,Ct=0,Et=0,Tt=0;const At=new Float32Array(256);function Mt(e){Pt=e,Ct=Pt._malloc(64),Et=Pt._malloc(64),Tt=Pt._malloc(1024)}function Rt(){Pt&&(Ct&&(Pt._free(Ct),Ct=0),Et&&(Pt._free(Et),Et=0),Tt&&(Pt._free(Tt),Tt=0)),Pt=null}function Ft(){if(!Pt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Pt}const Ut={r:1,g:1,b:1,a:1},Bt={begin(e){const t=Ft();t.HEAPF32.set(e,Ct/4),t.draw_begin(Ct)},end(){Ft().draw_end()},line(e,t,n,r=1){Ft().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,r)},rect(e,t,n,r=!0){Ft().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,r)},rectOutline(e,t,n,r=1){Ft().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,r)},circle(e,t,n,r=!0,s=32){Ft().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,r,s)},circleOutline(e,t,n,r=1,s=32){Ft().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,r,s)},texture(e,t,n,r=Ut){Ft().draw_texture(e.x,e.y,t.x,t.y,n,r.r,r.g,r.b,r.a)},textureRotated(e,t,n,r,s=Ut){Ft().draw_textureRotated(e.x,e.y,t.x,t.y,n,r,s.r,s.g,s.b,s.a)},setLayer(e){Ft().draw_setLayer(e)},setDepth(e){Ft().draw_setDepth(e)},getDrawCallCount:()=>Pt?Pt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Pt?Pt.draw_getPrimitiveCount():0,setBlendMode(e){Ft().draw_setBlendMode(e)},setDepthTest(e){Ft().draw_setDepthTest(e)},drawMesh(e,t,n){const r=Ft();r.HEAPF32.set(n,Et/4),r.draw_mesh(e,t,Et)},drawMeshWithMaterial(e,t,n){const r=Ft(),s=rt.get(t);if(!s)return;if(Bt.setBlendMode(s.blendMode),Bt.setDepthTest(s.depthTest),0===s.uniforms.size)return void Bt.drawMesh(e,s.shader,n);r.HEAPF32.set(n,Et/4);let i=0,o=0;for(const[e,t]of s.uniforms){const n=Wt(e);if(!(n<0)){if(qe(t))At[i++]=10,At[i++]=n,At[i++]=t.slot??o++,At[i++]=t.textureId;else if("number"==typeof t)At[i++]=1,At[i++]=n,At[i++]=t;else if(Array.isArray(t)){At[i++]=t.length,At[i++]=n;for(let e=0;e<t.length;e++)At[i++]=t[e]}else"w"in t?(At[i++]=4,At[i++]=n,At[i++]=t.x,At[i++]=t.y,At[i++]=t.z,At[i++]=t.w):"z"in t?(At[i++]=3,At[i++]=n,At[i++]=t.x,At[i++]=t.y,At[i++]=t.z):(At[i++]=2,At[i++]=n,At[i++]=t.x,At[i++]=t.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==i?(r.HEAPF32.set(At.subarray(0,i),Tt/4),r.draw_meshWithUniforms(e,s.shader,Et,Tt,i)):r.draw_mesh(e,s.shader,Et)}},It={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 Wt(e){return It[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 Dt=null,zt=0,$t=0,Ht=0;function Lt(e){Dt=e,zt=Dt._malloc(262144),$t=Dt._malloc(65536),Ht=Dt._malloc(256)}function Ot(){Dt&&(zt&&Dt._free(zt),$t&&Dt._free($t),Ht&&Dt._free(Ht),zt=0,$t=0,Ht=0),Dt=null}function Nt(){if(!Dt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Dt}const jt={create(e){const t=Nt(),n=t.geometry_create();if(0===n)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,zt/4);const s=e.layout.length,i=new Int32Array(s);for(let t=0;t<s;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Ht,s).set(i),t.geometry_init(n,zt,r,Ht,s,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,$t,r).set(e.indices),t.geometry_setIndices16(n,$t,r)}else{new Uint32Array(t.HEAPU8.buffer,$t,r).set(e.indices),t.geometry_setIndices32(n,$t,r)}}return n},updateVertices(e,t,n=0){const r=Nt(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);r.HEAPF32.set(t,zt/4),r.geometry_updateVertices(e,zt,s,n)},release(e){e>0&&Nt().geometry_release(e)},isValid:e=>!(!Dt||e<=0)&&Dt.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,r=t/2;return jt.create({vertices:new Float32Array([-n,-r,0,0,n,-r,1,0,n,r,1,1,-n,r,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=[],r=[];n.push(0,0,.5,.5);for(let r=0;r<=t;r++){const s=r/t*Math.PI*2,i=Math.cos(s)*e,o=Math.sin(s)*e,a=(Math.cos(s)+1)/2,c=(Math.sin(s)+1)/2;n.push(i,o,a,c)}for(let e=1;e<=t;e++)r.push(0,e,e+1);return jt.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:kt.Float2},{name:"a_texCoord",type:kt.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,n=1/0,r=-1/0,s=-1/0;for(const i of e)t=Math.min(t,i.x),n=Math.min(n,i.y),r=Math.max(r,i.x),s=Math.max(s,i.y);const i=[];for(const o of e){const e=(o.x-t)/(r-t),a=(o.y-n)/(s-n);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return jt.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:kt.Float2},{name:"a_texCoord",type:kt.Float2}],indices:new Uint16Array(o)})}};let Vt=null;function Xt(e){Vt=e}function Gt(){Vt&&qt.isInitialized()&&qt.shutdown(),Vt=null}function Yt(){if(!Vt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Vt}const qt={init:(e,t)=>Yt().postprocess_init(e,t),shutdown(){Yt().postprocess_shutdown()},resize(e,t){Yt().postprocess_resize(e,t)},addPass:(e,t)=>Yt().postprocess_addPass(e,t),removePass(e){Yt().postprocess_removePass(e)},setEnabled(e,t){Yt().postprocess_setPassEnabled(e,t)},isEnabled:e=>Yt().postprocess_isPassEnabled(e),setUniform(e,t,n){Yt().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Yt().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Yt().postprocess_begin()},end(){Yt().postprocess_end()},getPassCount:()=>Yt().postprocess_getPassCount(),isInitialized:()=>!!Vt&&Vt.postprocess_isInitialized(),setBypass(e){Yt().postprocess_setBypass(e)},isBypassed:()=>!Vt||Vt.postprocess_isBypassed(),createBlur:()=>rt.createShader(Kt,"#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:()=>rt.createShader(Kt,"#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:()=>rt.createShader(Kt,"#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:()=>rt.createShader(Kt,"#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")},Kt="#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 Jt;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Jt||(Jt={}));let Qt=null,Zt=0;function en(e){Qt=e,Zt=Qt._malloc(64)}function tn(){Qt&&Zt&&(Qt._free(Zt),Zt=0),Qt=null}const nn={init(e,t){Qt?.renderer_init(e,t)},resize(e,t){Qt?.renderer_resize(e,t)},begin(e,t){Qt&&Zt&&(Qt.HEAPF32.set(e,Zt/4),Qt.renderer_begin(Zt,t??0))},flush(){Qt?.renderer_flush()},end(){Qt?.renderer_end()},submitSprites(e){Qt&&Qt.renderer_submitSprites(e._cpp)},submitBitmapText(e){Qt&&Qt.renderer_submitBitmapText(e._cpp)},submitSpine(e){Qt&&Qt.renderer_submitSpine?.(e._cpp)},setStage(e){Qt?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Qt?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Qt?.renderer_releaseTarget(e)},getTargetTexture:e=>Qt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Qt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,r){Qt?.renderer_setClearColor?.(e,t,n,r)},setViewport(e,t,n,r){Qt?.renderer_setViewport(e,t,n,r)},setScissor(e,t,n,r,s){Qt?.renderer_setScissor(e,t,n,r,s)},clearBuffers(e){Qt?.renderer_clearBuffers(e)},getStats:()=>Qt?{drawCalls:Qt.renderer_getDrawCalls(),triangles:Qt.renderer_getTriangles(),sprites:Qt.renderer_getSprites(),text:Qt.renderer_getText(),spine:Qt.renderer_getSpine?.()??0,meshes:Qt.renderer_getMeshes(),culled:Qt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let rn=null;function sn(e){rn=e}function on(){rn=null}const an={enable(){rn?.gl_enableErrorCheck(!0)},disable(){rn?.gl_enableErrorCheck(!1)},check:e=>rn?.gl_checkErrors(e)??0,diagnose(){rn?.renderer_diagnose()}},cn=new Map;function ln(e,t){cn.set(e,t)}function un(e){cn.delete(e)}function hn(){cn.clear()}class dn{constructor(){this.spineRenderer_=null,this.lastWidth_=0,this.lastHeight_=0}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:n,width:r,height:s,elapsed:i}=e;r===this.lastWidth_&&s===this.lastHeight_||(nn.resize(r,s),qt.isInitialized()&&qt.getPassCount()>0&&qt.resize(r,s),this.lastWidth_=r,this.lastHeight_=s),nn.setViewport(0,0,r,s),nn.clearBuffers(3),nn.begin(n),nn.submitSprites(t),nn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):nn.submitSpine(t),nn.flush(),this.executeDrawCallbacks(n,i),nn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:r,clearFlags:s,elapsed:i}=e;nn.setViewport(r.x,r.y,r.w,r.h),nn.setScissor(r.x,r.y,r.w,r.h,!0),nn.clearBuffers(s),nn.setScissor(0,0,0,0,!1),nn.begin(n),nn.submitSprites(t),nn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):nn.submitSpine(t),nn.flush(),this.executeDrawCallbacks(n,i),nn.end()}executeDrawCallbacks(e,t){const n=cn;if(n.size>0){Bt.begin(e);const r=[];for(const[e,s]of n.entries())try{s(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),r.push(e)}Bt.end();for(const e of r)un(e)}}}class fn{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 $e,this.resources_=new ge;for(const e of Object.values(Ee))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new fn}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_}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(Ee.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,on(),tn(),Gt(),Ot(),tt(),Rt()}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 pn(e,t){const n=fn.new(),r=new e.Registry;n.connectCpp(r,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Mt(e),et(e),Lt(e),Xt(e),en(e),sn(e);const s=new dn;n.pipeline_=s;let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),a={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=o(),a=e.registry_getCanvasEntity(r);if(a>=0){const e=r.getCanvas(a).backgroundColor;nn.setClearColor(e.r,e.g,e.b,e.a)}const c=(d()-i)/1e3;nn.resize(t,n),qt.isInitialized()&&qt.getPassCount()>0&&!qt.isBypassed()&&qt.resize(t,n);const l=function(e,t,n,r){const s=e.registry_getCameraEntities(t);if(0===s.length)return[];const i=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),o=[];for(const e of s){const s=t.getCamera(e),a=t.getLocalTransform(e),c={x:s.viewportX,y:s.viewportY,w:s.viewportW,h:s.viewportH},l=c.w*n/(c.h*r);let u;if(1===s.projectionType){let e=s.orthoSize;if(i){e=gn(i.designResolution.y/2,i.designResolution.x/i.designResolution.y,l,i.scaleMode,i.matchWidthOrHeight)}const t=e*l;u=yn(-t,t,-e,e,-s.farPlane,s.farPlane)}else u=wn(s.fov*Math.PI/180,l,s.nearPlane,s.farPlane);const h=xn(a.position.x,a.position.y,a.position.z);o.push({entity:e,viewProjection:bn(u,h),viewportRect:c,clearFlags:s.clearFlags,priority:s.priority})}return o.sort((e,t)=>e.priority-t.priority),o}(e,r,t,n);if(0===l.length)s.render({registry:{_cpp:r},viewProjection:mn,width:t,height:n,elapsed:c});else{for(const e of l){const i=e.viewportRect,o=Math.round(i.x*t),a=Math.round((1-i.y-i.h)*n),l=Math.round(i.w*t),u=Math.round(i.h*n);s.renderCamera({registry:{_cpp:r},viewProjection:e.viewProjection,viewportPixels:{x:o,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}nn.setViewport(0,0,t,n)}}};return n.addSystemToSchedule(Ee.Last,a),n.addPlugin(vt),n.addPlugin(De),n.addPlugin(Ge),n}function _n(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 mn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function gn(e,t,n,r,s){const i=e*t/n,o=e;switch(r){case 0:return i;case 1:default:return o;case 2:return Math.max(i,o);case 3:return Math.min(i,o);case 4:{const e=s;return Math.pow(i,1-e)*Math.pow(o,e)}}}function yn(e,t,n,r,s,i){const o=new Float32Array(16),a=t-e,c=r-n,l=i-s;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(r+n)/c,o[14]=-(i+s)/l,o[15]=1,o}function wn(e,t,n,r){const s=new Float32Array(16),i=1/Math.tan(e/2),o=n-r;return s[0]=i/t,s[5]=i,s[10]=(r+n)/o,s[11]=-1,s[14]=2*r*n/o,s}function xn(e,t,n){const r=new Float32Array(16);return r[0]=1,r[5]=1,r[10]=1,r[15]=1,r[12]=-e,r[13]=-t,r[14]=-n,r}function bn(e,t){const n=new Float32Array(16);for(let r=0;r<4;r++)for(let s=0;s<4;s++)n[4*s+r]=e[0+r]*t[4*s+0]+e[4+r]*t[4*s+1]+e[8+r]*t[4*s+2]+e[12+r]*t[4*s+3];return n}async function vn(e,t){if(t)return t();return(0,(await import(e)).default)()}const Sn=fe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Pn=fe(null,"PhysicsAPI");function Cn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function En(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Tn{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(Sn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,r=vn(this.wasmUrl_,this.factory_).then(r=>{r._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const s=function(e){const t=e.world.getEntitiesWithComponents([re]);for(const n of t){const t=e.world.get(n,re);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/s,o=e.world;e.addSystemToSchedule(Ee.PostUpdate,Ae([pe(ye)],a=>{const c=o.getEntitiesWithComponents([z,Z,ee]),l=new Set;for(const s of c){l.add(s);const a=o.get(s,z),c=o.get(s,ee);if(t.has(s)){const e=n.get(s);!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(s,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 o=Cn(c.rotation);r._physics_createBody(s,a.bodyType,c.position.x*i,c.position.y*i,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),An(e,r,s),t.add(s),n.set(s,{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=Cn(c.rotation);r._physics_setBodyTransform(s,c.position.x*i,c.position.y*i,e)}}for(const e of t)l.has(e)||(r._physics_destroyBody(e),t.delete(e),n.delete(e));r._physics_step(a.delta),function(e,t,n){const r=t._physics_getDynamicBodyCount();if(0===r)return;const s=t._physics_getDynamicBodyTransforms(),i=s>>2;for(let s=0;s<r;s++){const r=i+4*s,o=t.HEAPU32[r],a=t.HEAPF32[r+1]*n,c=t.HEAPF32[r+2]*n,l=t.HEAPF32[r+3];if(!e.world.valid(o))continue;const u=e.world.get(o,Z);if(!u)continue;let h=a,d=c,f=l;if(e.world.has(o,ie)){const t=e.world.get(o,ie);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ee)){const n=e.world.get(t.entity,ee),r=Cn(n.rotation),s=a-n.position.x,i=c-n.position.y,o=Math.cos(-r),u=Math.sin(-r);h=(s*o-i*u)/(0!==n.scale.x?n.scale.x:1),d=(s*u+i*o)/(0!==n.scale.y?n.scale.y:1),f=l-r}}u.position.x=h,u.position.y=d;const p=En(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(o,Z,u)}}(e,r,s),function(e,t,n){t._physics_collectEvents();const r=[],s=t._physics_getCollisionEnterCount();if(s>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<s;i++){const s=e+6*i;r.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1],normalX:t.HEAPF32[s+2],normalY:t.HEAPF32[s+3],contactX:t.HEAPF32[s+4]*n,contactY:t.HEAPF32[s+5]*n})}}const i=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<o;n++){const r=e+2*n;i.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1]})}}const a=[],c=t._physics_getSensorEnterCount();if(c>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<c;n++){const r=e+2*n;a.push({sensorEntity:t.HEAPU32[r],visitorEntity:t.HEAPU32[r+1]})}}const l=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const r=e+2*n;l.push({sensorEntity:t.HEAPU32[r],visitorEntity:t.HEAPU32[r+1]})}}e.insertResource(Sn,{collisionEnters:r,collisionExits:i,sensorEnters:a,sensorExits:l})}(e,r,s)},{name:"PhysicsSystem"})),e.__physicsModule=r,e.insertResource(Pn,Mn._fromModule(r)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=r}}function An(e,t,n){const r=e.world;if(r.has(n,$)){const e=r.get(n,$);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(r.has(n,H)){const e=r.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(r.has(n,L)){const e=r.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 Mn{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(Mn.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 Rn(e,t,n=!0){const r=e.getResourceManager(),s=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,s);const i=r.createTexture(t.width,t.height,s,t.pixels.length,1,n);return e._free(s),i}function Fn(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 Un(e,t,n,r){const s=e.scale.x*t*(n?-1:1),i=e.scale.y*t*(r?-1:1),o=e.scale.z,a=e.rotation.x,c=e.rotation.y,l=e.rotation.z,u=e.rotation.w,h=a+a,d=c+c,f=l+l,p=a*h,_=a*d,m=a*f,g=c*d,y=c*f,w=l*f,x=u*h,b=u*d,v=u*f;return new Float32Array([(1-(g+w))*s,(_+v)*s,(m-b)*s,0,(_-v)*i,(1-(p+w))*i,(y+x)*i,0,(m+b)*o,(y-x)*o,(1-(p+g))*o,0,e.position.x,e.position.y,e.position.z,1])}async function Bn(e,t,n,r,s,i,o){const a=await async function(e,t,n){const r={};for(const s of t.entities)for(const t of s.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const s=t.data.texture;if(void 0!==r[s])continue;try{r[s]=Rn(e,await n.loadPixels(s))}catch{r[s]=0}}return r}(t,n,r);!function(e,t,n){if(!t.textureMetadata)return;const r=e.getResourceManager();for(const e in t.textureMetadata){const s=n[e];if(s&&s>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;r.setTextureMetadata(s,e.left,e.right,e.top,e.bottom)}}}}(t,n,a);let c={},l=null;if(s&&(l=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"])}}(s),c=await async function(e,t,n,r,s){const i={};for(const o of r.entities)for(const r of o.components){if("SpineAnimation"!==r.type||!r.data)continue;const o=r.data.skeletonPath,a=r.data.atlasPath;if(!o||!a)continue;const c=s.resolvePath(o),l=s.resolvePath(a);try{const r=s.readText(a),u=c.endsWith(".skel");let h,d;if(u){const e=s.readBinary(o);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=s.readText(o),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,r,r.length,u);if(t._free(h),f<0)continue;i[o]=f;const p=Fn(r),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<p.length;t++){const r=_+"/"+p[t];try{const i=s.loadPixelsRaw?await s.loadPixelsRaw(r):await s.loadPixels(r),o=Rn(e,i,!1),a=e.getResourceManager().getTextureGLId(o);n.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,s,l,n,r)),i){new Tn("",{gravity:o?.gravity??{x:0,y:-9.81},fixedTimestep:o?.fixedTimestep??1/60,subStepCount:o?.subStepCount??4},()=>Promise.resolve(i)).build(e)}const u=function(e,t){const n={},r={};for(const s of e.entities)for(const e of s.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const s=e.data.material;if(void 0===n[s])try{const e=JSON.parse(t.readText(s));if(!e.vertexSource||!e.fragmentSource){n[s]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=r[i];o||(o=rt.createShader(e.vertexSource,e.fragmentSource),r[i]=o),n[s]=rt.createFromAsset(e,o)}catch{n[s]=0}}return n}(n,r),h=ft(e.world,n);if(function(e,t,n,r){for(const s of t.entities){const t=r.get(s.id);if(void 0!==t)for(const r of s.components)if("Sprite"===r.type&&r.data.texture&&"string"==typeof r.data.texture){const s=e.get(t,te);s&&(s.texture=n[r.data.texture]||0,e.insert(t,te,s))}}}(e.world,n,a,h),function(e,t,n,r){for(const s of t.entities){const t=r.get(s.id);if(void 0!==t)for(const r of s.components){if(!r.data||"string"!=typeof r.data.material||!r.data.material)continue;const s=n[r.data.material]||0;if(s)if("Sprite"===r.type){const n=e.get(t,te);n&&(n.material=s,e.insert(t,te,n))}else if("SpineAnimation"===r.type){const n=e.get(t,ce);n&&(n.material=s,e.insert(t,ce,n))}}}}(e.world,n,u,h),s&&l){const r=function(e,t,n,r){const s={};for(const i of t.entities)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=n[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const c=r.get(i.id);void 0!==c&&(s[c]=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 s}(l,n,c,h);!function(e,t,n,r,s){let i=0;e.setSpineRenderer((o,a)=>{let c=a-i;i=a,(c<=0||c>.5)&&(c=1/60);const l=e.world;for(const e in s){const i=Number(e),o=s[e],a=l.has(i,ce)?l.get(i,ce):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&r.update(o,c*h);let d=0;if(l.has(i,ee)){const e=Un(l.get(i,ee),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=r.getMeshBatchCount(o);for(let e=0;e<f;e++){const s=r.getMeshBatchVertexCount(o,e),i=r.getMeshBatchIndexCount(o,e);if(!s||!i)continue;const a=8*s*4,c=2*i,l=n._malloc(a),u=n._malloc(c),h=n._malloc(4),f=n._malloc(4);r.getMeshBatchData(o,e,l,u,h,f);const p=n.HEAPU32[h>>2],_=n.HEAPU32[f>>2],m=new Float32Array(n.HEAPF32.buffer,l,8*s),g=new Uint16Array(n.HEAPU8.buffer,u,i),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(m,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(g),t.renderer_submitTriangles(y,s,w,i,p,_,d),t._free(y),t._free(w),n._free(l),n._free(u),n._free(h),n._free(f)}d&&t._free(d)}})}(e,t,s,l,r)}}class In{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 r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const r=e.data.skeletonPath,s=e.data.atlasPath;r&&(r.endsWith(".skel")?n.add(r):t.add(r)),s&&t.add(s)}"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)}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),r=await n.blob(),s=await createImageBitmap(r),i=new OffscreenCanvas(s.width,s.height).getContext("2d");i.drawImage(s,0,0);const o=i.getImageData(0,0,s.width,s.height);return s.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class Wn{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 o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new In(this.baseUrl_);await n.prefetch(t);let r=null;const s=this.app_.__spineInitPromise;if(s){r=(await s).controller.raw}await Bn(this.app_,this.app_.wasmModule,t,n,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([ne]);for(const r of n){if(e.get(r,ne).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const r=e.getEntitiesWithComponents([re]);for(const s of r){const r=e.get(s,re);if(r.designResolution){const e=r.pixelsPerUnit||100;t=r.designResolution.y/2/e,n=r.designResolution.x/r.designResolution.y;break}}const s=e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(s,Z,i);const o={isActive:!0,projectionType:0,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(s,ne,o)}}}const kn={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=nn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:nn.getTargetTexture(n),width:e.width,height:e.height}},release(e){nn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(nn.releaseRenderTarget(e._handle),kn.create({width:t,height:n,depth:!0})),begin(e,t){nn.begin(t,e._handle)},end(){nn.end()},getDepthTexture:e=>nn.getTargetDepthTexture(e._handle)};let Dn=!1;function zn(e){Dn=e}function $n(){return Dn}function Hn(){return!Dn}var Ln;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(),r={method:t?.method??"GET",headers:t?.headers,body:t?.body},s=await f(n,r);return{ok:s.ok,status:s.status,statusText:s.statusText,headers:new Headers(s.headers),json:()=>s.json(),text:()=>s.text(),arrayBuffer:()=>s.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 r=0;for(let t=0;t<e.length;t++){let s=e.charCodeAt(t);s<128?n[r++]=s:s<2048?(n[r++]=192|s>>6,n[r++]=128|63&s):s>=55296&&s<=56319?(s=e.charCodeAt(++t)-56320+(s-55296<<10)+65536,n[r++]=240|s>>18,n[r++]=128|s>>12&63,n[r++]=128|s>>6&63,n[r++]=128|63&s):(n[r++]=224|s>>12,n[r++]=128|s>>6&63,n[r++]=128|63&s)}return n.subarray(0,r)}}),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 r=t[e];if(r<128)n+=String.fromCharCode(r),e++;else if(192==(224&r))n+=String.fromCharCode((31&r)<<6|63&t[e+1]),e+=2;else if(224==(240&r))n+=String.fromCharCode((15&r)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const s=((7&r)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(s>>10),56320+(1023&s)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=Ln=A,console.log(`[ESEngine] Platform: ${Ln.name}`);export{fn as App,bt as AssetPlugin,wt as AssetServer,xt as Assets,yt as AsyncCache,ae as BitmapText,Ye as BlendMode,O as BodyType,$ as BoxCollider,ne as Camera,re as Canvas,L as CapsuleCollider,oe as Children,H as CircleCollider,Se as Commands,Ce as CommandsInstance,kt as DataType,Bt as Draw,Pe as EntityCommands,an as GLDebug,jt as Geometry,M as INVALID_ENTITY,F as INVALID_FONT,R as INVALID_TEXTURE,We as Input,ke as InputPlugin,Ie as InputState,Z as LocalTransform,rt as Material,dt as MaterialLoader,we as Mut,le as Name,ie as Parent,Mn as Physics,Sn as PhysicsEvents,Tn as PhysicsPlugin,qt as PostProcess,Wn as PreviewPlugin,be as Query,ve as QueryInstance,dn as RenderPipeline,Jt as RenderStage,kn as RenderTexture,nn as Renderer,pe as Res,_e as ResMut,z as RigidBody,Ee as Schedule,ht as ShaderSources,ce as SpineAnimation,te as Sprite,Be as SystemRunner,Ne as Text,He as TextAlign,Oe as TextOverflow,Xe as TextPlugin,je as TextRenderer,Le as TextVerticalAlign,ye as Time,Ve as UIRect,se as Velocity,In as WebAssetProvider,$e as World,ee as WorldTransform,Fe as addStartupSystem,Re as addSystem,Ue as addSystemToSchedule,vt as assetPlugin,hn as clearDrawCallbacks,q as clearUserComponents,W as color,pn as createWebApp,X as defineComponent,fe as defineResource,Ae as defineSystem,G as defineTag,gt as findEntityByName,_n as flushPendingSystems,he as getComponentDefaults,t as getPlatform,r as getPlatformType,Y as getUserComponent,Mt as initDrawAPI,sn as initGLDebugAPI,Lt as initGeometryAPI,et as initMaterialAPI,Xt as initPostProcessAPI,en as initRendererAPI,De as inputPlugin,Q as isBuiltinComponent,$n as isEditor,n as isPlatformInitialized,Hn as isRuntime,qe as isTextureRef,s as isWeChat,i as isWeb,_t as loadComponent,vn as loadPhysicsModule,Bn as loadRuntimeScene,ft as loadSceneData,pt as loadSceneWithAssets,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,k as quat,ln as registerDrawCallback,St as registerEmbeddedAssets,ut as registerMaterialCallback,zn as setEditorMode,Rt as shutdownDrawAPI,on as shutdownGLDebugAPI,Ot as shutdownGeometryAPI,tt as shutdownMaterialAPI,Gt as shutdownPostProcessAPI,tn as shutdownRendererAPI,Ge as textPlugin,un as unregisterDrawCallback,mt as updateCameraAspectRatio,U as vec2,B as vec3,I as vec4,w as wxFileExists,x as wxFileExistsSync,C as wxGetImagePixels,P as wxLoadImage,E as wxLoadImagePixels,g as wxReadFile,y 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 be5411fb7..839a16bb6 100644
--- a/desktop/public/sdk/esm/esengine.d.ts
+++ b/desktop/public/sdk/esm/esengine.d.ts
@@ -6,6 +6,8 @@ type Entity = number;
declare const INVALID_ENTITY: Entity;
type TextureHandle = number;
declare const INVALID_TEXTURE: TextureHandle;
+type FontHandle = number;
+declare const INVALID_FONT: FontHandle;
interface Vec2 {
x: number;
y: number;
@@ -183,6 +185,15 @@ interface SpineAnimationData {
skeletonScale: number;
material: number;
}
+interface BitmapTextData {
+ text: string;
+ color: Color;
+ fontSize: number;
+ align: number;
+ spacing: number;
+ layer: number;
+ font: number;
+}
interface NameData {
value: string;
}
@@ -194,6 +205,7 @@ 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 Name: ComponentDef<NameData>;
@@ -306,6 +318,10 @@ interface CppRegistry {
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;
}
@@ -318,6 +334,9 @@ interface CppResourceManager {
releaseShader(handle: number): void;
setTextureMetadata(handle: number, left: number, right: number, top: number, bottom: number): void;
registerTextureWithPath(handle: number, path: string): void;
+ loadBitmapFont(fntContent: string, textureHandle: number, texWidth: number, texHeight: number): number;
+ createLabelAtlasFont(textureHandle: number, texWidth: number, texHeight: number, chars: string, charWidth: number, charHeight: number): number;
+ releaseBitmapFont(handle: number): void;
}
interface EmscriptenFS {
writeFile(path: string, data: string | Uint8Array): void;
@@ -412,6 +431,7 @@ interface ESEngineModule {
renderer_flush(): void;
renderer_end(): void;
renderer_submitSprites(registry: CppRegistry): void;
+ renderer_submitBitmapText(registry: CppRegistry): void;
renderer_submitSpine?(registry: CppRegistry): void;
renderer_submitTriangles(verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, transformPtr: number): void;
renderer_setStage(stage: number): void;
@@ -422,6 +442,7 @@ interface ESEngineModule {
renderer_getDrawCalls(): number;
renderer_getTriangles(): number;
renderer_getSprites(): number;
+ renderer_getText(): number;
renderer_getSpine?(): number;
renderer_getMeshes(): number;
renderer_getCulled(): number;
@@ -502,10 +523,9 @@ type QueryResult<C extends readonly QueryArg$1[]> = [
declare class QueryInstance<C extends readonly QueryArg$1[]> implements Iterable<QueryResult<C>> {
private readonly world_;
private readonly descriptor_;
- private pendingMutations_;
+ private readonly actualComponents_;
+ private readonly allRequired_;
constructor(world: World, descriptor: QueryDescriptor<C>);
- private getActualComponent;
- private commitPending;
[Symbol.iterator](): Iterator<QueryResult<C>>;
forEach(callback: (entity: Entity, ...components: ComponentsData<C>) => void): void;
single(): QueryResult<C> | null;
@@ -633,6 +653,8 @@ type SpineRendererFn = (registry: {
}, elapsed: number) => void;
declare class RenderPipeline {
private spineRenderer_;
+ private lastWidth_;
+ private lastHeight_;
setSpineRenderer(fn: SpineRendererFn | null): void;
render(params: RenderParams): void;
renderCamera(params: CameraRenderParams): void;
@@ -791,6 +813,7 @@ declare class TextRenderer {
* Releases texture for entity
*/
release(entity: Entity): void;
+ cleanupOrphaned(isAlive: (entity: Entity) => boolean): void;
/**
* Releases all cached textures
*/
@@ -1101,6 +1124,7 @@ declare class AssetServer {
private materialLoader_;
private canvas_;
private ctx_;
+ private fontCache_;
private embedded_;
constructor(module: ESEngineModule);
registerEmbeddedAssets(assets: Record<string, string>): void;
@@ -1118,10 +1142,16 @@ declare class AssetServer {
hasTexture(source: string): boolean;
releaseTexture(source: string): void;
releaseAll(): void;
+ private cleanupVirtualFS;
setTextureMetadata(handle: TextureHandle, border: SliceBorder): void;
setTextureMetadataByPath(source: string, border: SliceBorder): boolean;
loadSpine(skeletonPath: string, atlasPath: string, baseUrl?: string): Promise<SpineLoadResult>;
isSpineLoaded(skeletonPath: string, atlasPath: string): boolean;
+ loadBitmapFont(fontPath: string, baseUrl?: string): Promise<FontHandle>;
+ getFont(fontPath: string): FontHandle | undefined;
+ releaseFont(fontPath: string): void;
+ private loadBmfontAsset;
+ private loadFntFile;
loadMaterial(path: string, baseUrl?: string): Promise<LoadedMaterial>;
getMaterial(path: string, baseUrl?: string): LoadedMaterial | undefined;
hasMaterial(path: string, baseUrl?: string): boolean;
@@ -1769,6 +1799,7 @@ interface RenderStats {
drawCalls: number;
triangles: number;
sprites: number;
+ text: number;
spine: number;
meshes: number;
culled: number;
@@ -1784,6 +1815,9 @@ declare const Renderer: {
submitSprites(registry: {
_cpp: CppRegistry;
}): void;
+ submitBitmapText(registry: {
+ _cpp: CppRegistry;
+ }): void;
submitSpine(registry: {
_cpp: CppRegistry;
}): void;
@@ -1898,5 +1932,5 @@ declare const GLDebug: {
diagnose(): void;
};
-export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BlendMode, BodyType, BoxCollider, Camera, Canvas, CapsuleCollider, Children, CircleCollider, Commands, CommandsInstance, DataType, Draw, EntityCommands, GLDebug, Geometry, INVALID_ENTITY, INVALID_TEXTURE, Input, InputPlugin, InputState, LocalTransform, Material, MaterialLoader, Mut, Name, Parent, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PreviewPlugin, Query, QueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, RigidBody, Schedule, ShaderSources, SpineAnimation, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIRect, Velocity, WebAssetProvider, World, WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, assetPlugin, clearDrawCallbacks, clearUserComponents, color, createWebApp, defineComponent, defineResource, defineSystem, defineTag, findEntityByName, flushPendingSystems, getComponentDefaults, getPlatform, getPlatformType, getUserComponent, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, inputPlugin, isBuiltinComponent, isEditor, isPlatformInitialized, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, setEditorMode, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textPlugin, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4 };
-export type { AnyComponentDef, AssetBundle, AssetManifest, AssetsData, BoxColliderData, BuiltinComponentDef, CameraData, CameraRenderParams, CanvasData, CapsuleColliderData, ChildrenData, CircleColliderData, CollisionEnterEvent, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DrawAPI, DrawCallback, ESEngineModule, Entity, FileLoadOptions, GeometryHandle, GeometryOptions, InferParam, InferParams, LoadedMaterial, LocalTransformData, 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, SensorEvent, ShaderHandle, ShaderLoader, SliceBorder, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteData, SystemDef, SystemParam, TextData, TextRenderResult, TextureHandle, TextureInfo, TextureRef, TimeData, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WorldTransformData };
+export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BitmapText, BlendMode, BodyType, BoxCollider, Camera, Canvas, CapsuleCollider, Children, CircleCollider, Commands, CommandsInstance, DataType, Draw, EntityCommands, GLDebug, Geometry, INVALID_ENTITY, INVALID_FONT, INVALID_TEXTURE, Input, InputPlugin, InputState, LocalTransform, Material, MaterialLoader, Mut, Name, Parent, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PreviewPlugin, Query, QueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, RigidBody, Schedule, ShaderSources, SpineAnimation, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIRect, Velocity, WebAssetProvider, World, WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, assetPlugin, clearDrawCallbacks, clearUserComponents, color, createWebApp, defineComponent, defineResource, defineSystem, defineTag, findEntityByName, flushPendingSystems, getComponentDefaults, getPlatform, getPlatformType, getUserComponent, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, inputPlugin, isBuiltinComponent, isEditor, isPlatformInitialized, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, setEditorMode, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textPlugin, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4 };
+export type { AnyComponentDef, AssetBundle, AssetManifest, AssetsData, BitmapTextData, BoxColliderData, BuiltinComponentDef, CameraData, CameraRenderParams, CanvasData, CapsuleColliderData, ChildrenData, CircleColliderData, CollisionEnterEvent, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DrawAPI, DrawCallback, ESEngineModule, Entity, FileLoadOptions, FontHandle, GeometryHandle, GeometryOptions, InferParam, InferParams, LoadedMaterial, LocalTransformData, 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, SensorEvent, ShaderHandle, ShaderLoader, SliceBorder, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteData, SystemDef, SystemParam, TextData, TextRenderResult, TextureHandle, TextureInfo, TextureRef, TimeData, 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 81a25ea08..a90e7bb63 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 r(){return e?.name??null}function s(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(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"}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),r={};return n.headers.forEach((e,t)=>{r[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:r,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 r=await WebAssembly.instantiate(n,t);return{instance:r.instance,module:r.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){const n=t??document.querySelector("canvas")??document.body;document.addEventListener("keydown",t=>e.onKeyDown(t.code)),document.addEventListener("keyup",t=>e.onKeyUp(t.code)),n.addEventListener("mousemove",t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)}),n.addEventListener("mousedown",t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)}),n.addEventListener("mouseup",t=>{e.onPointerUp(t.button)}),n.addEventListener("touchstart",t=>{const r=t.touches[0];if(r){const t=n.getBoundingClientRect();e.onPointerDown(0,r.clientX-t.left,r.clientY-t.top)}}),n.addEventListener("touchmove",t=>{const r=t.touches[0];if(r){const t=n.getBoundingClientRect();e.onPointerMove(r.clientX-t.left,r.clientY-t.top)}}),n.addEventListener("touchend",()=>{e.onPointerUp(0)}),n.addEventListener("wheel",t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)})}},p=0,_=4294967295,m=(e=0,t=0)=>({x:e,y:t}),g=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),y=(e=0,t=0,n=0,r=1)=>({x:e,y:t,z:n,w:r}),w=(e=1,t=1,n=1,r=1)=>({r:e,g:t,b:n,a:r}),x=(e=1,t=0,n=0,r=0)=>({w:e,x:t,y:n,z:r});function v(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const b=v("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),P=v("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),S=v("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),C=v("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=>({...t,...e})}}function M(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function R(e,t){const n=M(),r=n.get(e);if(r)return r;const s=A(e,t);return n.set(e,s),I(e,t,!1),s}function U(e){const t=M(),n=t.get(e);if(n)return n;const r=A(e,{});return t.set(e,r),I(e,{},!0),r}function F(e){return M().get(e)}function B(){M().clear()}function I(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 z(e){return!0===e._builtin}const D=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}}),L=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}}),$=k("Sprite",{texture:_,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),H=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}),W=k("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),O=k("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),N=k("Parent",{entity:0}),V=k("Children",{entities:[]}),j=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}),X={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},G={LocalTransform:D,WorldTransform:L,Sprite:$,Camera:H,Canvas:W,Velocity:O,Parent:N,Children:V,SpineAnimation:j,RigidBody:b,BoxCollider:P,CircleCollider:S,CapsuleCollider:C};function Y(e){const t=G[e];if(t)return{...t._default};const n=F(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 J(e){return{_type:"res",_resource:e}}function Q(e){return{_type:"res_mut",_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=q({delta:0,elapsed:0,frameCount:0},"Time");function ne(e){return{_type:"mut",_component:e}}function re(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function se(...e){return function(e,t=[],n=[]){const r=[];return e.forEach((e,t)=>{re(e)&&r.push(t)}),{_type:"query",_components:e,_mutIndices:r,_with:t,_without:n}}(e)}class ie{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return re(e)?e._component:e}commitPending(){for(const e of this.pendingMutations_)this.world_.insert(e.entity,e.component,e.data);this.pendingMutations_=[]}*[Symbol.iterator](){const{_components:e,_mutIndices:t,_with:n,_without:r}=this.descriptor_,s=e.map(e=>this.getActualComponent(e)),i=[...s,...n],o=this.world_.getEntitiesWithComponents(i);let a=null,c=[];try{for(const e of o){if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data);c=[];let n=!1;for(const t of r)if(this.world_.has(e,t)){n=!0;break}if(n)continue;const i=s.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:s[e],data:i[e]});a=e,yield[e,...i]}}finally{if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.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(){return[...this]}}function oe(){return{_type:"commands"}}class ae{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=z(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class ce{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ae(this,null);return this.spawned_.push(e),e}entity(e){return new ae(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 le;!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"}(le||(le={}));let ue=0;function he(e,t,n){const r=++ue;return{_id:Symbol(`System_${r}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${r}`}}function de(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function fe(e){de().push({schedule:le.Update,system:e})}function pe(e){de().push({schedule:le.Startup,system:e})}function _e(e,t){de().push({schedule:e,system:t})}class me{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 ie(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new ce(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class ge{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const ye=q(new ge,"Input");class we{constructor(e){this.target_=e??null}build(e){const n=new ge;e.insertResource(ye,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,r){n.mouseX=t,n.mouseY=r,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(le.First,he([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const xe=new we;function ve(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 r=t[e];n[e]=null==r||"object"!=typeof r||Array.isArray(r)?r:ve(r)}return n}class be{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return z(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return z(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return z(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){z(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const r={...t._default,...n};if(this.cppRegistry_){const n=`add${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e,ve(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 r=t.create(n);return this.getStorage(t).set(e,r),r}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e)}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();const t=[];for(const n of this.entities_){let r=!0;for(const t of e)if(!this.has(n,t)){r=!1;break}r&&t.push(n)}return t}}var Pe,Se,Ce;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Pe||(Pe={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Se||(Se={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Ce||(Ce={}));const Ee=R("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Pe.Left,verticalAlign:Se.Top,wordWrap:!0,overflow:Ce.Visible,lineHeight:1.2,dirty:!0});class Te{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,r=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const s=t&&t.size.x>0&&t.size.y>0,i=s?t.size.x:0,o=s?t.size.y:0,a=e.wordWrap&&s;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=s?Math.ceil(i):h+2*u,p=s?Math.ceil(o):d+2*u;if(s&&e.overflow===Ce.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}if(r.width<f||r.height<p){const e=Math.max(r.width,this.nextPowerOf2(f)),t=Math.max(r.height,this.nextPowerOf2(p));r.width=e,r.height=t}const _=Math.round(255*e.color.r),m=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,r.width,r.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${_}, ${m}, ${g}, ${y})`,s&&e.overflow===Ce.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=c.length*l;let x;if(s)switch(e.verticalAlign){case Se.Top:x=u;break;case Se.Middle:x=(p-w)/2;break;case Se.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let r;switch(e.align){case Pe.Left:r=u;break;case Pe.Center:r=f/2;break;case Pe.Right:r=f-u;break;default:r=u}n.fillText(t,r,v),v+=l}s&&e.overflow===Ce.Clip&&n.restore();const b=n.getImageData(0,0,f,p),P=new Uint8Array(b.data.buffer),S=this.module.getResourceManager(),C=this.module._malloc(P.length);this.module.HEAPU8.set(P,C);const E=S.createTexture(f,p,C,P.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 r=this.cache.get(e);if(r){this.module.getResourceManager().releaseTexture(r.textureHandle)}const s=this.renderText(t,n);return this.cache.set(e,s),s}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)}}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"),r=[];for(const e of n){if(!e){r.push("");continue}let n="";for(const s of e){const e=n+s;this.ctx.measureText(e).width>t&&n?(r.push(n),n=s):n=e}n&&r.push(n)}return r.length>0?r:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),r=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,r)}return t}mapAlign(e){switch(e){case Pe.Left:return"left";case Pe.Center:return"center";case Pe.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const Ae=R("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class Me{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Te(t),r=e.world;e.addSystemToSchedule(le.PreUpdate,he([],()=>{const e=r.getEntitiesWithComponents([Ee]);for(const t of e){const e=r.get(t,Ee);if(!e.dirty)continue;r.has(t,$)||r.insert(t,$,{texture:_,size:{x:0,y:0},color:{r:1,g:1,b:1,a:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const s=r.has(t,Ae)?r.get(t,Ae):null,i=n.renderForEntity(t,e,s),o=r.get(t,$);o.texture=i.textureHandle,o.size={x:i.width,y:i.height},o.uvOffset={x:0,y:0},o.uvScale={x:1,y:1},r.insert(t,$,o),e.dirty=!1}}))}}const Re=new Me;var Ue;function Fe(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"}(Ue||(Ue={}));let Be=null,Ie=null,ke=1;const ze=new Map;function De(e){Be=e,Ie=e.getResourceManager(),Ge()}function Le(){0!==Oe&&Be&&(Be._free(Oe),Oe=0),ze.clear(),ke=1,We=!1,Ie=null,Be=null}function $e(){if(!Ie)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ie}const He={createShader:(e,t)=>$e().createShader(e,t),releaseShader(e){e>0&&$e().releaseShader(e)},create(e){const t=ke++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Ue.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,r]of Object.entries(e.uniforms))n.uniforms.set(t,r);return ze.set(t,n),t},get:e=>ze.get(e),setUniform(e,t,n){const r=ze.get(e);r&&r.uniforms.set(t,n)},getUniform(e,t){const n=ze.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=ze.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=ze.get(e);return t?.blendMode??Ue.Normal},setDepthTest(e,t){const n=ze.get(e);n&&(n.depthTest=t)},getShader(e){const t=ze.get(e);return t?.shader??0},release(e){ze.delete(e)},isValid:e=>ze.has(e),createFromAsset(e,t){const n={};for(const[t,r]of Object.entries(e.properties))if("number"==typeof r)n[t]=r;else if("object"==typeof r&&null!==r){const e=r;"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??Ue.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=ze.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=ke++,r={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return ze.set(n,r),n},toAssetData(e,t){const n=ze.get(e);if(!n)return null;const r={};for(const[e,t]of n.uniforms)r[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:r}},getUniforms(e){const t=ze.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let We=!1,Oe=0;const Ne=4096,Ve=new Map,je=new TextEncoder;function Xe(e){const t=(0===Oe&&Be&&(Oe=Be._malloc(Ne)),Oe);if(0===t||!Be)return{ptr:0,count:0};let n=0,r=0;const s=Be.HEAPU8,i=Be.HEAPU32,o=Be.HEAPF32;for(const[a,c]of e){if(n+128>Ne)break;let e=Ve.get(a);e||(e=je.encode(a),Ve.set(a,e));const l=e.length,u=4*Math.ceil(l/4);i[t+n>>2]=l,n+=4,s.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof c)h=0,d[0]=c;else if(Array.isArray(c)){h=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(h=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(h=2,d=[c.x,c.y,c.z,0]):"y"in c&&(h=1,d=[c.x,c.y,0,0]);i[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=d[e],n+=4;r++}return{ptr:t,count:r}}function Ge(){if(!Be||We)return;Be.materialDataProvider=(e,t,n,r,s)=>{const i=ze.get(e);if(!i)return Be.HEAPU32[t>>2]=0,Be.HEAPU32[n>>2]=0,Be.HEAPU32[r>>2]=0,void(Be.HEAPU32[s>>2]=0);Be.HEAPU32[t>>2]=i.shader,Be.HEAPU32[n>>2]=i.blendMode;const{ptr:o,count:a}=Xe(i.uniforms);Be.HEAPU32[r>>2]=o,Be.HEAPU32[s>>2]=a},We=!0}const Ye={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 Ke{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 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&&(He.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())He.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const n=await c(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const r=JSON.parse(n);if("material"!==r.type)throw new Error(`Invalid material file type: ${r.type}`);const s=this.resolveShaderPath(e,r.shader),i=await this.shaderLoader_.load(s);return{handle:He.createFromAsset(r,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function qe(e,t){const n=new Map;for(const r of t.entities){const t=e.spawn();n.set(r.id,t),e.insert(t,X,{value:r.name});for(const n of r.components)Qe(e,t,n)}for(const r of t.entities)if(null!==r.parent){const t=n.get(r.id),s=n.get(r.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}return n}async function Je(e,t,n){const r=new Map,s=n?.assetServer,i=new Map;for(const o of t.entities){const t=e.spawn();r.set(o.id,t),e.insert(t,X,{value:o.name});for(const r of o.components){if("Sprite"===r.type&&s){const e=r.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,r=t.startsWith("data:")?t:n?.assetBaseUrl?`${n.assetBaseUrl}/${t}`:`/${t}`;try{const n=await s.loadTexture(r);e.texture=n.handle,i.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 s.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("SpineAnimation"===r.type&&s){const e=r.data,t=e.skeletonPath,i=e.atlasPath;if(t&&i){const e=await s.loadSpine(t,i,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Qe(e,t,r)}}for(const n of t.entities)if(null!==n.parent){const t=r.get(n.id),s=r.get(n.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}function Qe(e,t,n){const r=n.data;switch(n.type){case"LocalTransform":e.insert(t,D,r);break;case"Sprite":e.insert(t,$,r);break;case"Camera":e.insert(t,H,r);break;case"Canvas":e.insert(t,W,r);break;case"Text":e.insert(t,Ee,r);break;case"SpineAnimation":e.insert(t,j,r);break;case"UIRect":e.insert(t,Ae,r);break;case"RigidBody":e.insert(t,b,r);break;case"BoxCollider":e.insert(t,P,r);break;case"CircleCollider":e.insert(t,S,r);break;case"CapsuleCollider":e.insert(t,C,r);break;default:{const s=F(n.type);s?e.insert(t,s,r):console.warn(`Unknown component type: ${n.type}`);break}}}function Ze(e,t){const n=e.getEntitiesWithComponents([H]);for(const r of n){const n=e.get(r,H);n&&(n.aspectRatio=t,e.insert(r,H,n))}}function et(e,t){const n=e.getEntitiesWithComponents([X]);for(const r of n){const n=e.get(r,X);if(n&&n.value===t)return r}return null}class tt{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 r=this.pending_.get(e);if(r)return r;const s=t();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)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class nt{constructor(e){this.textureCache_=new tt,this.shaderCache_=new tt,this.jsonCache_=new tt,this.textCache_=new tt,this.binaryCache_=new tt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.embedded_=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 Ke(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 r=this.textureCacheKey(e,n),s=this.textureCache_.get(r);s&&(t.releaseTexture(s.handle),this.textureCache_.delete(r))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);this.textureCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.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 r=`${e}:${t}`;if(this.loadedSpines_.has(r))return{success:!0};try{const s=this.resolveUrl(t,n),i=await this.fetchText(s);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i);for(const e of a){const t=o?`${o}/${e}`:e,r=this.resolveUrl(t,n);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 c=this.resolveUrl(e,n),l=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);return this.writeToVirtualFS(e,l)?(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 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 Je(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 r of e.textures)n.push(this.loadTexture(r).then(e=>{t.textures.set(r,e)}));if(e.materials)for(const r of e.materials)n.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}`;n.push(this.loadSpine(r.skeleton,r.atlas,r.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const r of e.json)n.push(this.loadJson(r).then(e=>{t.json.set(r,e)}));if(e.text)for(const r of e.text)n.push(this.loadText(r).then(e=>{t.text.set(r,e)}));if(e.binary)for(const r of e.binary)n.push(this.loadBinary(r).then(e=>{t.binary.set(r,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,r=this.embedded_.get(n)??n;return new Promise((n,s)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(i)},i.onerror=()=>s(new Error(`Failed to load image: ${e}`)),i.src=r})}createTextureFromImage(e,t){const{width:n,height:r}=e,s=this.getWebGL2Context();return s?this.createTextureWebGL2(s,e,n,r,t):this.createTextureFallback(e,n,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,n,r,s){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,s?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 o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,r),width:n,height:r}}createTextureFallback(e,t,n,r){(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 s=this.ctx_.getImageData(0,0,t,n),i=new Uint8Array(s.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,n,a,i.length,1,r);return this.module_._free(a),{handle:c,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 r=255/n;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 l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:s}=this.parseEsShader(n);if(!r||!s)throw new Error(`Invalid shader format: ${e}`);return He.createShader(r,s)}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 c(t);return JSON.parse(n)}const n=await o(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):c(t)}const n=await o(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 o(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 r=n.split("/").filter(e=>e);let s="";for(const e of r){s=s?`${s}/${e}`:e;try{t.analyzePath(s).exists||t.mkdir(s)}catch{try{t.mkdir(s)}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 rt=q(null,"Assets");class st{build(e){const t=e.wasmModule;t?e.insertResource(rt,new nt(t)):console.warn("AssetPlugin: No WASM module available")}}const it=new st;function ot(e,t){const n=e.getResource(rt);n&&n.registerEmbeddedAssets(t)}let at=null,ct=0,lt=0,ut=0;const ht=new Float32Array(256);function dt(e){at=e,ct=at._malloc(64),lt=at._malloc(64),ut=at._malloc(1024)}function ft(){at&&(ct&&(at._free(ct),ct=0),lt&&(at._free(lt),lt=0),ut&&(at._free(ut),ut=0)),at=null}function pt(){if(!at)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return at}const _t={r:1,g:1,b:1,a:1},mt={begin(e){const t=pt();t.HEAPF32.set(e,ct/4),t.draw_begin(ct)},end(){pt().draw_end()},line(e,t,n,r=1){pt().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,r)},rect(e,t,n,r=!0){pt().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,r)},rectOutline(e,t,n,r=1){pt().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,r)},circle(e,t,n,r=!0,s=32){pt().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,r,s)},circleOutline(e,t,n,r=1,s=32){pt().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,r,s)},texture(e,t,n,r=_t){pt().draw_texture(e.x,e.y,t.x,t.y,n,r.r,r.g,r.b,r.a)},textureRotated(e,t,n,r,s=_t){pt().draw_textureRotated(e.x,e.y,t.x,t.y,n,r,s.r,s.g,s.b,s.a)},setLayer(e){pt().draw_setLayer(e)},setDepth(e){pt().draw_setDepth(e)},getDrawCallCount:()=>at?at.draw_getDrawCallCount():0,getPrimitiveCount:()=>at?at.draw_getPrimitiveCount():0,setBlendMode(e){pt().draw_setBlendMode(e)},setDepthTest(e){pt().draw_setDepthTest(e)},drawMesh(e,t,n){const r=pt();r.HEAPF32.set(n,lt/4),r.draw_mesh(e,t,lt)},drawMeshWithMaterial(e,t,n){const r=pt(),s=He.get(t);if(!s)return;if(mt.setBlendMode(s.blendMode),mt.setDepthTest(s.depthTest),0===s.uniforms.size)return void mt.drawMesh(e,s.shader,n);r.HEAPF32.set(n,lt/4);let i=0,o=0;for(const[e,t]of s.uniforms){const n=yt(e);if(!(n<0)){if(Fe(t))ht[i++]=10,ht[i++]=n,ht[i++]=t.slot??o++,ht[i++]=t.textureId;else if("number"==typeof t)ht[i++]=1,ht[i++]=n,ht[i++]=t;else if(Array.isArray(t)){ht[i++]=t.length,ht[i++]=n;for(let e=0;e<t.length;e++)ht[i++]=t[e]}else"w"in t?(ht[i++]=4,ht[i++]=n,ht[i++]=t.x,ht[i++]=t.y,ht[i++]=t.z,ht[i++]=t.w):"z"in t?(ht[i++]=3,ht[i++]=n,ht[i++]=t.x,ht[i++]=t.y,ht[i++]=t.z):(ht[i++]=2,ht[i++]=n,ht[i++]=t.x,ht[i++]=t.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==i?(r.HEAPF32.set(ht.subarray(0,i),ut/4),r.draw_meshWithUniforms(e,s.shader,lt,ut,i)):r.draw_mesh(e,s.shader,lt)}},gt={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function yt(e){return gt[e]??-1}var wt;!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"}(wt||(wt={}));let xt=null,vt=0,bt=0,Pt=0;function St(e){xt=e,vt=xt._malloc(262144),bt=xt._malloc(65536),Pt=xt._malloc(256)}function Ct(){xt&&(vt&&xt._free(vt),bt&&xt._free(bt),Pt&&xt._free(Pt),vt=0,bt=0,Pt=0),xt=null}function Et(){if(!xt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return xt}const Tt={create(e){const t=Et(),n=t.geometry_create();if(0===n)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,vt/4);const s=e.layout.length,i=new Int32Array(s);for(let t=0;t<s;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Pt,s).set(i),t.geometry_init(n,vt,r,Pt,s,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,bt,r).set(e.indices),t.geometry_setIndices16(n,bt,r)}else{new Uint32Array(t.HEAPU8.buffer,bt,r).set(e.indices),t.geometry_setIndices32(n,bt,r)}}return n},updateVertices(e,t,n=0){const r=Et(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);r.HEAPF32.set(t,vt/4),r.geometry_updateVertices(e,vt,s,n)},release(e){e>0&&Et().geometry_release(e)},isValid:e=>!(!xt||e<=0)&&xt.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,r=t/2;return Tt.create({vertices:new Float32Array([-n,-r,0,0,n,-r,1,0,n,r,1,1,-n,r,0,1]),layout:[{name:"a_position",type:wt.Float2},{name:"a_texCoord",type:wt.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],r=[];n.push(0,0,.5,.5);for(let r=0;r<=t;r++){const s=r/t*Math.PI*2,i=Math.cos(s)*e,o=Math.sin(s)*e,a=(Math.cos(s)+1)/2,c=(Math.sin(s)+1)/2;n.push(i,o,a,c)}for(let e=1;e<=t;e++)r.push(0,e,e+1);return Tt.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:wt.Float2},{name:"a_texCoord",type:wt.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,n=1/0,r=-1/0,s=-1/0;for(const i of e)t=Math.min(t,i.x),n=Math.min(n,i.y),r=Math.max(r,i.x),s=Math.max(s,i.y);const i=[];for(const o of e){const e=(o.x-t)/(r-t),a=(o.y-n)/(s-n);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return Tt.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:wt.Float2},{name:"a_texCoord",type:wt.Float2}],indices:new Uint16Array(o)})}};let At=null;function Mt(e){At=e}function Rt(){At&&Ft.isInitialized()&&Ft.shutdown(),At=null}function Ut(){if(!At)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return At}const Ft={init:(e,t)=>Ut().postprocess_init(e,t),shutdown(){Ut().postprocess_shutdown()},resize(e,t){Ut().postprocess_resize(e,t)},addPass:(e,t)=>Ut().postprocess_addPass(e,t),removePass(e){Ut().postprocess_removePass(e)},setEnabled(e,t){Ut().postprocess_setPassEnabled(e,t)},isEnabled:e=>Ut().postprocess_isPassEnabled(e),setUniform(e,t,n){Ut().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Ut().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Ut().postprocess_begin()},end(){Ut().postprocess_end()},getPassCount:()=>Ut().postprocess_getPassCount(),isInitialized:()=>!!At&&At.postprocess_isInitialized(),setBypass(e){Ut().postprocess_setBypass(e)},isBypassed:()=>!At||At.postprocess_isBypassed(),createBlur:()=>He.createShader(Bt,"#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:()=>He.createShader(Bt,"#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:()=>He.createShader(Bt,"#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:()=>He.createShader(Bt,"#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")},Bt="#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 It;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(It||(It={}));let kt=null,zt=0;function Dt(e){kt=e,zt=kt._malloc(64)}function Lt(){kt&&zt&&(kt._free(zt),zt=0),kt=null}const $t={init(e,t){kt?.renderer_init(e,t)},resize(e,t){kt?.renderer_resize(e,t)},begin(e,t){kt&&zt&&(kt.HEAPF32.set(e,zt/4),kt.renderer_begin(zt,t??0))},flush(){kt?.renderer_flush()},end(){kt?.renderer_end()},submitSprites(e){kt&&kt.renderer_submitSprites(e._cpp)},submitSpine(e){kt&&kt.renderer_submitSpine?.(e._cpp)},setStage(e){kt?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>kt?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){kt?.renderer_releaseTarget(e)},getTargetTexture:e=>kt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>kt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,r){kt?.renderer_setClearColor?.(e,t,n,r)},setViewport(e,t,n,r){kt?.renderer_setViewport(e,t,n,r)},setScissor(e,t,n,r,s){kt?.renderer_setScissor(e,t,n,r,s)},clearBuffers(e){kt?.renderer_clearBuffers(e)},getStats:()=>kt?{drawCalls:kt.renderer_getDrawCalls(),triangles:kt.renderer_getTriangles(),sprites:kt.renderer_getSprites(),spine:kt.renderer_getSpine?.()??0,meshes:kt.renderer_getMeshes(),culled:kt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let Ht=null;function Wt(e){Ht=e}function Ot(){Ht=null}const Nt={enable(){Ht?.gl_enableErrorCheck(!0)},disable(){Ht?.gl_enableErrorCheck(!1)},check:e=>Ht?.gl_checkErrors(e)??0,diagnose(){Ht?.renderer_diagnose()}},Vt=new Map;function jt(e,t){Vt.set(e,t)}function Xt(e){Vt.delete(e)}function Gt(){Vt.clear()}class Yt{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:n,width:r,height:s,elapsed:i}=e;$t.resize(r,s),Ft.isInitialized()&&Ft.getPassCount()>0&&!Ft.isBypassed()&&Ft.resize(r,s),$t.setViewport(0,0,r,s),$t.clearBuffers(3),$t.begin(n),$t.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,i):$t.submitSpine(t),$t.flush(),this.executeDrawCallbacks(n,i),$t.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:r,clearFlags:s,elapsed:i}=e;$t.setViewport(r.x,r.y,r.w,r.h),$t.setScissor(r.x,r.y,r.w,r.h,!0),$t.clearBuffers(s),$t.setScissor(0,0,0,0,!1),$t.begin(n),$t.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,i):$t.submitSpine(t),$t.flush(),this.executeDrawCallbacks(n,i),$t.end()}executeDrawCallbacks(e,t){const n=Vt;if(n.size>0){mt.begin(e);const r=[];for(const[e,s]of n.entries())try{s(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),r.push(e)}mt.end();for(const e of r)Xt(e)}}}class Kt{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(le.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(le.FixedPreUpdate),this.runSchedule(le.FixedUpdate),this.runSchedule(le.FixedPostUpdate);this.runSchedule(le.PreUpdate),this.runSchedule(le.Update),this.runSchedule(le.PostUpdate),this.runSchedule(le.Last),requestAnimationFrame(this.mainLoop)},this.world_=new be,this.resources_=new ee;for(const e of Object.values(le))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Kt}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(le.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(le.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 me(this.world_,this.resources_),this.resources_.insert(te,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(le.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Ot(),Lt(),Rt(),Ct(),Le(),ft()}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++}}function qt(e,t){const n=Kt.new(),r=new e.Registry;n.connectCpp(r,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),dt(e),De(e),St(e),Mt(e),Dt(e),Wt(e);const s=new Yt;n.pipeline_=s;let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),a={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=o(),a=e.registry_getCanvasEntity(r);if(a>=0){const e=r.getCanvas(a).backgroundColor;$t.setClearColor(e.r,e.g,e.b,e.a)}const c=(d()-i)/1e3;$t.resize(t,n),Ft.isInitialized()&&Ft.getPassCount()>0&&!Ft.isBypassed()&&Ft.resize(t,n);const l=function(e,t,n,r){const s=e.registry_getCameraEntities(t);if(0===s.length)return[];const i=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),o=[];for(const e of s){const s=t.getCamera(e),a=t.getLocalTransform(e),c={x:s.viewportX,y:s.viewportY,w:s.viewportW,h:s.viewportH},l=c.w*n/(c.h*r);let u;if(1===s.projectionType){let e=s.orthoSize;if(i){e=Zt(i.designResolution.y/2,i.designResolution.x/i.designResolution.y,l,i.scaleMode,i.matchWidthOrHeight)}const t=e*l;u=en(-t,t,-e,e,-s.farPlane,s.farPlane)}else u=tn(s.fov*Math.PI/180,l,s.nearPlane,s.farPlane);const h=nn(a.position.x,a.position.y,a.position.z);o.push({entity:e,viewProjection:rn(u,h),viewportRect:c,clearFlags:s.clearFlags,priority:s.priority})}return o.sort((e,t)=>e.priority-t.priority),o}(e,r,t,n);if(0===l.length)s.render({registry:{_cpp:r},viewProjection:Qt,width:t,height:n,elapsed:c});else{for(const e of l){const i=e.viewportRect,o=Math.round(i.x*t),a=Math.round((1-i.y-i.h)*n),l=Math.round(i.w*t),u=Math.round(i.h*n);s.renderCamera({registry:{_cpp:r},viewProjection:e.viewProjection,viewportPixels:{x:o,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}$t.setViewport(0,0,t,n)}}};return n.addSystemToSchedule(le.Last,a),n.addPlugin(it),n.addPlugin(xe),n.addPlugin(Re),n}function Jt(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 Qt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Zt(e,t,n,r,s){const i=e*t/n,o=e;switch(r){case 0:return i;case 1:default:return o;case 2:return Math.max(i,o);case 3:return Math.min(i,o);case 4:{const e=s;return Math.pow(i,1-e)*Math.pow(o,e)}}}function en(e,t,n,r,s,i){const o=new Float32Array(16),a=t-e,c=r-n,l=i-s;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(r+n)/c,o[14]=-(i+s)/l,o[15]=1,o}function tn(e,t,n,r){const s=new Float32Array(16),i=1/Math.tan(e/2),o=n-r;return s[0]=i/t,s[5]=i,s[10]=(r+n)/o,s[11]=-1,s[14]=2*r*n/o,s}function nn(e,t,n){const r=new Float32Array(16);return r[0]=1,r[5]=1,r[10]=1,r[15]=1,r[12]=-e,r[13]=-t,r[14]=-n,r}function rn(e,t){const n=new Float32Array(16);for(let r=0;r<4;r++)for(let s=0;s<4;s++)n[4*s+r]=e[0+r]*t[4*s+0]+e[4+r]*t[4*s+1]+e[8+r]*t[4*s+2]+e[12+r]*t[4*s+3];return n}async function sn(e,t){if(t)return t();return(0,(await import(e)).default)()}const on=q({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),an=q(null,"PhysicsAPI");function cn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function ln(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class un{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,r=sn(this.wasmUrl_,this.factory_).then(r=>{r._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const s=function(e){const t=e.world.getEntitiesWithComponents([W]);for(const n of t){const t=e.world.get(n,W);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/s,o=e.world;e.addSystemToSchedule(le.PostUpdate,he([J(te)],a=>{const c=o.getEntitiesWithComponents([b,D,L]),l=new Set;for(const s of c){l.add(s);const a=o.get(s,b),c=o.get(s,L);if(t.has(s)){const e=n.get(s);!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(s,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 o=cn(c.rotation);r._physics_createBody(s,a.bodyType,c.position.x*i,c.position.y*i,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),hn(e,r,s),t.add(s),n.set(s,{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=cn(c.rotation);r._physics_setBodyTransform(s,c.position.x*i,c.position.y*i,e)}}for(const e of t)l.has(e)||(r._physics_destroyBody(e),t.delete(e),n.delete(e));r._physics_step(a.delta),function(e,t,n){const r=t._physics_getDynamicBodyCount();if(0===r)return;const s=t._physics_getDynamicBodyTransforms(),i=s>>2;for(let s=0;s<r;s++){const r=i+4*s,o=t.HEAPU32[r],a=t.HEAPF32[r+1]*n,c=t.HEAPF32[r+2]*n,l=t.HEAPF32[r+3];if(!e.world.valid(o))continue;const u=e.world.get(o,D);if(!u)continue;let h=a,d=c,f=l;if(e.world.has(o,N)){const t=e.world.get(o,N);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,L)){const n=e.world.get(t.entity,L),r=cn(n.rotation),s=a-n.position.x,i=c-n.position.y,o=Math.cos(-r),u=Math.sin(-r);h=(s*o-i*u)/(0!==n.scale.x?n.scale.x:1),d=(s*u+i*o)/(0!==n.scale.y?n.scale.y:1),f=l-r}}u.position.x=h,u.position.y=d;const p=ln(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(o,D,u)}}(e,r,s),function(e,t,n){t._physics_collectEvents();const r=[],s=t._physics_getCollisionEnterCount();if(s>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<s;i++){const s=e+6*i;r.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1],normalX:t.HEAPF32[s+2],normalY:t.HEAPF32[s+3],contactX:t.HEAPF32[s+4]*n,contactY:t.HEAPF32[s+5]*n})}}const i=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<o;n++){const r=e+2*n;i.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1]})}}const a=[],c=t._physics_getSensorEnterCount();if(c>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<c;n++){const r=e+2*n;a.push({sensorEntity:t.HEAPU32[r],visitorEntity:t.HEAPU32[r+1]})}}const l=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const r=e+2*n;l.push({sensorEntity:t.HEAPU32[r],visitorEntity:t.HEAPU32[r+1]})}}e.insertResource(on,{collisionEnters:r,collisionExits:i,sensorEnters:a,sensorExits:l})}(e,r,s)},{name:"PhysicsSystem"})),e.__physicsModule=r,e.insertResource(an,dn._fromModule(r)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=r}}function hn(e,t,n){const r=e.world;if(r.has(n,P)){const e=r.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(r.has(n,S)){const e=r.get(n,S);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(r.has(n,C)){const e=r.get(n,C);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 dn{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(dn.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 fn(e,t,n=!0){const r=e.getResourceManager(),s=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,s);const i=r.createTexture(t.width,t.height,s,t.pixels.length,1,n);return e._free(s),i}function pn(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 _n(e,t,n,r){const s=e.scale.x*t*(n?-1:1),i=e.scale.y*t*(r?-1:1),o=e.scale.z,a=e.rotation.x,c=e.rotation.y,l=e.rotation.z,u=e.rotation.w,h=a+a,d=c+c,f=l+l,p=a*h,_=a*d,m=a*f,g=c*d,y=c*f,w=l*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(g+w))*s,(_+b)*s,(m-v)*s,0,(_-b)*i,(1-(p+w))*i,(y+x)*i,0,(m+v)*o,(y-x)*o,(1-(p+g))*o,0,e.position.x,e.position.y,e.position.z,1])}async function mn(e,t,n,r,s,i,o){const a=await async function(e,t,n){const r={};for(const s of t.entities)for(const t of s.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const s=t.data.texture;if(void 0!==r[s])continue;try{r[s]=fn(e,await n.loadPixels(s))}catch{r[s]=0}}return r}(t,n,r);!function(e,t,n){if(!t.textureMetadata)return;const r=e.getResourceManager();for(const e in t.textureMetadata){const s=n[e];if(s&&s>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;r.setTextureMetadata(s,e.left,e.right,e.top,e.bottom)}}}}(t,n,a);let c={},l=null;if(s&&(l=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"])}}(s),c=await async function(e,t,n,r,s){const i={};for(const o of r.entities)for(const r of o.components){if("SpineAnimation"!==r.type||!r.data)continue;const o=r.data.skeletonPath,a=r.data.atlasPath;if(!o||!a)continue;const c=s.resolvePath(o),l=s.resolvePath(a);try{const r=s.readText(a),u=c.endsWith(".skel");let h,d;if(u){const e=s.readBinary(o);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=s.readText(o),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,r,r.length,u);if(t._free(h),f<0)continue;i[o]=f;const p=pn(r),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<p.length;t++){const r=_+"/"+p[t];try{const i=s.loadPixelsRaw?await s.loadPixelsRaw(r):await s.loadPixels(r),o=fn(e,i,!1),a=e.getResourceManager().getTextureGLId(o);n.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,s,l,n,r)),i){new un("",{gravity:o?.gravity??{x:0,y:-9.81},fixedTimestep:o?.fixedTimestep??1/60,subStepCount:o?.subStepCount??4},()=>Promise.resolve(i)).build(e)}const u=function(e,t){const n={},r={};for(const s of e.entities)for(const e of s.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const s=e.data.material;if(void 0===n[s])try{const e=JSON.parse(t.readText(s));if(!e.vertexSource||!e.fragmentSource){n[s]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=r[i];o||(o=He.createShader(e.vertexSource,e.fragmentSource),r[i]=o),n[s]=He.createFromAsset(e,o)}catch{n[s]=0}}return n}(n,r),h=qe(e.world,n);if(function(e,t,n,r){for(const s of t.entities){const t=r.get(s.id);if(void 0!==t)for(const r of s.components)if("Sprite"===r.type&&r.data.texture&&"string"==typeof r.data.texture){const s=e.get(t,$);s&&(s.texture=n[r.data.texture]||0,e.insert(t,$,s))}}}(e.world,n,a,h),function(e,t,n,r){for(const s of t.entities){const t=r.get(s.id);if(void 0!==t)for(const r of s.components){if(!r.data||"string"!=typeof r.data.material||!r.data.material)continue;const s=n[r.data.material]||0;if(s)if("Sprite"===r.type){const n=e.get(t,$);n&&(n.material=s,e.insert(t,$,n))}else if("SpineAnimation"===r.type){const n=e.get(t,j);n&&(n.material=s,e.insert(t,j,n))}}}}(e.world,n,u,h),s&&l){const r=function(e,t,n,r){const s={};for(const i of t.entities)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=n[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const c=r.get(i.id);void 0!==c&&(s[c]=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 s}(l,n,c,h);!function(e,t,n,r,s){let i=0;e.setSpineRenderer((o,a)=>{let c=a-i;i=a,(c<=0||c>.5)&&(c=1/60);const l=e.world;for(const e in s){const i=Number(e),o=s[e],a=l.has(i,j)?l.get(i,j):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&r.update(o,c*h);let d=0;if(l.has(i,L)){const e=_n(l.get(i,L),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=r.getMeshBatchCount(o);for(let e=0;e<f;e++){const s=r.getMeshBatchVertexCount(o,e),i=r.getMeshBatchIndexCount(o,e);if(!s||!i)continue;const a=8*s*4,c=2*i,l=n._malloc(a),u=n._malloc(c),h=n._malloc(4),f=n._malloc(4);r.getMeshBatchData(o,e,l,u,h,f);const p=n.HEAPU32[h>>2],_=n.HEAPU32[f>>2],m=new Float32Array(n.HEAPF32.buffer,l,8*s),g=new Uint16Array(n.HEAPU8.buffer,u,i),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(m,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(g),t.renderer_submitTriangles(y,s,w,i,p,_,d),t._free(y),t._free(w),n._free(l),n._free(u),n._free(h),n._free(f)}d&&t._free(d)}})}(e,t,s,l,r)}}class gn{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 r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const r=e.data.skeletonPath,s=e.data.atlasPath;r&&(r.endsWith(".skel")?n.add(r):t.add(r)),s&&t.add(s)}"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)}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),r=await n.blob(),s=await createImageBitmap(r),i=new OffscreenCanvas(s.width,s.height).getContext("2d");i.drawImage(s,0,0);const o=i.getImageData(0,0,s.width,s.height);return s.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class yn{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 o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new gn(this.baseUrl_);await n.prefetch(t);let r=null;const s=this.app_.__spineInitPromise;if(s){r=(await s).controller.raw}await mn(this.app_,this.app_.wasmModule,t,n,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 r of n){if(e.get(r,H).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const r=e.getEntitiesWithComponents([W]);for(const s of r){const r=e.get(s,W);if(r.designResolution){const e=r.pixelsPerUnit||100;t=r.designResolution.y/2/e,n=r.designResolution.x/r.designResolution.y;break}}const s=e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(s,D,i);const o={isActive:!0,projectionType:0,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(s,H,o)}}}const wn={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=$t.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:$t.getTargetTexture(n),width:e.width,height:e.height}},release(e){$t.releaseRenderTarget(e._handle)},resize:(e,t,n)=>($t.releaseRenderTarget(e._handle),wn.create({width:t,height:n,depth:!0})),begin(e,t){$t.begin(t,e._handle)},end(){$t.end()},getDepthTexture:e=>$t.getTargetDepthTexture(e._handle)};let xn=!1;function vn(e){xn=e}function bn(){return xn}function Pn(){return!xn}var Sn;e=Sn=f,console.log(`[ESEngine] Platform: ${Sn.name}`);export{Kt as App,st as AssetPlugin,nt as AssetServer,rt as Assets,tt as AsyncCache,Ue as BlendMode,E as BodyType,P as BoxCollider,H as Camera,W as Canvas,C as CapsuleCollider,V as Children,S as CircleCollider,oe as Commands,ce as CommandsInstance,wt as DataType,mt as Draw,ae as EntityCommands,Nt as GLDebug,Tt as Geometry,p as INVALID_ENTITY,_ as INVALID_TEXTURE,ye as Input,we as InputPlugin,ge as InputState,D as LocalTransform,He as Material,Ke as MaterialLoader,ne as Mut,X as Name,N as Parent,dn as Physics,on as PhysicsEvents,un as PhysicsPlugin,Ft as PostProcess,yn as PreviewPlugin,se as Query,ie as QueryInstance,Yt as RenderPipeline,It as RenderStage,wn as RenderTexture,$t as Renderer,J as Res,Q as ResMut,b as RigidBody,le as Schedule,Ye as ShaderSources,j as SpineAnimation,$ as Sprite,me as SystemRunner,Ee as Text,Pe as TextAlign,Ce as TextOverflow,Me as TextPlugin,Te as TextRenderer,Se as TextVerticalAlign,te as Time,Ae as UIRect,O as Velocity,gn as WebAssetProvider,be as World,L as WorldTransform,pe as addStartupSystem,fe as addSystem,_e as addSystemToSchedule,it as assetPlugin,Gt as clearDrawCallbacks,B as clearUserComponents,w as color,qt as createWebApp,R as defineComponent,q as defineResource,he as defineSystem,U as defineTag,et as findEntityByName,Jt as flushPendingSystems,Y as getComponentDefaults,t as getPlatform,r as getPlatformType,F as getUserComponent,dt as initDrawAPI,Wt as initGLDebugAPI,St as initGeometryAPI,De as initMaterialAPI,Mt as initPostProcessAPI,Dt as initRendererAPI,xe as inputPlugin,z as isBuiltinComponent,bn as isEditor,n as isPlatformInitialized,Pn as isRuntime,Fe as isTextureRef,s as isWeChat,i as isWeb,Qe as loadComponent,sn as loadPhysicsModule,mn as loadRuntimeScene,qe as loadSceneData,Je as loadSceneWithAssets,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,x as quat,jt as registerDrawCallback,ot as registerEmbeddedAssets,Ge as registerMaterialCallback,vn as setEditorMode,ft as shutdownDrawAPI,Ot as shutdownGLDebugAPI,Ct as shutdownGeometryAPI,Le as shutdownMaterialAPI,Rt as shutdownPostProcessAPI,Lt as shutdownRendererAPI,Re as textPlugin,Xt as unregisterDrawCallback,Ze as updateCameraAspectRatio,m as vec2,g as vec3,y as vec4};
+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 i(){return"web"===e?.name}async function o(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(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),i=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},o=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},l=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",i),n.addEventListener("mousedown",o),n.addEventListener("mouseup",a),n.addEventListener("touchstart",c),n.addEventListener("touchmove",l),n.addEventListener("touchend",u),n.addEventListener("wheel",h),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",r),n.removeEventListener("mousemove",i),n.removeEventListener("mousedown",o),n.removeEventListener("mouseup",a),n.removeEventListener("touchstart",c),n.removeEventListener("touchmove",l),n.removeEventListener("touchend",u),n.removeEventListener("wheel",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=0,_=4294967295,m=0,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}),T={Static:0,Kinematic:1,Dynamic:2};let A=0;function R(e,t){const n=++A;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function M(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function F(e,t){const n=M(),s=n.get(e);if(s)return s;const r=R(e,t);return n.set(e,r),k(e,t,!1),r}function U(e){const t=M(),n=t.get(e);if(n)return n;const s=R(e,{});return t.set(e,s),k(e,{},!0),s}function B(e){return M().get(e)}function I(){M().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 D=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}}),$=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:_,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}}),N=z("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),V=z("Parent",{entity:0}),j=z("Children",{entities:[]}),X=z("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:0}),G=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}),Y={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},K={LocalTransform:D,WorldTransform:$,Sprite:H,Camera:W,Canvas:O,Velocity:N,Parent:V,Children:j,BitmapText:X,SpineAnimation:G,RigidBody:S,BoxCollider:P,CircleCollider:C,CapsuleCollider:E};function q(e){const t=K[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 ie(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function oe(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{ie(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=>ie(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,i=e.length>0,o=t.length>0;let a=null,c=[];try{for(const l of s){if(null!==a&&i){for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(a,t.component,t.data)}c.length=0}if(o){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(l,t[n])){e=!0;break}if(e)continue}const s=new Array(r+1);s[0]=l;for(let e=0;e<r;e++)s[e+1]=this.world_.get(l,n[e]);if(i){for(let t=0;t<e.length;t++){const r=e[t];c.push({component:n[r],data:s[r+1]})}a=l}yield s}}finally{if(null!==a&&i)for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(a,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(){return[...this]}}function ce(){return{_type:"commands"}}class le{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 le(this,null);return this.spawned_.push(e),e}entity(e){return new le(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 _e(e){pe().push({schedule:he.Update,system:e})}function me(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.First,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}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,Ee,Te;!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"}(Te||(Te={}));const Ae=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:Te.Visible,lineHeight:1.2,dirty:!0});class Re{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,i=r?t.size.x:0,o=r?t.size.y:0,a=e.wordWrap&&r;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=r?Math.ceil(i):h+2*u,p=r?Math.ceil(o):d+2*u;if(r&&e.overflow===Te.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}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 _=Math.round(255*e.color.r),m=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===Te.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=c.length*l;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 c){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+=l}r&&e.overflow===Te.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 Me=F("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},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 Re(t),s=e.world;e.addSystemToSchedule(he.PreUpdate,fe([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Ae));const e=s.getEntitiesWithComponents([Ae]);for(const t of e){const e=s.get(t,Ae);if(!e.dirty)continue;s.has(t,H)||s.insert(t,H,{texture:_,size:{x:0,y:0},color:{r:1,g:1,b:1,a:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const r=s.has(t,Me)?s.get(t,Me):null,i=n.renderForEntity(t,e,r),o=s.get(t,H);o.texture=i.textureHandle,o.size.x=i.width,o.size.y=i.height,o.uvOffset.x=0,o.uvOffset.y=0,o.uvScale.x=1,o.uvScale.y=1,s.insert(t,H,o),e.dirty=!1}}))}}const Ue=new Fe;var Be;function Ie(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"}(Be||(Be={}));let ke=null,ze=null,Le=1;const De=new Map;function $e(e){ke=e,ze=e.getResourceManager(),Ke()}function He(){0!==Ve&&ke&&(ke._free(Ve),Ve=0),De.clear(),Le=1,Ne=!1,ze=null,ke=null}function We(){if(!ze)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return ze}const Oe={createShader:(e,t)=>We().createShader(e,t),releaseShader(e){e>0&&We().releaseShader(e)},create(e){const t=Le++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Be.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return De.set(t,n),t},get:e=>De.get(e),setUniform(e,t,n){const s=De.get(e);s&&s.uniforms.set(t,n)},getUniform(e,t){const n=De.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=De.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=De.get(e);return t?.blendMode??Be.Normal},setDepthTest(e,t){const n=De.get(e);n&&(n.depthTest=t)},getShader(e){const t=De.get(e);return t?.shader??0},release(e){De.delete(e)},isValid:e=>De.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??Be.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=De.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Le++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return De.set(n,s),n},toAssetData(e,t){const n=De.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=De.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ne=!1,Ve=0;const je=4096,Xe=new Map;let Ge=null;function Ye(e){const t=(0===Ve&&ke&&(Ve=ke._malloc(je)),Ve);if(0===t||!ke)return{ptr:0,count:0};let n=0,s=0;const r=ke.HEAPU8,i=ke.HEAPU32,o=ke.HEAPF32;for(const[a,c]of e){if(n+128>je)break;let e=Xe.get(a);e||(Ge||(Ge=new TextEncoder),e=Ge.encode(a),Xe.set(a,e));const l=e.length,u=4*Math.ceil(l/4);i[t+n>>2]=l,n+=4,r.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof c)h=0,d[0]=c;else if(Array.isArray(c)){h=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(h=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(h=2,d=[c.x,c.y,c.z,0]):"y"in c&&(h=1,d=[c.x,c.y,0,0]);i[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function Ke(){if(!ke||Ne)return;ke.materialDataProvider=(e,t,n,s,r)=>{const i=De.get(e);if(!i)return ke.HEAPU32[t>>2]=0,ke.HEAPU32[n>>2]=0,ke.HEAPU32[s>>2]=0,void(ke.HEAPU32[r>>2]=0);ke.HEAPU32[t>>2]=i.shader,ke.HEAPU32[n>>2]=i.blendMode;const{ptr:o,count:a}=Ye(i.uniforms);ke.HEAPU32[s>>2]=o,ke.HEAPU32[r>>2]=a},Ne=!0}const qe={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 Je{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&&(Oe.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Oe.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const n=await c(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),i=await this.shaderLoader_.load(r);return{handle:Oe.createFromAsset(s,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function Qe(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)et(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 Ze(e,t,n){const s=new Map,r=n?.assetServer,i=new Map;for(const o of t.entities){const t=e.spawn();s.set(o.id,t),e.insert(t,Y,{value:o.name});for(const s of o.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,i.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,i=e.atlasPath;if(t&&i){const e=await r.loadSpine(t,i,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}}et(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=i.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function et(e,t,n){const s=n.data;switch(n.type){case"LocalTransform":e.insert(t,D,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,Ae,s);break;case"BitmapText":e.insert(t,X,s);break;case"SpineAnimation":e.insert(t,G,s);break;case"UIRect":e.insert(t,Me,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 tt(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 nt(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}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 rt{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.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 Je(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),i=await this.fetchText(r);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i);for(const e of a){const t=o?`${o}/${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 c=this.resolveUrl(e,n),l=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);return this.writeToVirtualFS(e,l)?(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("/")),i=r?`${r}/${s}`:s,o=await this.loadTextureRaw(i);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.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 Ze(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}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 i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(i)},i.onerror=()=>r(new Error(`Failed to load image: ${e}`)),i.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 i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),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 o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),i=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,n,a,i.length,1,s);return this.module_._free(a),{handle:c,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 l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(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 Oe.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 c(t);return JSON.parse(n)}const n=await o(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):c(t)}const n=await o(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 o(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 it=Q(null,"Assets");class ot{build(e){const t=e.wasmModule;t?e.insertResource(it,new rt(t)):console.warn("AssetPlugin: No WASM module available")}}const at=new ot;function ct(e,t){const n=e.getResource(it);n&&n.registerEmbeddedAssets(t)}let lt=null,ut=0,ht=0,dt=0;const ft=new Float32Array(256);function pt(e){lt=e,ut=lt._malloc(64),ht=lt._malloc(64),dt=lt._malloc(1024)}function _t(){lt&&(ut&&(lt._free(ut),ut=0),ht&&(lt._free(ht),ht=0),dt&&(lt._free(dt),dt=0)),lt=null}function mt(){if(!lt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return lt}const gt={r:1,g:1,b:1,a:1},yt={begin(e){const t=mt();t.HEAPF32.set(e,ut/4),t.draw_begin(ut)},end(){mt().draw_end()},line(e,t,n,s=1){mt().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){mt().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){mt().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){mt().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){mt().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=gt){mt().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=gt){mt().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){mt().draw_setLayer(e)},setDepth(e){mt().draw_setDepth(e)},getDrawCallCount:()=>lt?lt.draw_getDrawCallCount():0,getPrimitiveCount:()=>lt?lt.draw_getPrimitiveCount():0,setBlendMode(e){mt().draw_setBlendMode(e)},setDepthTest(e){mt().draw_setDepthTest(e)},drawMesh(e,t,n){const s=mt();s.HEAPF32.set(n,ht/4),s.draw_mesh(e,t,ht)},drawMeshWithMaterial(e,t,n){const s=mt(),r=Oe.get(t);if(!r)return;if(yt.setBlendMode(r.blendMode),yt.setDepthTest(r.depthTest),0===r.uniforms.size)return void yt.drawMesh(e,r.shader,n);s.HEAPF32.set(n,ht/4);let i=0,o=0;for(const[e,t]of r.uniforms){const n=xt(e);if(!(n<0)){if(Ie(t))ft[i++]=10,ft[i++]=n,ft[i++]=t.slot??o++,ft[i++]=t.textureId;else if("number"==typeof t)ft[i++]=1,ft[i++]=n,ft[i++]=t;else if(Array.isArray(t)){ft[i++]=t.length,ft[i++]=n;for(let e=0;e<t.length;e++)ft[i++]=t[e]}else"w"in t?(ft[i++]=4,ft[i++]=n,ft[i++]=t.x,ft[i++]=t.y,ft[i++]=t.z,ft[i++]=t.w):"z"in t?(ft[i++]=3,ft[i++]=n,ft[i++]=t.x,ft[i++]=t.y,ft[i++]=t.z):(ft[i++]=2,ft[i++]=n,ft[i++]=t.x,ft[i++]=t.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==i?(s.HEAPF32.set(ft.subarray(0,i),dt/4),s.draw_meshWithUniforms(e,r.shader,ht,dt,i)):s.draw_mesh(e,r.shader,ht)}},wt={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 xt(e){return wt[e]??-1}var vt;!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"}(vt||(vt={}));let bt=null,St=0,Pt=0,Ct=0;function Et(e){bt=e,St=bt._malloc(262144),Pt=bt._malloc(65536),Ct=bt._malloc(256)}function Tt(){bt&&(St&&bt._free(St),Pt&&bt._free(Pt),Ct&&bt._free(Ct),St=0,Pt=0,Ct=0),bt=null}function At(){if(!bt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return bt}const Rt={create(e){const t=At(),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,St/4);const r=e.layout.length,i=new Int32Array(r);for(let t=0;t<r;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Ct,r).set(i),t.geometry_init(n,St,s,Ct,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,Pt,s).set(e.indices),t.geometry_setIndices16(n,Pt,s)}else{new Uint32Array(t.HEAPU8.buffer,Pt,s).set(e.indices),t.geometry_setIndices32(n,Pt,s)}}return n},updateVertices(e,t,n=0){const s=At(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,St/4),s.geometry_updateVertices(e,St,r,n)},release(e){e>0&&At().geometry_release(e)},isValid:e=>!(!bt||e<=0)&&bt.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Rt.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:vt.Float2},{name:"a_texCoord",type:vt.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,i=Math.cos(r)*e,o=Math.sin(r)*e,a=(Math.cos(r)+1)/2,c=(Math.sin(r)+1)/2;n.push(i,o,a,c)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return Rt.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:vt.Float2},{name:"a_texCoord",type:vt.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 i of e)t=Math.min(t,i.x),n=Math.min(n,i.y),s=Math.max(s,i.x),r=Math.max(r,i.y);const i=[];for(const o of e){const e=(o.x-t)/(s-t),a=(o.y-n)/(r-n);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return Rt.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:vt.Float2},{name:"a_texCoord",type:vt.Float2}],indices:new Uint16Array(o)})}};let Mt=null;function Ft(e){Mt=e}function Ut(){Mt&&It.isInitialized()&&It.shutdown(),Mt=null}function Bt(){if(!Mt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Mt}const It={init:(e,t)=>Bt().postprocess_init(e,t),shutdown(){Bt().postprocess_shutdown()},resize(e,t){Bt().postprocess_resize(e,t)},addPass:(e,t)=>Bt().postprocess_addPass(e,t),removePass(e){Bt().postprocess_removePass(e)},setEnabled(e,t){Bt().postprocess_setPassEnabled(e,t)},isEnabled:e=>Bt().postprocess_isPassEnabled(e),setUniform(e,t,n){Bt().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Bt().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Bt().postprocess_begin()},end(){Bt().postprocess_end()},getPassCount:()=>Bt().postprocess_getPassCount(),isInitialized:()=>!!Mt&&Mt.postprocess_isInitialized(),setBypass(e){Bt().postprocess_setBypass(e)},isBypassed:()=>!Mt||Mt.postprocess_isBypassed(),createBlur:()=>Oe.createShader(kt,"#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:()=>Oe.createShader(kt,"#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:()=>Oe.createShader(kt,"#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:()=>Oe.createShader(kt,"#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")},kt="#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 zt;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(zt||(zt={}));let Lt=null,Dt=0;function $t(e){Lt=e,Dt=Lt._malloc(64)}function Ht(){Lt&&Dt&&(Lt._free(Dt),Dt=0),Lt=null}const Wt={init(e,t){Lt?.renderer_init(e,t)},resize(e,t){Lt?.renderer_resize(e,t)},begin(e,t){Lt&&Dt&&(Lt.HEAPF32.set(e,Dt/4),Lt.renderer_begin(Dt,t??0))},flush(){Lt?.renderer_flush()},end(){Lt?.renderer_end()},submitSprites(e){Lt&&Lt.renderer_submitSprites(e._cpp)},submitBitmapText(e){Lt&&Lt.renderer_submitBitmapText(e._cpp)},submitSpine(e){Lt&&Lt.renderer_submitSpine?.(e._cpp)},setStage(e){Lt?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Lt?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Lt?.renderer_releaseTarget(e)},getTargetTexture:e=>Lt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Lt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Lt?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Lt?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){Lt?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){Lt?.renderer_clearBuffers(e)},getStats:()=>Lt?{drawCalls:Lt.renderer_getDrawCalls(),triangles:Lt.renderer_getTriangles(),sprites:Lt.renderer_getSprites(),text:Lt.renderer_getText(),spine:Lt.renderer_getSpine?.()??0,meshes:Lt.renderer_getMeshes(),culled:Lt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Ot=null;function Nt(e){Ot=e}function Vt(){Ot=null}const jt={enable(){Ot?.gl_enableErrorCheck(!0)},disable(){Ot?.gl_enableErrorCheck(!1)},check:e=>Ot?.gl_checkErrors(e)??0,diagnose(){Ot?.renderer_diagnose()}},Xt=new Map;function Gt(e,t){Xt.set(e,t)}function Yt(e){Xt.delete(e)}function Kt(){Xt.clear()}class qt{constructor(){this.spineRenderer_=null,this.lastWidth_=0,this.lastHeight_=0}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:i}=e;s===this.lastWidth_&&r===this.lastHeight_||(Wt.resize(s,r),It.isInitialized()&&It.getPassCount()>0&&It.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),Wt.setViewport(0,0,s,r),Wt.clearBuffers(3),Wt.begin(n),Wt.submitSprites(t),Wt.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Wt.submitSpine(t),Wt.flush(),this.executeDrawCallbacks(n,i),Wt.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:i}=e;Wt.setViewport(s.x,s.y,s.w,s.h),Wt.setScissor(s.x,s.y,s.w,s.h,!0),Wt.clearBuffers(r),Wt.setScissor(0,0,0,0,!1),Wt.begin(n),Wt.submitSprites(t),Wt.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Wt.submitSpine(t),Wt.flush(),this.executeDrawCallbacks(n,i),Wt.end()}executeDrawCallbacks(e,t){const n=Xt;if(n.size>0){yt.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)}yt.end();for(const e of s)Yt(e)}}}class Jt{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 Jt}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,Vt(),Ht(),Ut(),Tt(),He(),_t()}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 Qt(e,t){const n=Jt.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),pt(e),$e(e),Et(e),Ft(e),$t(e),Nt(e);const r=new qt;n.pipeline_=r;let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),a={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=o(),a=e.registry_getCanvasEntity(s);if(a>=0){const e=s.getCanvas(a).backgroundColor;Wt.setClearColor(e.r,e.g,e.b,e.a)}const c=(d()-i)/1e3;Wt.resize(t,n),It.isInitialized()&&It.getPassCount()>0&&!It.isBypassed()&&It.resize(t,n);const l=function(e,t,n,s){const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const i=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),o=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),c={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},l=c.w*n/(c.h*s);let u;if(1===r.projectionType){let e=r.orthoSize;if(i){e=tn(i.designResolution.y/2,i.designResolution.x/i.designResolution.y,l,i.scaleMode,i.matchWidthOrHeight)}const t=e*l;u=nn(-t,t,-e,e,-r.farPlane,r.farPlane)}else u=sn(r.fov*Math.PI/180,l,r.nearPlane,r.farPlane);const h=rn(a.position.x,a.position.y,a.position.z);o.push({entity:e,viewProjection:on(u,h),viewportRect:c,clearFlags:r.clearFlags,priority:r.priority})}return o.sort((e,t)=>e.priority-t.priority),o}(e,s,t,n);if(0===l.length)r.render({registry:{_cpp:s},viewProjection:en,width:t,height:n,elapsed:c});else{for(const e of l){const i=e.viewportRect,o=Math.round(i.x*t),a=Math.round((1-i.y-i.h)*n),l=Math.round(i.w*t),u=Math.round(i.h*n);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:o,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}Wt.setViewport(0,0,t,n)}}};return n.addSystemToSchedule(he.Last,a),n.addPlugin(at),n.addPlugin(be),n.addPlugin(Ue),n}function Zt(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 en=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function tn(e,t,n,s,r){const i=e*t/n,o=e;switch(s){case 0:return i;case 1:default:return o;case 2:return Math.max(i,o);case 3:return Math.min(i,o);case 4:{const e=r;return Math.pow(i,1-e)*Math.pow(o,e)}}}function nn(e,t,n,s,r,i){const o=new Float32Array(16),a=t-e,c=s-n,l=i-r;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(s+n)/c,o[14]=-(i+r)/l,o[15]=1,o}function sn(e,t,n,s){const r=new Float32Array(16),i=1/Math.tan(e/2),o=n-s;return r[0]=i/t,r[5]=i,r[10]=(s+n)/o,r[11]=-1,r[14]=2*s*n/o,r}function rn(e,t,n){const s=new Float32Array(16);return s[0]=1,s[5]=1,s[10]=1,s[15]=1,s[12]=-e,s[13]=-t,s[14]=-n,s}function on(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 an(e,t){if(t)return t();return(0,(await import(e)).default)()}const cn=Q({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),ln=Q(null,"PhysicsAPI");function un(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function hn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class dn{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(cn,{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),i=1/r,o=e.world;e.addSystemToSchedule(he.PostUpdate,fe([Z(se)],a=>{const c=o.getEntitiesWithComponents([S,D,$]),l=new Set;for(const r of c){l.add(r);const a=o.get(r,S),c=o.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 o=un(c.rotation);s._physics_createBody(r,a.bodyType,c.position.x*i,c.position.y*i,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),fn(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===T.Kinematic){const e=un(c.rotation);s._physics_setBodyTransform(r,c.position.x*i,c.position.y*i,e)}}for(const e of t)l.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(),i=r>>2;for(let r=0;r<s;r++){const s=i+4*r,o=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,c=t.HEAPF32[s+2]*n,l=t.HEAPF32[s+3];if(!e.world.valid(o))continue;const u=e.world.get(o,D);if(!u)continue;let h=a,d=c,f=l;if(e.world.has(o,V)){const t=e.world.get(o,V);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,$)){const n=e.world.get(t.entity,$),s=un(n.rotation),r=a-n.position.x,i=c-n.position.y,o=Math.cos(-s),u=Math.sin(-s);h=(r*o-i*u)/(0!==n.scale.x?n.scale.x:1),d=(r*u+i*o)/(0!==n.scale.y?n.scale.y:1),f=l-s}}u.position.x=h,u.position.y=d;const p=hn(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(o,D,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 i=0;i<r;i++){const r=e+6*i;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const i=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<o;n++){const s=e+2*n;i.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],c=t._physics_getSensorEnterCount();if(c>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<c;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const l=[],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;l.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(cn,{collisionEnters:s,collisionExits:i,sensorEnters:a,sensorExits:l})}(e,s,r)},{name:"PhysicsSystem"})),e.__physicsModule=s,e.insertResource(ln,pn._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=s}}function fn(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 pn{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(pn.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 _n(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const i=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),i}function mn(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 gn(e,t,n,s){const r=e.scale.x*t*(n?-1:1),i=e.scale.y*t*(s?-1:1),o=e.scale.z,a=e.rotation.x,c=e.rotation.y,l=e.rotation.z,u=e.rotation.w,h=a+a,d=c+c,f=l+l,p=a*h,_=a*d,m=a*f,g=c*d,y=c*f,w=l*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(g+w))*r,(_+b)*r,(m-v)*r,0,(_-b)*i,(1-(p+w))*i,(y+x)*i,0,(m+v)*o,(y-x)*o,(1-(p+g))*o,0,e.position.x,e.position.y,e.position.z,1])}async function yn(e,t,n,s,r,i,o){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]=_n(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 c={},l=null;if(r&&(l=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),c=await async function(e,t,n,s,r){const i={};for(const o of s.entities)for(const s of o.components){if("SpineAnimation"!==s.type||!s.data)continue;const o=s.data.skeletonPath,a=s.data.atlasPath;if(!o||!a)continue;const c=r.resolvePath(o),l=r.resolvePath(a);try{const s=r.readText(a),u=c.endsWith(".skel");let h,d;if(u){const e=r.readBinary(o);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=r.readText(o),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;i[o]=f;const p=mn(s),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=_+"/"+p[t];try{const i=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),o=_n(e,i,!1),a=e.getResourceManager().getTextureGLId(o);n.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,l,n,s)),i){new dn("",{gravity:o?.gravity??{x:0,y:-9.81},fixedTimestep:o?.fixedTimestep??1/60,subStepCount:o?.subStepCount??4},()=>Promise.resolve(i)).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 i=e.vertexSource+e.fragmentSource;let o=s[i];o||(o=Oe.createShader(e.vertexSource,e.fragmentSource),s[i]=o),n[r]=Oe.createFromAsset(e,o)}catch{n[r]=0}}return n}(n,s),h=Qe(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,G);n&&(n.material=r,e.insert(t,G,n))}}}}(e.world,n,u,h),r&&l){const s=function(e,t,n,s){const r={};for(const i of t.entities)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=n[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const c=s.get(i.id);void 0!==c&&(r[c]=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}(l,n,c,h);!function(e,t,n,s,r){let i=0;e.setSpineRenderer((o,a)=>{let c=a-i;i=a,(c<=0||c>.5)&&(c=1/60);const l=e.world;for(const e in r){const i=Number(e),o=r[e],a=l.has(i,G)?l.get(i,G):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&s.update(o,c*h);let d=0;if(l.has(i,$)){const e=gn(l.get(i,$),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=s.getMeshBatchCount(o);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(o,e),i=s.getMeshBatchIndexCount(o,e);if(!r||!i)continue;const a=8*r*4,c=2*i,l=n._malloc(a),u=n._malloc(c),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(o,e,l,u,h,f);const p=n.HEAPU32[h>>2],_=n.HEAPU32[f>>2],m=new Float32Array(n.HEAPF32.buffer,l,8*r),g=new Uint16Array(n.HEAPU8.buffer,u,i),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(m,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(g),t.renderer_submitTriangles(y,r,w,i,p,_,d),t._free(y),t._free(w),n._free(l),n._free(u),n._free(h),n._free(f)}d&&t._free(d)}})}(e,t,r,l,s)}}class wn{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),i=new OffscreenCanvas(r.width,r.height).getContext("2d");i.drawImage(r,0,0);const o=i.getImageData(0,0,r.width,r.height);return r.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class xn{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 o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new wn(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.__spineInitPromise;if(r){s=(await r).controller.raw}await yn(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(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,D,i);const o={isActive:!0,projectionType:0,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,o)}}}const vn={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Wt.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Wt.getTargetTexture(n),width:e.width,height:e.height}},release(e){Wt.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Wt.releaseRenderTarget(e._handle),vn.create({width:t,height:n,depth:!0})),begin(e,t){Wt.begin(t,e._handle)},end(){Wt.end()},getDepthTexture:e=>Wt.getTargetDepthTexture(e._handle)};let bn=!1;function Sn(e){bn=e}function Pn(){return bn}function Cn(){return!bn}var En;e=En=f,console.log(`[ESEngine] Platform: ${En.name}`);export{Jt as App,ot as AssetPlugin,rt as AssetServer,it as Assets,st as AsyncCache,X as BitmapText,Be as BlendMode,T as BodyType,P as BoxCollider,W as Camera,O as Canvas,E as CapsuleCollider,j as Children,C as CircleCollider,ce as Commands,ue as CommandsInstance,vt as DataType,yt as Draw,le as EntityCommands,jt as GLDebug,Rt as Geometry,p as INVALID_ENTITY,m as INVALID_FONT,_ as INVALID_TEXTURE,xe as Input,ve as InputPlugin,we as InputState,D as LocalTransform,Oe as Material,Je as MaterialLoader,re as Mut,Y as Name,V as Parent,pn as Physics,cn as PhysicsEvents,dn as PhysicsPlugin,It as PostProcess,xn as PreviewPlugin,oe as Query,ae as QueryInstance,qt as RenderPipeline,zt as RenderStage,vn as RenderTexture,Wt as Renderer,Z as Res,ee as ResMut,S as RigidBody,he as Schedule,qe as ShaderSources,G as SpineAnimation,H as Sprite,ye as SystemRunner,Ae as Text,Ce as TextAlign,Te as TextOverflow,Fe as TextPlugin,Re as TextRenderer,Ee as TextVerticalAlign,se as Time,Me as UIRect,N as Velocity,wn as WebAssetProvider,Pe as World,$ as WorldTransform,me as addStartupSystem,_e as addSystem,ge as addSystemToSchedule,at as assetPlugin,Kt as clearDrawCallbacks,I as clearUserComponents,x as color,Qt as createWebApp,F as defineComponent,Q as defineResource,fe as defineSystem,U as defineTag,nt as findEntityByName,Zt as flushPendingSystems,q as getComponentDefaults,t as getPlatform,s as getPlatformType,B as getUserComponent,pt as initDrawAPI,Nt as initGLDebugAPI,Et as initGeometryAPI,$e as initMaterialAPI,Ft as initPostProcessAPI,$t as initRendererAPI,be as inputPlugin,L as isBuiltinComponent,Pn as isEditor,n as isPlatformInitialized,Cn as isRuntime,Ie as isTextureRef,r as isWeChat,i as isWeb,et as loadComponent,an as loadPhysicsModule,yn as loadRuntimeScene,Qe as loadSceneData,Ze as loadSceneWithAssets,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,v as quat,Gt as registerDrawCallback,ct as registerEmbeddedAssets,Ke as registerMaterialCallback,Sn as setEditorMode,_t as shutdownDrawAPI,Vt as shutdownGLDebugAPI,Tt as shutdownGeometryAPI,He as shutdownMaterialAPI,Ut as shutdownPostProcessAPI,Ht as shutdownRendererAPI,Ue as textPlugin,Yt as unregisterDrawCallback,tt as updateCameraAspectRatio,g as vec2,y as vec3,w as vec4};
//# 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 e6490277a..71b1f5792 100644
--- a/desktop/public/sdk/esm/physics/index.d.ts
+++ b/desktop/public/sdk/esm/physics/index.d.ts
@@ -159,6 +159,10 @@ interface CppRegistry {
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;
}
@@ -171,6 +175,9 @@ interface CppResourceManager {
releaseShader(handle: number): void;
setTextureMetadata(handle: number, left: number, right: number, top: number, bottom: number): void;
registerTextureWithPath(handle: number, path: string): void;
+ loadBitmapFont(fntContent: string, textureHandle: number, texWidth: number, texHeight: number): number;
+ createLabelAtlasFont(textureHandle: number, texWidth: number, texHeight: number, chars: string, charWidth: number, charHeight: number): number;
+ releaseBitmapFont(handle: number): void;
}
interface EmscriptenFS {
writeFile(path: string, data: string | Uint8Array): void;
@@ -265,6 +272,7 @@ interface ESEngineModule {
renderer_flush(): void;
renderer_end(): void;
renderer_submitSprites(registry: CppRegistry): void;
+ renderer_submitBitmapText(registry: CppRegistry): void;
renderer_submitSpine?(registry: CppRegistry): void;
renderer_submitTriangles(verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, transformPtr: number): void;
renderer_setStage(stage: number): void;
@@ -275,6 +283,7 @@ interface ESEngineModule {
renderer_getDrawCalls(): number;
renderer_getTriangles(): number;
renderer_getSprites(): number;
+ renderer_getText(): number;
renderer_getSpine?(): number;
renderer_getMeshes(): number;
renderer_getCulled(): number;
diff --git a/desktop/public/sdk/esm/spine/index.d.ts b/desktop/public/sdk/esm/spine/index.d.ts
index a1a54fd7b..dad1f5c7c 100644
--- a/desktop/public/sdk/esm/spine/index.d.ts
+++ b/desktop/public/sdk/esm/spine/index.d.ts
@@ -109,6 +109,10 @@ interface CppRegistry {
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;
}
@@ -121,6 +125,9 @@ interface CppResourceManager {
releaseShader(handle: number): void;
setTextureMetadata(handle: number, left: number, right: number, top: number, bottom: number): void;
registerTextureWithPath(handle: number, path: string): void;
+ loadBitmapFont(fntContent: string, textureHandle: number, texWidth: number, texHeight: number): number;
+ createLabelAtlasFont(textureHandle: number, texWidth: number, texHeight: number, chars: string, charWidth: number, charHeight: number): number;
+ releaseBitmapFont(handle: number): void;
}
interface EmscriptenFS {
writeFile(path: string, data: string | Uint8Array): void;
@@ -215,6 +222,7 @@ interface ESEngineModule {
renderer_flush(): void;
renderer_end(): void;
renderer_submitSprites(registry: CppRegistry): void;
+ renderer_submitBitmapText(registry: CppRegistry): void;
renderer_submitSpine?(registry: CppRegistry): void;
renderer_submitTriangles(verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, transformPtr: number): void;
renderer_setStage(stage: number): void;
@@ -225,6 +233,7 @@ interface ESEngineModule {
renderer_getDrawCalls(): number;
renderer_getTriangles(): number;
renderer_getSprites(): number;
+ renderer_getText(): number;
renderer_getSpine?(): number;
renderer_getMeshes(): number;
renderer_getCulled(): number;
diff --git a/desktop/public/sdk/esm/wasm.d.ts b/desktop/public/sdk/esm/wasm.d.ts
index fc374431e..e77d4219f 100644
--- a/desktop/public/sdk/esm/wasm.d.ts
+++ b/desktop/public/sdk/esm/wasm.d.ts
@@ -66,6 +66,10 @@ interface CppRegistry {
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;
}
@@ -78,6 +82,9 @@ interface CppResourceManager {
releaseShader(handle: number): void;
setTextureMetadata(handle: number, left: number, right: number, top: number, bottom: number): void;
registerTextureWithPath(handle: number, path: string): void;
+ loadBitmapFont(fntContent: string, textureHandle: number, texWidth: number, texHeight: number): number;
+ createLabelAtlasFont(textureHandle: number, texWidth: number, texHeight: number, chars: string, charWidth: number, charHeight: number): number;
+ releaseBitmapFont(handle: number): void;
}
interface EmscriptenFS {
writeFile(path: string, data: string | Uint8Array): void;
@@ -172,6 +179,7 @@ interface ESEngineModule {
renderer_flush(): void;
renderer_end(): void;
renderer_submitSprites(registry: CppRegistry): void;
+ renderer_submitBitmapText(registry: CppRegistry): void;
renderer_submitSpine?(registry: CppRegistry): void;
renderer_submitTriangles(verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, transformPtr: number): void;
renderer_setStage(stage: number): void;
@@ -182,6 +190,7 @@ interface ESEngineModule {
renderer_getDrawCalls(): number;
renderer_getTriangles(): number;
renderer_getSprites(): number;
+ renderer_getText(): number;
renderer_getSpine?(): number;
renderer_getMeshes(): number;
renderer_getCulled(): number;
diff --git a/desktop/public/wasm/esengine.single.js b/desktop/public/wasm/esengine.single.js
index e9e29bb8b..1a3f21fdc 100644
Binary files a/desktop/public/wasm/esengine.single.js and b/desktop/public/wasm/esengine.single.js differ
diff --git a/editor/src/asset/AssetTypes.ts b/editor/src/asset/AssetTypes.ts
index 61d3f98c6..c9f6c868f 100644
--- a/editor/src/asset/AssetTypes.ts
+++ b/editor/src/asset/AssetTypes.ts
@@ -5,6 +5,7 @@ export const ASSET_EXTENSIONS = new Set([
'mp3', 'wav', 'ogg',
'atlas', 'skel', 'json',
'esmaterial', 'esshader',
+ 'bmfont', 'fnt',
]);
export function getAssetType(path: string): string {
@@ -22,6 +23,8 @@ export function getAssetType(path: string): string {
return 'spine-skeleton';
case 'json':
return 'json';
+ case 'bmfont': case 'fnt':
+ return 'bitmap-font';
case 'mp3': case 'wav': case 'ogg':
return 'audio';
default:
diff --git a/editor/src/asset/EditorAssetServer.ts b/editor/src/asset/EditorAssetServer.ts
index 77d1e8812..15a6654e0 100644
--- a/editor/src/asset/EditorAssetServer.ts
+++ b/editor/src/asset/EditorAssetServer.ts
@@ -40,6 +40,8 @@ export class EditorAssetServer {
private materialPending_ = new Map<string, Promise<LoadedMaterial>>();
private shaderCache_ = new Map<string, ShaderHandle>();
private materialInstances_ = new Map<string, MaterialInstance>();
+ private fontCache_ = new Map<string, number>();
+ private fontPending_ = new Map<string, Promise<number>>();
constructor(module: ESEngineModule, pathResolver: AssetPathResolver) {
this.module_ = module;
@@ -105,6 +107,73 @@ export class EditorAssetServer {
releaseAll(): void {
this.textureManager_.releaseAll();
this.assetLoader_.clearCache();
+ const rm = this.module_.getResourceManager();
+ for (const handle of this.fontCache_.values()) {
+ rm.releaseBitmapFont(handle);
+ }
+ this.fontCache_.clear();
+ }
+
+ async loadBitmapFont(fontRef: string): Promise<number> {
+ const cached = this.fontCache_.get(fontRef);
+ if (cached !== undefined) return cached;
+
+ const pending = this.fontPending_.get(fontRef);
+ if (pending) return pending;
+
+ const promise = this.loadBitmapFontInternal(fontRef);
+ this.fontPending_.set(fontRef, promise);
+
+ try {
+ const handle = await promise;
+ this.fontCache_.set(fontRef, handle);
+ return handle;
+ } finally {
+ this.fontPending_.delete(fontRef);
+ }
+ }
+
+ private async loadBitmapFontInternal(fontRef: string): Promise<number> {
+ const fs = this.getNativeFS();
+ if (!fs) throw new Error('NativeFS not available');
+
+ const fullPath = this.pathResolver_.toAbsolutePath(fontRef);
+
+ let fntRelDir: string;
+ let fntFile: string;
+
+ if (fontRef.endsWith('.bmfont')) {
+ const content = await fs.readFile(fullPath);
+ if (!content) throw new Error(`Failed to read: ${fullPath}`);
+ const json = JSON.parse(content) as { type?: string; fntFile?: string; generatedFnt?: string };
+ const f = json.type === 'label-atlas' ? json.generatedFnt : json.fntFile;
+ if (!f) throw new Error(`No fnt file in: ${fontRef}`);
+ const refDir = fontRef.substring(0, fontRef.lastIndexOf('/'));
+ fntRelDir = refDir;
+ fntFile = f;
+ } else {
+ const lastSlash = fontRef.lastIndexOf('/');
+ fntRelDir = lastSlash > 0 ? fontRef.substring(0, lastSlash) : '';
+ fntFile = lastSlash > 0 ? fontRef.substring(lastSlash + 1) : fontRef;
+ }
+
+ const fntFullPath = fntRelDir ? `${this.pathResolver_.toAbsolutePath(fntRelDir)}/${fntFile}` : this.pathResolver_.toAbsolutePath(fntFile);
+ const fntContent = await fs.readFile(fntFullPath);
+ if (!fntContent) throw new Error(`Failed to read: ${fntFullPath}`);
+
+ const pageMatch = fntContent.match(/file="([^"]+)"/);
+ if (!pageMatch) throw new Error(`No page texture in: ${fntFullPath}`);
+
+ const texName = pageMatch[1];
+ const texRelPath = fntRelDir ? `${fntRelDir}/${texName}` : texName;
+
+ const texResult = await this.assetLoader_.loadTexture(texRelPath);
+ if (!texResult.success || texResult.handle === undefined) {
+ throw new Error(`Failed to load font texture: ${texRelPath}`);
+ }
+
+ const rm = this.module_.getResourceManager();
+ return rm.loadBitmapFont(fntContent, texResult.handle, texResult.width ?? 0, texResult.height ?? 0);
}
setTextureMetadata(handle: number, border: SliceBorder): void {
diff --git a/editor/src/panels/ContentBrowserPanel.ts b/editor/src/panels/ContentBrowserPanel.ts
index eb6749c59..235db532f 100644
--- a/editor/src/panels/ContentBrowserPanel.ts
+++ b/editor/src/panels/ContentBrowserPanel.ts
@@ -33,7 +33,7 @@ interface FolderNode {
interface AssetItem {
name: string;
path: string;
- type: 'folder' | 'scene' | 'script' | 'image' | 'audio' | 'json' | 'material' | 'shader' | 'spine' | 'file';
+ type: 'folder' | 'scene' | 'script' | 'image' | 'audio' | 'json' | 'material' | 'shader' | 'spine' | 'font' | 'file';
}
export interface ContentBrowserOptions {
@@ -89,6 +89,8 @@ function getAssetType(entry: DirectoryEntry): AssetItem['type'] {
case '.skel':
case '.atlas':
return 'spine';
+ case '.bmfont':
+ return 'font';
default:
return 'file';
}
@@ -114,6 +116,8 @@ function getAssetIcon(type: AssetItem['type'], size: number = 32): string {
return icons.code(size);
case 'spine':
return icons.bone(size);
+ case 'font':
+ return icons.type(size);
default:
return icons.file(size);
}
@@ -570,6 +574,11 @@ export class ContentBrowserPanel {
icon: icons.code(14),
onClick: () => this.createNewShader(path),
},
+ {
+ label: 'BitmapFont',
+ icon: icons.type(14),
+ onClick: () => this.createNewBitmapFont(path),
+ },
{
label: 'Scene',
icon: icons.layers(14),
@@ -731,6 +740,27 @@ void main() {
}
}
+ private async createNewBitmapFont(parentPath: string): Promise<void> {
+ const name = await this.promptFileName('NewFont', '.bmfont');
+ if (!name) return;
+
+ const platform = getPlatformAdapter();
+ const filePath = `${parentPath}/${name}`;
+
+ const content = JSON.stringify({
+ version: '1.0',
+ type: 'label-atlas',
+ glyphs: {},
+ }, null, 2);
+
+ try {
+ await platform.writeTextFile(filePath, content);
+ this.refresh();
+ } catch (err) {
+ console.error('Failed to create bitmap font:', err);
+ }
+ }
+
private async promptFileName(defaultName: string, extension: string = ''): Promise<string | null> {
const name = await showInputDialog({
title: 'Enter Name',
diff --git a/editor/src/panels/HierarchyPanel.ts b/editor/src/panels/HierarchyPanel.ts
index 6a685be85..a4081b352 100644
--- a/editor/src/panels/HierarchyPanel.ts
+++ b/editor/src/panels/HierarchyPanel.ts
@@ -477,11 +477,12 @@ export class HierarchyPanel {
const hasCamera = entity.components.some(c => c.type === 'Camera');
const hasSprite = entity.components.some(c => c.type === 'Sprite');
const hasText = entity.components.some(c => c.type === 'Text');
+ const hasBitmapText = entity.components.some(c => c.type === 'BitmapText');
const hasSpine = entity.components.some(c => c.type === 'SpineAnimation');
if (hasCamera) return icons.camera(12);
if (hasSpine) return icons.bone(12);
- if (hasText) return icons.type(12);
+ if (hasText || hasBitmapText) return icons.type(12);
if (hasSprite) return icons.image(12);
return icons.box(12);
}
@@ -559,6 +560,7 @@ export class HierarchyPanel {
} },
{ label: 'Create Sprite', icon: icons.image(14), onClick: () => this.createEntityWithComponent('Sprite', entity) },
{ label: 'Create Text', icon: icons.type(14), onClick: () => this.createEntityWithComponent('Text', entity) },
+ { label: 'Create BitmapText', icon: icons.type(14), onClick: () => this.createEntityWithComponent('BitmapText', entity) },
{ label: 'Create Spine', icon: icons.bone(14), onClick: () => this.createEntityWithComponent('SpineAnimation', entity) },
{ label: 'Create Camera', icon: icons.camera(14), onClick: () => this.createEntityWithComponent('Camera', entity) },
{ label: 'Create Canvas', icon: icons.template(14), onClick: () => this.createEntityWithComponent('Canvas', entity) },
diff --git a/editor/src/panels/InspectorPanel.ts b/editor/src/panels/InspectorPanel.ts
index 89ca3d773..ce6809099 100644
--- a/editor/src/panels/InspectorPanel.ts
+++ b/editor/src/panels/InspectorPanel.ts
@@ -101,6 +101,7 @@ function getAssetIcon(type: AssetType, size: number = 16): string {
case 'json': return icons.braces(size);
case 'material': return icons.settings(size);
case 'shader': return icons.code(size);
+ case 'font': return icons.type(size);
case 'folder': return icons.folder(size);
default: return icons.file(size);
}
@@ -115,6 +116,7 @@ function getAssetTypeName(type: AssetType): string {
case 'json': return 'JSON';
case 'material': return 'Material';
case 'shader': return 'Shader';
+ case 'font': return 'BitmapFont';
case 'folder': return 'Folder';
default: return 'File';
}
@@ -622,7 +624,7 @@ export class InspectorPanel {
const openBtn = this.materialPreviewContainer_.querySelector('.es-material-preview-open-btn');
openBtn?.addEventListener('click', (e) => {
e.stopPropagation();
- this.navigateToAsset(materialPath);
+ this.openAssetInBrowser(materialPath);
});
const propsContainer = this.materialPreviewContainer_.querySelector('.es-material-preview-properties')!;
@@ -884,6 +886,9 @@ export class InspectorPanel {
case 'material':
await this.renderMaterialInspector(asset.path);
break;
+ case 'font':
+ await this.renderBitmapFontInspector(asset.path);
+ break;
case 'folder':
await this.renderFolderInspector(asset.path);
break;
@@ -1478,7 +1483,7 @@ export class InspectorPanel {
input.addEventListener('click', () => {
if (input.value) {
- this.navigateToAsset(input.value);
+ this.openAssetInBrowser(input.value);
}
});
@@ -1558,7 +1563,7 @@ export class InspectorPanel {
return projectPath.replace(/\\/g, '/').replace(/\/[^/]+$/, '');
}
- private navigateToAsset(assetPath: string): void {
+ private openAssetInBrowser(assetPath: string): void {
const editor = getEditorInstance();
if (editor && typeof editor.navigateToAsset === 'function') {
editor.navigateToAsset(assetPath);
@@ -2051,7 +2056,7 @@ export class InspectorPanel {
input.addEventListener('click', () => {
if (input.value) {
- this.navigateToAsset(input.value);
+ this.openAssetInBrowser(input.value);
}
});
@@ -2124,6 +2129,459 @@ export class InspectorPanel {
container.appendChild(wrapper);
}
+ private async renderBitmapFontInspector(path: string): Promise<void> {
+ const fs = getNativeFS();
+ const platform = getPlatformAdapter();
+ if (!fs) {
+ this.renderError('File system not available');
+ return;
+ }
+
+ const content = await fs.readFile(path);
+ if (!content) {
+ this.renderError('Failed to load font file');
+ return;
+ }
+
+ let fontData: Record<string, unknown>;
+ try {
+ fontData = JSON.parse(content);
+ } catch {
+ this.renderError('Invalid font file');
+ return;
+ }
+
+ const fontType = (fontData.type as string) ?? 'label-atlas';
+
+ const fontDir = path.substring(0, path.lastIndexOf('/'));
+ const baseName = getFileName(path).replace('.bmfont', '');
+
+ const save = async () => {
+ try {
+ await platform.writeTextFile(path, JSON.stringify(fontData, null, 2));
+ } catch (err) {
+ console.error('Failed to save bitmap font:', err);
+ }
+ };
+
+ const buildAtlas = async (): Promise<boolean> => {
+ const glyphs = (fontData.glyphs ?? {}) as Record<string, string>;
+ const validGlyphs = Object.fromEntries(
+ Object.entries(glyphs).filter(([, v]) => v)
+ );
+ const generated = await this.buildBitmapFontAtlas(fontDir, baseName, validGlyphs);
+ if (generated) {
+ fontData.generatedFnt = generated.fntName;
+ await save();
+ return true;
+ }
+ return false;
+ };
+
+ const section = document.createElement('div');
+ section.className = 'es-component-section es-collapsible es-expanded';
+ section.innerHTML = `
+ <div class="es-component-header es-collapsible-header">
+ <span class="es-collapse-icon">${icons.chevronDown(12)}</span>
+ <span class="es-component-icon">${icons.type(14)}</span>
+ <span class="es-component-title">BitmapFont</span>
+ </div>
+ <div class="es-component-properties es-collapsible-content"></div>
+ `;
+
+ const header = section.querySelector('.es-collapsible-header');
+ header?.addEventListener('click', () => {
+ section.classList.toggle('es-expanded');
+ });
+
+ const propsContainer = section.querySelector('.es-component-properties')!;
+
+ const typeRow = document.createElement('div');
+ typeRow.className = 'es-property-row';
+ typeRow.innerHTML = `<label class="es-property-label">Type</label><div class="es-property-editor"></div>`;
+ const typeEditor = typeRow.querySelector('.es-property-editor')!;
+ const typeSelect = document.createElement('select');
+ typeSelect.className = 'es-input es-input-select';
+ for (const opt of [{ label: 'BMFont (.fnt)', value: 'bmfont' }, { label: 'LabelAtlas', value: 'label-atlas' }]) {
+ const option = document.createElement('option');
+ option.value = opt.value;
+ option.textContent = opt.label;
+ if (opt.value === fontType) option.selected = true;
+ typeSelect.appendChild(option);
+ }
+ typeEditor.appendChild(typeSelect);
+ propsContainer.appendChild(typeRow);
+
+ const dynamicContainer = document.createElement('div');
+ propsContainer.appendChild(dynamicContainer);
+
+ const renderFields = () => {
+ dynamicContainer.innerHTML = '';
+ const currentType = fontData.type as string;
+
+ if (currentType === 'bmfont') {
+ this.createBmfontFileInput(dynamicContainer, 'fntFile', String(fontData.fntFile ?? ''), ['.fnt'], 'FNT Files', async (v) => {
+ fontData.fntFile = v;
+ await save();
+ });
+ } else {
+ this.renderGlyphList(dynamicContainer, fontData, fontDir, save);
+
+ const buildBtn = document.createElement('button');
+ buildBtn.className = 'es-btn es-btn-primary';
+ buildBtn.textContent = 'Build Atlas';
+ buildBtn.style.marginTop = '8px';
+ buildBtn.style.width = '100%';
+ buildBtn.addEventListener('click', async () => {
+ buildBtn.disabled = true;
+ buildBtn.textContent = 'Building...';
+ try {
+ const result = await buildAtlas();
+ buildBtn.textContent = result ? 'Done!' : 'No valid glyphs';
+ } catch (err) {
+ console.error('[BitmapFont] Build failed:', err);
+ buildBtn.textContent = 'Build Failed';
+ }
+ setTimeout(() => {
+ buildBtn.disabled = false;
+ buildBtn.textContent = 'Build Atlas';
+ }, 1500);
+ });
+ dynamicContainer.appendChild(buildBtn);
+ }
+ };
+
+ typeSelect.addEventListener('change', async () => {
+ fontData.type = typeSelect.value;
+ if (typeSelect.value === 'label-atlas' && !fontData.glyphs) {
+ fontData.glyphs = {};
+ }
+ await save();
+ renderFields();
+ });
+
+ renderFields();
+ this.contentContainer_.appendChild(section);
+ }
+
+ private async buildBitmapFontAtlas(
+ fontDir: string,
+ baseName: string,
+ glyphs: Record<string, string>,
+ ): Promise<{ fntName: string } | null> {
+ const fs = getNativeFS();
+ const platform = getPlatformAdapter();
+ if (!fs) return null;
+
+ const entries: { char: string; img: HTMLImageElement; w: number; h: number }[] = [];
+
+ for (const [char, imgPath] of Object.entries(glyphs)) {
+ if (!imgPath) continue;
+ const fullPath = `${fontDir}/${imgPath}`;
+ const url = platform.convertFilePathToUrl(fullPath);
+ try {
+ const img = await this.loadImageFromUrl(url);
+ entries.push({ char, img, w: img.naturalWidth, h: img.naturalHeight });
+ } catch (err) {
+ console.error(`[BitmapFont] Failed to load glyph '${char}': ${fullPath}`, err);
+ }
+ }
+
+ console.log(`[BitmapFont] Loaded ${entries.length}/${Object.keys(glyphs).length} glyphs`);
+
+ const maxH = entries.length > 0 ? Math.max(...entries.map(e => e.h)) : 1;
+ const totalW = entries.reduce((sum, e) => sum + e.w, 0) || 1;
+ const atlasW = this.nextPowerOf2(totalW);
+ const atlasH = this.nextPowerOf2(maxH);
+
+ const canvas = document.createElement('canvas');
+ canvas.width = atlasW;
+ canvas.height = atlasH;
+ const ctx = canvas.getContext('2d')!;
+
+ let x = 0;
+ const fntLines = [
+ `info face="${baseName}" size=${maxH}`,
+ `common lineHeight=${maxH} base=${maxH} scaleW=${atlasW} scaleH=${atlasH} pages=1`,
+ `page id=0 file="${baseName}.atlas.png"`,
+ `chars count=${entries.length}`,
+ ];
+
+ for (const entry of entries) {
+ ctx.drawImage(entry.img, x, 0);
+ const charCode = entry.char.codePointAt(0)!;
+ fntLines.push(
+ `char id=${charCode} x=${x} y=0 width=${entry.w} height=${entry.h} xoffset=0 yoffset=0 xadvance=${entry.w} page=0`
+ );
+ x += entry.w;
+ }
+
+ const blob = await new Promise<Blob | null>(resolve => canvas.toBlob(resolve, 'image/png'));
+ if (!blob) return null;
+
+ const arrayBuffer = await blob.arrayBuffer();
+ const pngData = new Uint8Array(arrayBuffer);
+
+ const atlasPath = `${fontDir}/${baseName}.atlas.png`;
+ const fntPath = `${fontDir}/${baseName}.fnt`;
+
+ await fs.writeBinaryFile(atlasPath, pngData);
+ await fs.writeFile(fntPath, fntLines.join('\n'));
+
+ return { fntName: `${baseName}.fnt` };
+ }
+
+ private loadImageFromUrl(url: string): Promise<HTMLImageElement> {
+ return new Promise((resolve, reject) => {
+ const img = new Image();
+ img.crossOrigin = 'anonymous';
+ img.onload = () => resolve(img);
+ img.onerror = () => reject(new Error(`Failed to load: ${url}`));
+ img.src = url;
+ });
+ }
+
+ private nextPowerOf2(n: number): number {
+ let p = 1;
+ while (p < n) p *= 2;
+ return p;
+ }
+
+ private renderGlyphList(
+ container: HTMLElement,
+ fontData: Record<string, unknown>,
+ fontDir: string,
+ save: () => Promise<void>,
+ ): void {
+ const glyphs = (fontData.glyphs ?? {}) as Record<string, string>;
+
+ const listContainer = document.createElement('div');
+ listContainer.className = 'es-bmfont-glyph-list';
+
+ const rebuildList = () => {
+ listContainer.innerHTML = '';
+ const currentGlyphs = (fontData.glyphs ?? {}) as Record<string, string>;
+
+ for (const [char, imgPath] of Object.entries(currentGlyphs)) {
+ const row = document.createElement('div');
+ row.className = 'es-property-row es-bmfont-glyph-row';
+
+ const charInput = document.createElement('input');
+ charInput.type = 'text';
+ charInput.className = 'es-input es-bmfont-char-input';
+ charInput.value = char;
+ charInput.maxLength = 2;
+ charInput.style.width = '36px';
+ charInput.style.textAlign = 'center';
+
+ const fileInput = document.createElement('input');
+ fileInput.type = 'text';
+ fileInput.className = 'es-input es-input-file';
+ fileInput.value = imgPath;
+ fileInput.placeholder = 'image.png';
+ fileInput.readOnly = true;
+ fileInput.style.flex = '1';
+
+ const browseBtn = document.createElement('button');
+ browseBtn.className = 'es-btn es-btn-icon es-btn-browse';
+ browseBtn.title = 'Browse';
+ browseBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 7v10a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-6l-2-2H5a2 2 0 0 0-2 2z"></path></svg>`;
+
+ const removeBtn = document.createElement('button');
+ removeBtn.className = 'es-btn es-btn-icon es-btn-clear';
+ removeBtn.title = 'Remove';
+ removeBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>`;
+
+ charInput.addEventListener('change', async () => {
+ const newChar = charInput.value;
+ if (newChar && newChar !== char) {
+ const g = fontData.glyphs as Record<string, string>;
+ delete g[char];
+ g[newChar] = imgPath;
+ await save();
+ rebuildList();
+ }
+ });
+
+ browseBtn.addEventListener('click', async () => {
+ try {
+ const result = await getPlatformAdapter().openFileDialog({
+ title: 'Select Glyph Image',
+ defaultPath: fontDir,
+ filters: [{ name: 'Images', extensions: ['png', 'jpg', 'jpeg', 'webp'] }],
+ });
+ if (result) {
+ const relativePath = this.toRelativeFromDir(result, fontDir);
+ if (relativePath) {
+ (fontData.glyphs as Record<string, string>)[char] = relativePath;
+ fileInput.value = relativePath;
+ await save();
+ }
+ }
+ } catch (err) {
+ console.error('Failed to open file dialog:', err);
+ }
+ });
+
+ removeBtn.addEventListener('click', async () => {
+ delete (fontData.glyphs as Record<string, string>)[char];
+ await save();
+ rebuildList();
+ });
+
+ const wrapper = document.createElement('div');
+ wrapper.className = 'es-file-editor';
+ wrapper.style.display = 'flex';
+ wrapper.style.gap = '4px';
+ wrapper.style.alignItems = 'center';
+ wrapper.style.width = '100%';
+ wrapper.appendChild(charInput);
+ wrapper.appendChild(fileInput);
+ wrapper.appendChild(browseBtn);
+ wrapper.appendChild(removeBtn);
+
+ row.appendChild(wrapper);
+ listContainer.appendChild(row);
+ }
+ };
+
+ rebuildList();
+ container.appendChild(listContainer);
+
+ const actionsRow = document.createElement('div');
+ actionsRow.className = 'es-bmfont-actions';
+ actionsRow.style.display = 'flex';
+ actionsRow.style.gap = '4px';
+ actionsRow.style.padding = '4px 0';
+
+ const addBtn = document.createElement('button');
+ addBtn.className = 'es-btn es-btn-small';
+ addBtn.textContent = 'Add Glyph';
+ addBtn.addEventListener('click', async () => {
+ const g = (fontData.glyphs ?? {}) as Record<string, string>;
+ let nextChar = 'A';
+ for (let i = 65; i < 127; i++) {
+ const c = String.fromCharCode(i);
+ if (!(c in g)) { nextChar = c; break; }
+ }
+ g[nextChar] = '';
+ fontData.glyphs = g;
+ await save();
+ rebuildList();
+ });
+
+ const importBtn = document.createElement('button');
+ importBtn.className = 'es-btn es-btn-small';
+ importBtn.textContent = 'Import Folder';
+ importBtn.addEventListener('click', async () => {
+ const fs = getNativeFS();
+ if (!fs) return;
+ try {
+ const sampleFile = await getPlatformAdapter().openFileDialog({
+ title: 'Select any image in the glyph folder',
+ defaultPath: fontDir,
+ filters: [{ name: 'Images', extensions: ['png', 'jpg', 'jpeg', 'webp'] }],
+ });
+ if (!sampleFile) return;
+ const normalized = sampleFile.replace(/\\/g, '/');
+ const folderPath = normalized.substring(0, normalized.lastIndexOf('/'));
+ const entries = await fs.listDirectoryDetailed(folderPath);
+ const imageExts = ['.png', '.jpg', '.jpeg', '.webp'];
+ const g = (fontData.glyphs ?? {}) as Record<string, string>;
+ for (const entry of entries) {
+ if (entry.isDirectory) continue;
+ const ext = entry.name.substring(entry.name.lastIndexOf('.')).toLowerCase();
+ if (!imageExts.includes(ext)) continue;
+ const charName = entry.name.substring(0, entry.name.lastIndexOf('.'));
+ if (!charName) continue;
+ const relativePath = this.toRelativeFromDir(`${folderPath}/${entry.name}`, fontDir);
+ if (relativePath) {
+ g[charName] = relativePath;
+ }
+ }
+ fontData.glyphs = g;
+ await save();
+ rebuildList();
+ } catch (err) {
+ console.error('Failed to import folder:', err);
+ }
+ });
+
+ actionsRow.appendChild(addBtn);
+ actionsRow.appendChild(importBtn);
+ container.appendChild(actionsRow);
+
+ const countDiv = document.createElement('div');
+ countDiv.className = 'es-property-value';
+ countDiv.style.padding = '2px 0';
+ countDiv.style.fontSize = '11px';
+ countDiv.style.opacity = '0.6';
+ countDiv.textContent = `${Object.keys(glyphs).length} glyphs`;
+ container.appendChild(countDiv);
+ }
+
+ private toRelativeFromDir(absolutePath: string, dir: string): string | null {
+ const normalized = absolutePath.replace(/\\/g, '/');
+ const normalizedDir = dir.replace(/\\/g, '/');
+ if (normalized.startsWith(normalizedDir + '/')) {
+ return normalized.substring(normalizedDir.length + 1);
+ }
+ return normalized.substring(normalized.lastIndexOf('/') + 1);
+ }
+
+ private createBmfontFileInput(
+ container: HTMLElement, label: string, value: string,
+ extensions: string[], filterName: string,
+ onChange: (v: string) => void
+ ): void {
+ const row = document.createElement('div');
+ row.className = 'es-property-row';
+ row.innerHTML = `<label class="es-property-label">${label}</label><div class="es-property-editor"></div>`;
+ const editor = row.querySelector('.es-property-editor')!;
+
+ const wrapper = document.createElement('div');
+ wrapper.className = 'es-file-editor';
+ const input = document.createElement('input');
+ input.type = 'text';
+ input.className = 'es-input es-input-file';
+ input.value = value;
+ input.placeholder = 'None';
+
+ const browseBtn = document.createElement('button');
+ browseBtn.className = 'es-btn es-btn-icon es-btn-browse';
+ browseBtn.title = 'Browse';
+ browseBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 7v10a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-6l-2-2H5a2 2 0 0 0-2 2z"></path></svg>`;
+
+ browseBtn.addEventListener('click', async () => {
+ const projectDir = this.getProjectDir();
+ if (!projectDir) return;
+ try {
+ const result = await getPlatformAdapter().openFileDialog({
+ title: `Select ${label}`,
+ defaultPath: `${projectDir}/assets`,
+ filters: [{ name: filterName, extensions: extensions.map(e => e.replace('.', '')) }],
+ });
+ if (result) {
+ const normalizedPath = result.replace(/\\/g, '/');
+ const assetsIndex = normalizedPath.indexOf('/assets/');
+ if (assetsIndex !== -1) {
+ const relativePath = normalizedPath.substring(assetsIndex + '/assets/'.length);
+ input.value = relativePath;
+ onChange(relativePath);
+ }
+ }
+ } catch (err) {
+ console.error('Failed to open file dialog:', err);
+ }
+ });
+
+ input.addEventListener('change', () => onChange(input.value));
+ wrapper.appendChild(input);
+ wrapper.appendChild(browseBtn);
+ editor.appendChild(wrapper);
+ container.appendChild(row);
+ }
+
private async renderFolderInspector(path: string): Promise<void> {
const fs = getNativeFS();
const projectDir = this.getProjectDir();
diff --git a/editor/src/property/editors.ts b/editor/src/property/editors.ts
index 2fdc948ff..11099b4ca 100644
--- a/editor/src/property/editors.ts
+++ b/editor/src/property/editors.ts
@@ -1449,6 +1449,130 @@ function createMaterialFileEditor(
};
}
+// =============================================================================
+// Bitmap Font File Editor
+// =============================================================================
+
+function createBitmapFontFileEditor(
+ container: HTMLElement,
+ ctx: PropertyEditorContext
+): PropertyEditorInstance {
+ const { value, onChange } = ctx;
+
+ const wrapper = document.createElement('div');
+ wrapper.className = 'es-file-editor';
+
+ const input = document.createElement('input');
+ input.type = 'text';
+ input.className = 'es-input es-input-file es-asset-link';
+ input.value = resolveDisplayName(String(value ?? ''));
+ input.placeholder = 'None';
+ input.readOnly = true;
+
+ const browseBtn = document.createElement('button');
+ browseBtn.className = 'es-btn es-btn-icon es-btn-browse';
+ browseBtn.title = 'Browse';
+ browseBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 7v10a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-6l-2-2H5a2 2 0 0 0-2 2z"></path></svg>`;
+
+ const clearBtn = document.createElement('button');
+ clearBtn.className = 'es-btn es-btn-icon es-btn-clear';
+ clearBtn.title = 'Clear';
+ clearBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>`;
+
+ input.addEventListener('click', () => {
+ if (input.value) {
+ navigateToAsset(input.value);
+ }
+ });
+
+ wrapper.addEventListener('dragover', (e) => {
+ e.preventDefault();
+ const data = e.dataTransfer?.types.includes('application/esengine-asset');
+ if (data) {
+ wrapper.classList.add('es-drag-over');
+ e.dataTransfer!.dropEffect = 'copy';
+ } else {
+ e.dataTransfer!.dropEffect = 'none';
+ }
+ });
+
+ wrapper.addEventListener('dragleave', () => {
+ wrapper.classList.remove('es-drag-over');
+ });
+
+ wrapper.addEventListener('drop', (e) => {
+ e.preventDefault();
+ wrapper.classList.remove('es-drag-over');
+
+ const jsonData = e.dataTransfer?.getData('application/esengine-asset');
+ if (!jsonData) return;
+
+ try {
+ const assetData = JSON.parse(jsonData);
+ if (assetData.type === 'font') {
+ const projectDir = getProjectDir();
+ if (projectDir && assetData.path.startsWith(projectDir)) {
+ const relativePath = assetData.path.substring(projectDir.length + 1);
+ const uuid = getAssetLibrary().getUuid(relativePath);
+ const ref = uuid ?? relativePath;
+ input.value = relativePath;
+ onChange(ref);
+ }
+ }
+ } catch (err) {
+ console.error('Failed to parse drop data:', err);
+ }
+ });
+
+ browseBtn.addEventListener('click', async () => {
+ const projectDir = getProjectDir();
+ if (!projectDir) return;
+
+ const assetsDir = `${projectDir}/assets`;
+
+ try {
+ const platform = getPlatformAdapter();
+ const result = await platform.openFileDialog({
+ title: 'Select BitmapFont',
+ defaultPath: assetsDir,
+ filters: [{ name: 'BitmapFont Files', extensions: ['bmfont'] }],
+ });
+ if (result) {
+ const normalizedPath = result.replace(/\\/g, '/');
+ const assetsIndex = normalizedPath.indexOf('/assets/');
+ if (assetsIndex !== -1) {
+ const relativePath = normalizedPath.substring(assetsIndex + 1);
+ const uuid = getAssetLibrary().getUuid(relativePath);
+ const ref = uuid ?? relativePath;
+ input.value = relativePath;
+ onChange(ref);
+ }
+ }
+ } catch (err) {
+ console.error('Failed to open file dialog:', err);
+ }
+ });
+
+ clearBtn.addEventListener('click', () => {
+ input.value = '';
+ onChange('');
+ });
+
+ wrapper.appendChild(input);
+ wrapper.appendChild(browseBtn);
+ wrapper.appendChild(clearBtn);
+ container.appendChild(wrapper);
+
+ return {
+ update(v: unknown) {
+ input.value = resolveDisplayName(String(v ?? ''));
+ },
+ dispose() {
+ wrapper.remove();
+ },
+ };
+}
+
// =============================================================================
// Register All Editors
// =============================================================================
@@ -1469,4 +1593,5 @@ export function registerBuiltinEditors(): void {
registerPropertyEditor('spine-animation', createSpineAnimationEditor);
registerPropertyEditor('spine-skin', createSpineSkinEditor);
registerPropertyEditor('material-file', createMaterialFileEditor);
+ registerPropertyEditor('bitmap-font-file', createBitmapFontFileEditor);
}
diff --git a/editor/src/scene/EditorSceneManager.ts b/editor/src/scene/EditorSceneManager.ts
index 254d8ba2c..ace67a705 100644
--- a/editor/src/scene/EditorSceneManager.ts
+++ b/editor/src/scene/EditorSceneManager.ts
@@ -9,13 +9,16 @@ import {
loadComponent,
LocalTransform,
Sprite,
+ BitmapText,
INVALID_TEXTURE,
+ INVALID_FONT,
TextRenderer,
TextAlign,
TextVerticalAlign,
TextOverflow,
type SceneComponentData,
type TextData,
+ type BitmapTextData,
type LocalTransformData,
type WorldTransformData,
} from 'esengine';
@@ -173,6 +176,10 @@ export class EditorSceneManager {
this.syncText(entity, comp.data, entityId);
break;
+ case 'BitmapText':
+ await this.syncBitmapText(entity, comp.data, entityId);
+ break;
+
case 'SpineAnimation':
await this.syncSpineAnimation(entity, comp.data, entityId);
break;
@@ -244,6 +251,9 @@ export class EditorSceneManager {
if (this.world_.has(entity, Sprite)) {
this.world_.remove(entity, Sprite);
}
+ if (this.world_.has(entity, BitmapText)) {
+ this.world_.remove(entity, BitmapText);
+ }
}
async showEntity(entityId: number): Promise<void> {
@@ -573,6 +583,34 @@ export class EditorSceneManager {
});
}
+ private async syncBitmapText(entity: Entity, data: any, _entityId: number): Promise<void> {
+ let fontHandle = INVALID_FONT as number;
+
+ const fontRef = data.font;
+ if (fontRef && typeof fontRef === 'string') {
+ try {
+ const fontPath = this.resolveAssetRef(fontRef);
+ fontHandle = await this.assetServer_.loadBitmapFont(fontPath);
+ } catch (err) {
+ console.warn(`[EditorSceneManager] Failed to load bitmap font: ${fontRef}`, err);
+ }
+ }
+
+ if (this.world_.has(entity, BitmapText)) {
+ this.world_.remove(entity, BitmapText);
+ }
+
+ this.world_.insert(entity, BitmapText, {
+ text: data.text ?? '',
+ color: data.color ?? { r: 1, g: 1, b: 1, a: 1 },
+ fontSize: data.fontSize ?? 1.0,
+ align: data.align ?? 0,
+ spacing: data.spacing ?? 0,
+ layer: data.layer ?? 0,
+ font: fontHandle,
+ });
+ }
+
private async syncSpineAnimation(entity: Entity, data: any, entityId: number): Promise<void> {
const skeletonRef = data.skeletonPath ?? '';
const atlasRef = data.atlasPath ?? '';
diff --git a/editor/src/schemas/ComponentSchemas.ts b/editor/src/schemas/ComponentSchemas.ts
index 770da4a3d..ab2ecfd5f 100644
--- a/editor/src/schemas/ComponentSchemas.ts
+++ b/editor/src/schemas/ComponentSchemas.ts
@@ -188,6 +188,28 @@ export const CanvasSchema: ComponentSchema = {
],
};
+export const BitmapTextSchema: ComponentSchema = {
+ name: 'BitmapText',
+ category: 'builtin',
+ properties: [
+ { name: 'text', type: 'string' },
+ { name: 'font', type: 'bitmap-font-file' },
+ { name: 'color', type: 'color' },
+ { name: 'fontSize', type: 'number', min: 0.1, step: 0.1 },
+ {
+ name: 'align',
+ type: 'enum',
+ options: [
+ { label: 'Left', value: 0 },
+ { label: 'Center', value: 1 },
+ { label: 'Right', value: 2 },
+ ],
+ },
+ { name: 'spacing', type: 'number', step: 0.1 },
+ { name: 'layer', type: 'number', min: -1000, max: 1000 },
+ ],
+};
+
export const SpineAnimationSchema: ComponentSchema = {
name: 'SpineAnimation',
category: 'builtin',
@@ -376,6 +398,7 @@ export function registerBuiltinSchemas(options?: BuiltinSchemaOptions): void {
registerComponentSchema(TextSchema);
registerComponentSchema(UIRectSchema);
registerComponentSchema(CanvasSchema);
+ registerComponentSchema(BitmapTextSchema);
registerComponentSchema(RigidBodySchema);
registerComponentSchema(BoxColliderSchema);
registerComponentSchema(CircleColliderSchema);
@@ -395,6 +418,15 @@ export function registerSpineSchema(): void {
// =============================================================================
const editorOnlyDefaults: Record<string, Record<string, unknown>> = {
+ BitmapText: {
+ text: 'BitmapText',
+ font: '',
+ color: { r: 1, g: 1, b: 1, a: 1 },
+ fontSize: 1.0,
+ align: 0,
+ spacing: 0,
+ layer: 0,
+ },
UIRect: {
size: { x: 100, y: 100 },
anchor: { x: 0.5, y: 0.5 },
@@ -414,15 +446,15 @@ const editorOnlyDefaults: Record<string, Record<string, unknown>> = {
};
export function getDefaultComponentData(typeName: string): Record<string, unknown> {
- const sdkDefaults = getComponentDefaults(typeName);
- if (sdkDefaults) {
- return sdkDefaults;
- }
-
const editorDefaults = editorOnlyDefaults[typeName];
if (editorDefaults) {
return { ...editorDefaults };
}
+ const sdkDefaults = getComponentDefaults(typeName);
+ if (sdkDefaults) {
+ return sdkDefaults;
+ }
+
return {};
}
diff --git a/editor/src/store/EditorStore.ts b/editor/src/store/EditorStore.ts
index 7dff38329..4c8358a45 100644
--- a/editor/src/store/EditorStore.ts
+++ b/editor/src/store/EditorStore.ts
@@ -24,7 +24,7 @@ import { isComponentRemovable } from '../schemas/ComponentSchemas';
// Types
// =============================================================================
-export type AssetType = 'image' | 'script' | 'scene' | 'audio' | 'json' | 'material' | 'shader' | 'file' | 'folder';
+export type AssetType = 'image' | 'script' | 'scene' | 'audio' | 'json' | 'material' | 'shader' | 'font' | 'file' | 'folder';
export interface AssetSelection {
path: string;
diff --git a/sdk/src/asset/AssetServer.ts b/sdk/src/asset/AssetServer.ts
index 5f7f6bfd7..567cf03c3 100644
--- a/sdk/src/asset/AssetServer.ts
+++ b/sdk/src/asset/AssetServer.ts
@@ -3,7 +3,7 @@
* @brief Asset loading and caching system
*/
-import type { Entity, TextureHandle } from '../types';
+import type { Entity, TextureHandle, FontHandle } from '../types';
import type { ESEngineModule } from '../wasm';
import type { ShaderHandle } from '../material';
import { Material } from '../material';
@@ -82,6 +82,7 @@ export class AssetServer {
private materialLoader_: MaterialLoader;
private canvas_: HTMLCanvasElement;
private ctx_: CanvasRenderingContext2D;
+ private fontCache_ = new AsyncCache<FontHandle>();
private embedded_ = new Map<string, string>();
constructor(module: ESEngineModule) {
@@ -151,7 +152,11 @@ export class AssetServer {
for (const info of this.textureCache_.values()) {
rm.releaseTexture(info.handle);
}
+ for (const handle of this.fontCache_.values()) {
+ rm.releaseBitmapFont(handle);
+ }
this.textureCache_.clear();
+ this.fontCache_.clear();
this.jsonCache_.clear();
this.textCache_.clear();
this.binaryCache_.clear();
@@ -245,6 +250,66 @@ export class AssetServer {
return this.loadedSpines_.has(`${skeletonPath}:${atlasPath}`);
}
+ // =========================================================================
+ // BitmapFont
+ // =========================================================================
+
+ async loadBitmapFont(fontPath: string, baseUrl?: string): Promise<FontHandle> {
+ const url = this.resolveUrl(fontPath, baseUrl);
+ return this.fontCache_.getOrLoad(url, async () => {
+ if (fontPath.endsWith('.bmfont')) {
+ return this.loadBmfontAsset(url);
+ }
+ return this.loadFntFile(url);
+ });
+ }
+
+ getFont(fontPath: string): FontHandle | undefined {
+ return this.fontCache_.get(fontPath);
+ }
+
+ releaseFont(fontPath: string): void {
+ const handle = this.fontCache_.get(fontPath);
+ if (handle) {
+ const rm = this.module_.getResourceManager();
+ rm.releaseBitmapFont(handle);
+ this.fontCache_.delete(fontPath);
+ }
+ }
+
+ private async loadBmfontAsset(url: string): Promise<FontHandle> {
+ const json = await this.fetchJson(url) as {
+ type: string;
+ fntFile?: string;
+ generatedFnt?: string;
+ };
+ const dir = url.substring(0, url.lastIndexOf('/'));
+
+ const fntFile = json.type === 'label-atlas'
+ ? json.generatedFnt
+ : json.fntFile;
+
+ if (!fntFile) {
+ throw new Error(`Invalid bmfont asset: no fnt file specified`);
+ }
+ const fntUrl = dir ? `${dir}/${fntFile}` : fntFile;
+ return this.loadFntFile(fntUrl);
+ }
+
+ private async loadFntFile(url: string): Promise<FontHandle> {
+ const fntContent = await this.fetchText(url);
+ const pageMatch = fntContent.match(/file="([^"]+)"/);
+ if (!pageMatch) {
+ throw new Error(`No page texture found in .fnt file: ${url}`);
+ }
+ const texName = pageMatch[1];
+ const fntDir = url.substring(0, url.lastIndexOf('/'));
+ const texUrl = fntDir ? `${fntDir}/${texName}` : texName;
+ const texInfo = await this.loadTextureRaw(texUrl);
+ const rm = this.module_.getResourceManager();
+ return rm.loadBitmapFont(fntContent, texInfo.handle, texInfo.width, texInfo.height) as FontHandle;
+ }
+
// =========================================================================
// Material & Shader
// =========================================================================
diff --git a/sdk/src/component.ts b/sdk/src/component.ts
index 181aa7198..cee90479d 100644
--- a/sdk/src/component.ts
+++ b/sdk/src/component.ts
@@ -3,7 +3,7 @@
* @brief Component definition and builtin components
*/
-import { Entity, Vec2, Vec3, Color, Quat, INVALID_TEXTURE } from './types';
+import { Entity, Vec2, Vec3, Color, Quat, INVALID_TEXTURE, INVALID_FONT } from './types';
import {
RigidBody, BoxCollider, CircleCollider, CapsuleCollider,
type RigidBodyData, type BoxColliderData, type CircleColliderData, type CapsuleColliderData,
@@ -201,6 +201,16 @@ export interface SpineAnimationData {
material: number;
}
+export interface BitmapTextData {
+ text: string;
+ color: Color;
+ fontSize: number;
+ align: number;
+ spacing: number;
+ layer: number;
+ font: number;
+}
+
export interface NameData {
value: string;
}
@@ -271,6 +281,16 @@ export const Children = defineBuiltin<ChildrenData>('Children', {
entities: []
});
+export const BitmapText = defineBuiltin<BitmapTextData>('BitmapText', {
+ text: '',
+ color: { r: 1, g: 1, b: 1, a: 1 },
+ fontSize: 1.0,
+ align: 0,
+ spacing: 0,
+ layer: 0,
+ font: INVALID_FONT,
+});
+
export const SpineAnimation = defineBuiltin<SpineAnimationData>('SpineAnimation', {
skeletonPath: '',
atlasPath: '',
@@ -324,6 +344,7 @@ const builtinComponents: Record<string, BuiltinComponentDef<any>> = {
Velocity,
Parent,
Children,
+ BitmapText,
SpineAnimation,
RigidBody,
BoxCollider,
diff --git a/sdk/src/core.ts b/sdk/src/core.ts
index 7ea08a335..9e920cf4d 100644
--- a/sdk/src/core.ts
+++ b/sdk/src/core.ts
@@ -12,6 +12,8 @@ export {
INVALID_ENTITY,
type TextureHandle,
INVALID_TEXTURE,
+ type FontHandle,
+ INVALID_FONT,
type Vec2,
type Vec3,
type Vec4,
@@ -47,6 +49,7 @@ export {
Velocity,
Parent,
Children,
+ BitmapText,
SpineAnimation,
type LocalTransformData,
type WorldTransformData,
@@ -56,6 +59,7 @@ export {
type VelocityData,
type ParentData,
type ChildrenData,
+ type BitmapTextData,
type SpineAnimationData,
RigidBody,
BoxCollider,
diff --git a/sdk/src/renderPipeline.ts b/sdk/src/renderPipeline.ts
index 377917d47..7d616e0ee 100644
--- a/sdk/src/renderPipeline.ts
+++ b/sdk/src/renderPipeline.ts
@@ -52,6 +52,7 @@ export class RenderPipeline {
Renderer.clearBuffers(3);
Renderer.begin(viewProjection);
Renderer.submitSprites(registry);
+ Renderer.submitBitmapText(registry);
if (this.spineRenderer_) {
this.spineRenderer_(registry, elapsed);
} else {
@@ -74,6 +75,7 @@ export class RenderPipeline {
Renderer.begin(viewProjection);
Renderer.submitSprites(registry);
+ Renderer.submitBitmapText(registry);
if (this.spineRenderer_) {
this.spineRenderer_(registry, elapsed);
} else {
diff --git a/sdk/src/renderer.ts b/sdk/src/renderer.ts
index 8a3f984bd..b44f85825 100644
--- a/sdk/src/renderer.ts
+++ b/sdk/src/renderer.ts
@@ -13,6 +13,7 @@ export interface RenderStats {
drawCalls: number;
triangles: number;
sprites: number;
+ text: number;
spine: number;
meshes: number;
culled: number;
@@ -62,6 +63,11 @@ export const Renderer = {
module.renderer_submitSprites(registry._cpp);
},
+ submitBitmapText(registry: { _cpp: CppRegistry }): void {
+ if (!module) return;
+ module.renderer_submitBitmapText(registry._cpp);
+ },
+
submitSpine(registry: { _cpp: CppRegistry }): void {
if (!module) return;
module.renderer_submitSpine?.(registry._cpp);
@@ -105,12 +111,13 @@ export const Renderer = {
getStats(): RenderStats {
if (!module) {
- return { drawCalls: 0, triangles: 0, sprites: 0, spine: 0, meshes: 0, culled: 0 };
+ return { drawCalls: 0, triangles: 0, sprites: 0, text: 0, spine: 0, meshes: 0, culled: 0 };
}
return {
drawCalls: module.renderer_getDrawCalls(),
triangles: module.renderer_getTriangles(),
sprites: module.renderer_getSprites(),
+ text: module.renderer_getText(),
spine: module.renderer_getSpine?.() ?? 0,
meshes: module.renderer_getMeshes(),
culled: module.renderer_getCulled(),
diff --git a/sdk/src/scene.ts b/sdk/src/scene.ts
index 43248f4b9..b375ed3f9 100644
--- a/sdk/src/scene.ts
+++ b/sdk/src/scene.ts
@@ -10,6 +10,7 @@ import {
Sprite,
Camera,
Canvas,
+ BitmapText,
SpineAnimation,
RigidBody,
BoxCollider,
@@ -21,6 +22,7 @@ import {
type SpriteData,
type CameraData,
type CanvasData,
+ type BitmapTextData,
type SpineAnimationData,
type RigidBodyData,
type BoxColliderData,
@@ -153,6 +155,22 @@ export async function loadSceneWithAssets(
}
}
+ if (compData.type === 'BitmapText' && assetServer) {
+ const data = compData.data as Record<string, unknown>;
+ if (typeof data.font === 'string' && data.font) {
+ try {
+ const handle = await assetServer.loadBitmapFont(
+ data.font,
+ options?.assetBaseUrl
+ );
+ data.font = handle;
+ } catch (err) {
+ console.warn(`Failed to load bitmap font: ${data.font}`, err);
+ data.font = 0;
+ }
+ }
+ }
+
if (compData.type === 'SpineAnimation' && assetServer) {
const data = compData.data as Record<string, unknown>;
const skeletonPath = data.skeletonPath as string;
@@ -225,6 +243,9 @@ export function loadComponent(world: World, entity: Entity, compData: SceneCompo
case 'Text':
world.insert(entity, Text, data as TextData);
break;
+ case 'BitmapText':
+ world.insert(entity, BitmapText, data as BitmapTextData);
+ break;
case 'SpineAnimation':
world.insert(entity, SpineAnimation, data as SpineAnimationData);
break;
diff --git a/sdk/src/types.ts b/sdk/src/types.ts
index e83c34774..eaf51a468 100644
--- a/sdk/src/types.ts
+++ b/sdk/src/types.ts
@@ -13,6 +13,9 @@ export const INVALID_ENTITY = 0 as Entity;
export type TextureHandle = number;
export const INVALID_TEXTURE = 0xFFFFFFFF as TextureHandle;
+export type FontHandle = number;
+export const INVALID_FONT = 0 as FontHandle;
+
// =============================================================================
// Math Types
// =============================================================================
diff --git a/sdk/src/ui/TextPlugin.ts b/sdk/src/ui/TextPlugin.ts
index e1afd6cfb..58a4083e5 100644
--- a/sdk/src/ui/TextPlugin.ts
+++ b/sdk/src/ui/TextPlugin.ts
@@ -29,6 +29,7 @@ export class TextPlugin implements Plugin {
app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(
[],
() => {
+ renderer.cleanupOrphaned(e => world.valid(e) && world.has(e, Text));
const entities = world.getEntitiesWithComponents([Text]);
for (const entity of entities) {
@@ -52,9 +53,12 @@ export class TextPlugin implements Plugin {
const sprite = world.get(entity, Sprite) as SpriteData;
sprite.texture = result.textureHandle;
- sprite.size = { x: result.width, y: result.height };
- sprite.uvOffset = { x: 0, y: 0 };
- sprite.uvScale = { x: 1, y: 1 };
+ sprite.size.x = result.width;
+ sprite.size.y = result.height;
+ sprite.uvOffset.x = 0;
+ sprite.uvOffset.y = 0;
+ sprite.uvScale.x = 1;
+ sprite.uvScale.y = 1;
world.insert(entity, Sprite, sprite);
text.dirty = false;
diff --git a/sdk/src/ui/TextRenderer.ts b/sdk/src/ui/TextRenderer.ts
index 8c4ec3538..67bc3b239 100644
--- a/sdk/src/ui/TextRenderer.ts
+++ b/sdk/src/ui/TextRenderer.ts
@@ -195,6 +195,16 @@ export class TextRenderer {
}
}
+ cleanupOrphaned(isAlive: (entity: Entity) => boolean): void {
+ const rm = this.module.getResourceManager();
+ for (const [entity, result] of this.cache) {
+ if (!isAlive(entity)) {
+ rm.releaseTexture(result.textureHandle);
+ this.cache.delete(entity);
+ }
+ }
+ }
+
/**
* Releases all cached textures
*/
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index b23c0c34f..64bc36db1 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -80,6 +80,11 @@ export interface CppRegistry {
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;
@@ -98,6 +103,9 @@ export interface CppResourceManager {
releaseShader(handle: number): void;
setTextureMetadata(handle: number, left: number, right: number, top: number, bottom: number): void;
registerTextureWithPath(handle: number, path: string): void;
+ loadBitmapFont(fntContent: string, textureHandle: number, texWidth: number, texHeight: number): number;
+ createLabelAtlasFont(textureHandle: number, texWidth: number, texHeight: number, chars: string, charWidth: number, charHeight: number): number;
+ releaseBitmapFont(handle: number): void;
}
// =============================================================================
@@ -212,6 +220,7 @@ export interface ESEngineModule {
renderer_flush(): void;
renderer_end(): void;
renderer_submitSprites(registry: CppRegistry): void;
+ renderer_submitBitmapText(registry: CppRegistry): void;
renderer_submitSpine?(registry: CppRegistry): void;
renderer_submitTriangles(
verticesPtr: number, vertexCount: number,
@@ -226,6 +235,7 @@ export interface ESEngineModule {
renderer_getDrawCalls(): number;
renderer_getTriangles(): number;
renderer_getSprites(): number;
+ renderer_getText(): number;
renderer_getSpine?(): number;
renderer_getMeshes(): number;
renderer_getCulled(): number;
diff --git a/src/esengine/renderer/RenderFrame.cpp b/src/esengine/renderer/RenderFrame.cpp
index 7ec11f8f2..d800793cd 100644
--- a/src/esengine/renderer/RenderFrame.cpp
+++ b/src/esengine/renderer/RenderFrame.cpp
@@ -979,8 +979,10 @@ void RenderFrame::renderText(u32 begin, u32 end) {
f32 posX = cursorX + (glyph->xOffset + glyph->width * 0.5f) * scale;
f32 posY = baseY + (fontBase - glyph->yOffset - glyph->height * 0.5f) * scale;
- glm::vec2 uvOffset(glyph->x / texW, glyph->y / texH);
- glm::vec2 uvScale(glyph->width / texW, glyph->height / texH);
+ f32 uvY = glyph->y / texH;
+ f32 uvH = glyph->height / texH;
+ glm::vec2 uvOffset(glyph->x / texW, uvY + uvH);
+ glm::vec2 uvScale(glyph->width / texW, -uvH);
batcher_->drawQuad(
glm::vec2(posX, posY),