Skip to content

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

refactor: change Color type from {x,y,z,w} to {r,g,b,a}

esenginee5081bd5f39d
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.js
index e1c11fa5d..260cd3368 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 n(e){return t().readFile(e)}async function s(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,n)=>{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,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];r({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,r="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(r).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function c(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const 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,n)=>{h().readFile({filePath:e,encoding:t,success:e=>{r(e.data)},fail:t=>{n(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 x(e){return new Promise((t,r)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>r(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function g(e){const{width:t,height:r}=e,{ctx:n}=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);n.clearRect(0,0,t,r),n.drawImage(e,0,0);const s=n.getImageData(0,0,t,r);return{width:t,height:r,pixels:new Uint8Array(s.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(),n=r.get(e);if(n)return n;const s=M(e,t);return r.set(e,s),B(e,t,!1),s}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 z=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}}),W=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}}),k=I("Sprite",{texture:v,color:{x:1,y:1,z:1,w:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),L=I("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0}),$=I("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w: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:{x:1,y:1,z:1,w:1},layer:0,skeletonScale:1,material:0}),G={LocalTransform:z,WorldTransform:W,Sprite:k,Camera:L,Canvas:$,Velocity:H,Parent:O,Children:N,SpineAnimation:V,RigidBody:S,BoxCollider:P,CircleCollider:C,CapsuleCollider:T};let X=0;function j(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 Y{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 K{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 Y(this.get(e),t=>this.set(e,t))}}const J=j({delta:0,elapsed:0,frameCount:0},"Time");function Q(e){return"object"==typeof e&&null!==e&&"mut"===e._type}class Z{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return Q(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:n}=this.descriptor_,s=e.map(e=>this.getActualComponent(e)),o=[...s,...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 n)if(this.world_.has(e,t)){r=!0;break}if(r)continue;const o=s.map(t=>this.world_.get(e,t));for(const e of t)l.push({component:s[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 ee{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let 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 te{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ee(this,null);return this.spawned_.push(e),e}entity(e){return new ee(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,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 re;exports.Schedule=void 0,(re=exports.Schedule||(exports.Schedule={}))[re.Startup=0]="Startup",re[re.First=1]="First",re[re.PreUpdate=2]="PreUpdate",re[re.Update=3]="Update",re[re.PostUpdate=4]="PostUpdate",re[re.Last=5]="Last",re[re.FixedPreUpdate=10]="FixedPreUpdate",re[re.FixedUpdate=11]="FixedUpdate",re[re.FixedPostUpdate=12]="FixedPostUpdate";let ne=0;function se(e,t,r){const n=++ne;return{_id:Symbol(`System_${n}_${r?.name??""}`),_params:e,_fn:t,_name:r?.name??`System_${n}`}}function oe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class ie{constructor(e,t){this.world_=e,this.resources_=t}run(e){const t=e._params.map(e=>this.resolveParam(e));e._fn(...t);for(const e of t)e instanceof te&&e.flush()}resolveParam(e){switch(e._type){case"query":return new Z(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new te(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class ae{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const le=j(new ae,"Input");class ce{constructor(e){this.target_=e??null}build(e){const r=new ae;e.insertResource(le,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,n){r.mouseX=t,r.mouseY=n,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,se([],()=>{r.keysPressed.clear(),r.keysReleased.clear(),r.mouseButtonsPressed.clear(),r.mouseButtonsReleased.clear(),r.scrollDeltaX=0,r.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ue=new ce;class he{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 n={...t._default,...r};if(this.cppRegistry_){const r=`add${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e,n)}return n}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const r=`get${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const r=`has${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const r=`remove${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e)}insertScript(e,t,r){const n=t.create(r);return this.getStorage(t).set(e,n),n}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 n=!0;for(const t of e)if(!this.has(r,t)){n=!1;break}n&&t.push(r)}return t}}var de,pe,fe;exports.TextAlign=void 0,(de=exports.TextAlign||(exports.TextAlign={}))[de.Left=0]="Left",de[de.Center=1]="Center",de[de.Right=2]="Right",exports.TextVerticalAlign=void 0,(pe=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[pe.Top=0]="Top",pe[pe.Middle=1]="Middle",pe[pe.Bottom=2]="Bottom",exports.TextOverflow=void 0,(fe=exports.TextOverflow||(exports.TextOverflow={}))[fe.Visible=0]="Visible",fe[fe.Clip=1]="Clip",fe[fe.Ellipsis=2]="Ellipsis";const me=U("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2,dirty:!0});class _e{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,n=this.canvas;r.font=`${e.fontSize}px ${e.fontFamily}`;const s=t&&t.size.x>0&&t.size.y>0,o=s?t.size.x:0,i=s?t.size.y:0,a=e.wordWrap&&s;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=s?Math.ceil(o):h+2*u,f=s?Math.ceil(i):d+2*u;if(s&&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(n.width<p||n.height<f){const e=Math.max(n.width,this.nextPowerOf2(p)),t=Math.max(n.height,this.nextPowerOf2(f));n.width=e,n.height=t}const m=Math.round(255*e.color.x),_=Math.round(255*e.color.y),x=Math.round(255*e.color.z),g=e.color.w;r.clearRect(0,0,n.width,n.height),r.font=`${e.fontSize}px ${e.fontFamily}`,r.textAlign=this.mapAlign(e.align),r.textBaseline="top",r.fillStyle=`rgba(${m}, ${_}, ${x}, ${g})`,s&&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(s)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 n;switch(e.align){case exports.TextAlign.Left:n=u;break;case exports.TextAlign.Center:n=p/2;break;case exports.TextAlign.Right:n=p-u;break;default:n=u}r.fillText(t,n,v),v+=c}s&&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 n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const s=this.renderText(t,r);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 r=e.split("\n"),n=[];for(const e of r){if(!e){n.push("");continue}let r="";for(const s of e){const e=r+s;this.ctx.measureText(e).width>t&&r?(n.push(r),r=s):r=e}r&&n.push(r)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const r of e){const e=this.ctx.measureText(r),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const xe=U("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class ge{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const r=new _e(t),n=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,se([],()=>{const e=n.getEntitiesWithComponents([me]);for(const t of e){const e=n.get(t,me);if(!e.dirty)continue;n.has(t,k)||n.insert(t,k,{texture:v,size:{x:0,y:0},color:{x:1,y:1,z:1,w:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const s=n.has(t,xe)?n.get(t,xe):null,o=r.renderForEntity(t,e,s),i=n.get(t,k);i.texture=o.textureHandle,i.size={x:o.width,y:o.height},i.uvOffset={x:0,y:0},i.uvScale={x:1,y:1},n.insert(t,k,i),e.dirty=!1}}))}}const ye=new ge;var we;function ve(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(we=exports.BlendMode||(exports.BlendMode={}))[we.Normal=0]="Normal",we[we.Additive=1]="Additive",we[we.Multiply=2]="Multiply",we[we.Screen=3]="Screen",we[we.PremultipliedAlpha=4]="PremultipliedAlpha";let be=null,Se=null,Pe=1;const Ce=new Map;function Te(e){be=e,Se=e.getResourceManager(),Ie()}function Ae(){0!==Ue&&be&&(be._free(Ue),Ue=0),Ce.clear(),Pe=1,Re=!1,Se=null,be=null}function Ee(){if(!Se)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Se}const Me={createShader:(e,t)=>Ee().createShader(e,t),releaseShader(e){e>0&&Ee().releaseShader(e)},create(e){const t=Pe++,r={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))r.uniforms.set(t,n);return Ce.set(t,r),t},get:e=>Ce.get(e),setUniform(e,t,r){const n=Ce.get(e);n&&n.uniforms.set(t,r)},getUniform(e,t){const r=Ce.get(e);return r?.uniforms.get(t)},setBlendMode(e,t){const r=Ce.get(e);r&&(r.blendMode=t)},getBlendMode(e){const t=Ce.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const r=Ce.get(e);r&&(r.depthTest=t)},getShader(e){const t=Ce.get(e);return t?.shader??0},release(e){Ce.delete(e)},isValid:e=>Ce.has(e),createFromAsset(e,t){const r={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)r[t]=n;else if("object"==typeof n&&null!==n){const e=n;"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=Ce.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const r=Pe++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Ce.set(r,n),r},toAssetData(e,t){const r=Ce.get(e);if(!r)return null;const n={};for(const[e,t]of r.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:r.blendMode,depthTest:r.depthTest,properties:n}},getUniforms(e){const t=Ce.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Re=!1,Ue=0;const Fe=4096;function Be(e){const t=(0===Ue&&be&&(Ue=be._malloc(Fe)),Ue);if(0===t||!be)return{ptr:0,count:0};let r=0,n=0;const s=be.HEAPU8,o=be.HEAPU32,i=be.HEAPF32;for(const[a,l]of e){if(r+128>Fe)break;const e=(new TextEncoder).encode(a),c=e.length,u=4*Math.ceil(c/4);o[t+r>>2]=c,r+=4,s.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;n++}return{ptr:t,count:n}}function Ie(){if(!be||Re)return;be.materialDataProvider=(e,t,r,n,s)=>{const o=Ce.get(e);if(!o)return be.HEAPU32[t>>2]=0,be.HEAPU32[r>>2]=0,be.HEAPU32[n>>2]=0,void(be.HEAPU32[s>>2]=0);be.HEAPU32[t>>2]=o.shader,be.HEAPU32[r>>2]=o.blendMode;const{ptr:i,count:a}=Be(o.uniforms);be.HEAPU32[n>>2]=i,be.HEAPU32[s>>2]=a},Re=!0}const De={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 ze{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 n=this.loadInternal(e);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)}release(e){const t=this.cache_.get(e);t&&(Me.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Me.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 s(t);if(!r)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(r);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const i=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(i);return{handle:Me.createFromAsset(n,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const r=e.substring(0,e.lastIndexOf("/"));return r?`${r}/${t}`:t}}function We(e,t){const r=new Map;for(const n of t.entities){const t=e.spawn();r.set(n.id,t);for(const r of n.components)Le(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)}return r}async function ke(e,t,r){const n=new Map,s=r?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();n.set(i.id,t);for(const n of i.components){if("Sprite"===n.type&&s){const e=n.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,n=t.startsWith("data:")?t:r?.assetBaseUrl?`${r.assetBaseUrl}/${t}`:`/${t}`;try{const r=await s.loadTexture(n);e.texture=r.handle,o.set(t,n)}catch(t){console.warn(`Failed to load texture: ${n}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await s.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"===n.type&&s){const e=n.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await s.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 s.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Le(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)}if(s&&t.textureMetadata)for(const[e,r]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&r.sliceBorder&&s.setTextureMetadataByPath(t,r.sliceBorder)}return n}function Le(e,t,r){const n=r.data;switch(r.type){case"LocalTransform":e.insert(t,z,n);break;case"Sprite":e.insert(t,k,n);break;case"Camera":e.insert(t,L,n);break;case"Canvas":e.insert(t,$,n);break;case"Text":e.insert(t,me,n);break;case"SpineAnimation":e.insert(t,V,n);break;case"UIRect":e.insert(t,xe,n);break;case"RigidBody":e.insert(t,S,n);break;case"BoxCollider":e.insert(t,P,n);break;case"CircleCollider":e.insert(t,C,n);break;case"CapsuleCollider":e.insert(t,T,n);break;default:{const s=F(r.type);s?e.insert(t,s,n):console.warn(`Unknown component type: ${r.type}`);break}}}class $e{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 n=this.pending_.get(e);if(n)return n;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 He{constructor(e){this.textureCache_=new $e,this.shaderCache_=new $e,this.jsonCache_=new $e,this.textCache_=new $e,this.binaryCache_=new $e,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 ze(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 n=this.textureCacheKey(e,r),s=this.textureCache_.get(n);s&&(t.releaseTexture(s.handle),this.textureCache_.delete(n))}}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 n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const s=this.resolveUrl(t,r),o=await this.fetchText(s);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,n=this.resolveUrl(t,r);try{const e=await this.loadTextureRaw(n);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(n),{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 ke(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 n of e.textures)r.push(this.loadTexture(n).then(e=>{t.textures.set(n,e)}));if(e.materials)for(const n of e.materials)r.push(this.loadMaterial(n).then(e=>{t.materials.set(n,e)}));if(e.spine)for(const n of e.spine){const e=`${n.skeleton}:${n.atlas}`;r.push(this.loadSpine(n.skeleton,n.atlas,n.baseUrl).then(r=>{t.spine.set(e,r)}))}if(e.json)for(const n of e.json)r.push(this.loadJson(n).then(e=>{t.json.set(n,e)}));if(e.text)for(const n of e.text)r.push(this.loadText(n).then(e=>{t.text.set(n,e)}));if(e.binary)for(const n of e.binary)r.push(this.loadBinary(n).then(e=>{t.binary.set(n,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,n=this.embedded_.get(r)??r;return new Promise((r,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void r(e)}catch{}r(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=n})}createTextureFromImage(e,t){const{width:r,height:n}=e,s=this.getWebGL2Context();return s?this.createTextureWebGL2(s,e,r,n,t):this.createTextureFallback(e,r,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,r,n,s){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),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 i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,r,n),width:r,height:n}}createTextureFallback(e,t,r,n){(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 s=this.ctx_.getImageData(0,0,t,r),o=new Uint8Array(s.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,n);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 n=255/r;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e;if(!await o(t))throw new Error(`Shader file not found: ${e}`);const r=await s(t);if(!r)throw new Error(`Failed to read shader file: ${e}`);const{vertex:n,fragment:i}=this.parseEsShader(r);if(!n||!i)throw new Error(`Invalid shader format: ${e}`);return Me.createShader(n,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 s(t);return JSON.parse(r)}const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):s(t)}const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):n(t)}const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const 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 n=r.split("/").filter(e=>e);let s="";for(const e of n){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 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 Oe=j(null,"Assets");class Ne{build(e){const t=e.wasmModule;t?e.insertResource(Oe,new He(t)):console.warn("AssetPlugin: No WASM module available")}}const Ve=new Ne;let Ge=null,Xe=0,je=0,qe=0;const Ye=new Float32Array(256);function Ke(e){Ge=e,Xe=Ge._malloc(64),je=Ge._malloc(64),qe=Ge._malloc(1024)}function Je(){Ge&&(Xe&&(Ge._free(Xe),Xe=0),je&&(Ge._free(je),je=0),qe&&(Ge._free(qe),qe=0)),Ge=null}function Qe(){if(!Ge)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Ge}const Ze={x:1,y:1,z:1,w:1},et={begin(e){const t=Qe();t.HEAPF32.set(e,Xe/4),t.draw_begin(Xe)},end(){Qe().draw_end()},line(e,t,r,n=1){Qe().draw_line(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,n)},rect(e,t,r,n=!0){Qe().draw_rect(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,n)},rectOutline(e,t,r,n=1){Qe().draw_rectOutline(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,n)},circle(e,t,r,n=!0,s=32){Qe().draw_circle(e.x,e.y,t,r.x,r.y,r.z,r.w,n,s)},circleOutline(e,t,r,n=1,s=32){Qe().draw_circleOutline(e.x,e.y,t,r.x,r.y,r.z,r.w,n,s)},texture(e,t,r,n=Ze){Qe().draw_texture(e.x,e.y,t.x,t.y,r,n.x,n.y,n.z,n.w)},textureRotated(e,t,r,n,s=Ze){Qe().draw_textureRotated(e.x,e.y,t.x,t.y,r,n,s.x,s.y,s.z,s.w)},setLayer(e){Qe().draw_setLayer(e)},setDepth(e){Qe().draw_setDepth(e)},getDrawCallCount:()=>Ge?Ge.draw_getDrawCallCount():0,getPrimitiveCount:()=>Ge?Ge.draw_getPrimitiveCount():0,setBlendMode(e){Qe().draw_setBlendMode(e)},setDepthTest(e){Qe().draw_setDepthTest(e)},drawMesh(e,t,r){const n=Qe();n.HEAPF32.set(r,je/4),n.draw_mesh(e,t,je)},drawMeshWithMaterial(e,t,r){const n=Qe(),s=Me.get(t);if(!s)return;if(et.setBlendMode(s.blendMode),et.setDepthTest(s.depthTest),0===s.uniforms.size)return void et.drawMesh(e,s.shader,r);n.HEAPF32.set(r,je/4);let o=0,i=0;for(const[e,t]of s.uniforms){const r=rt(e);if(!(r<0)){if(ve(t))Ye[o++]=10,Ye[o++]=r,Ye[o++]=t.slot??i++,Ye[o++]=t.textureId;else if("number"==typeof t)Ye[o++]=1,Ye[o++]=r,Ye[o++]=t;else if(Array.isArray(t)){Ye[o++]=t.length,Ye[o++]=r;for(let e=0;e<t.length;e++)Ye[o++]=t[e]}else"w"in t?(Ye[o++]=4,Ye[o++]=r,Ye[o++]=t.x,Ye[o++]=t.y,Ye[o++]=t.z,Ye[o++]=t.w):"z"in t?(Ye[o++]=3,Ye[o++]=r,Ye[o++]=t.x,Ye[o++]=t.y,Ye[o++]=t.z):(Ye[o++]=2,Ye[o++]=r,Ye[o++]=t.x,Ye[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(n.HEAPF32.set(Ye.subarray(0,o),qe/4),n.draw_meshWithUniforms(e,s.shader,je,qe,o)):n.draw_mesh(e,s.shader,je)}},tt={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 rt(e){return tt[e]??-1}var nt;exports.DataType=void 0,(nt=exports.DataType||(exports.DataType={}))[nt.Float=1]="Float",nt[nt.Float2=2]="Float2",nt[nt.Float3=3]="Float3",nt[nt.Float4=4]="Float4",nt[nt.Int=5]="Int",nt[nt.Int2=6]="Int2",nt[nt.Int3=7]="Int3",nt[nt.Int4=8]="Int4";let st=null,ot=0,it=0,at=0;function lt(e){st=e,ot=st._malloc(262144),it=st._malloc(65536),at=st._malloc(256)}function ct(){st&&(ot&&st._free(ot),it&&st._free(it),at&&st._free(at),ot=0,it=0,at=0),st=null}function ut(){if(!st)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return st}const ht={create(e){const t=ut(),r=t.geometry_create();if(0===r)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,ot/4);const s=e.layout.length,o=new Int32Array(s);for(let t=0;t<s;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,at,s).set(o),t.geometry_init(r,ot,n,at,s,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,it,n).set(e.indices),t.geometry_setIndices16(r,it,n)}else{new Uint32Array(t.HEAPU8.buffer,it,n).set(e.indices),t.geometry_setIndices32(r,it,n)}}return r},updateVertices(e,t,r=0){const n=ut(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);n.HEAPF32.set(t,ot/4),n.geometry_updateVertices(e,ot,s,r)},release(e){e>0&&ut().geometry_release(e)},isValid:e=>!(!st||e<=0)&&st.geometry_isValid(e),createQuad(e=1,t=1){const r=e/2,n=t/2;return ht.create({vertices:new Float32Array([-r,-n,0,0,r,-n,1,0,r,n,1,1,-r,n,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const r=[],n=[];r.push(0,0,.5,.5);for(let n=0;n<=t;n++){const s=n/t*Math.PI*2,o=Math.cos(s)*e,i=Math.sin(s)*e,a=(Math.cos(s)+1)/2,l=(Math.sin(s)+1)/2;r.push(o,i,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return ht.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,r=1/0,n=-1/0,s=-1/0;for(const o of e)t=Math.min(t,o.x),r=Math.min(r,o.y),n=Math.max(n,o.x),s=Math.max(s,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-r)/(s-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 ht.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 dt=null;function pt(e){dt=e}function ft(){dt&&_t.isInitialized()&&_t.shutdown(),dt=null}function mt(){if(!dt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return dt}const _t={init:(e,t)=>mt().postprocess_init(e,t),shutdown(){mt().postprocess_shutdown()},resize(e,t){mt().postprocess_resize(e,t)},addPass:(e,t)=>mt().postprocess_addPass(e,t),removePass(e){mt().postprocess_removePass(e)},setEnabled(e,t){mt().postprocess_setPassEnabled(e,t)},isEnabled:e=>mt().postprocess_isPassEnabled(e),setUniform(e,t,r){mt().postprocess_setUniformFloat(e,t,r)},setUniformVec4(e,t,r){mt().postprocess_setUniformVec4(e,t,r.x,r.y,r.z,r.w)},begin(){mt().postprocess_begin()},end(){mt().postprocess_end()},getPassCount:()=>mt().postprocess_getPassCount(),isInitialized:()=>!!dt&&dt.postprocess_isInitialized(),setBypass(e){mt().postprocess_setBypass(e)},isBypassed:()=>!dt||dt.postprocess_isBypassed(),createBlur:()=>Me.createShader(xt,"#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:()=>Me.createShader(xt,"#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:()=>Me.createShader(xt,"#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:()=>Me.createShader(xt,"#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")},xt="#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 gt;exports.RenderStage=void 0,(gt=exports.RenderStage||(exports.RenderStage={}))[gt.Background=0]="Background",gt[gt.Opaque=1]="Opaque",gt[gt.Transparent=2]="Transparent",gt[gt.Overlay=3]="Overlay";let yt=null,wt=0;function vt(e){yt=e,wt=yt._malloc(64)}function bt(){yt&&wt&&(yt._free(wt),wt=0),yt=null}const St={init(e,t){yt?.renderer_init(e,t)},resize(e,t){yt?.renderer_resize(e,t)},begin(e,t){yt&&wt&&(yt.HEAPF32.set(e,wt/4),yt.renderer_begin(wt,t??0))},flush(){yt?.renderer_flush()},end(){yt?.renderer_end()},submitSprites(e){yt&&yt.renderer_submitSprites(e._cpp)},submitSpine(e){yt&&yt.renderer_submitSpine?.(e._cpp)},setStage(e){yt?.renderer_setStage(e)},createRenderTarget:(e,t,r=1)=>yt?.renderer_createTarget(e,t,r)??0,releaseRenderTarget(e){yt?.renderer_releaseTarget(e)},getTargetTexture:e=>yt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>yt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,r,n){yt?.renderer_setClearColor?.(e,t,r,n)},getStats:()=>yt?{drawCalls:yt.renderer_getDrawCalls(),triangles:yt.renderer_getTriangles(),sprites:yt.renderer_getSprites(),spine:yt.renderer_getSpine?.()??0,meshes:yt.renderer_getMeshes(),culled:yt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let Pt=null;function Ct(e){Pt=e}function Tt(){Pt=null}const At={enable(){Pt?.gl_enableErrorCheck(!0)},disable(){Pt?.gl_enableErrorCheck(!1)},check:e=>Pt?.gl_checkErrors(e)??0,diagnose(){Pt?.renderer_diagnose()}},Et=new Map;function Mt(e){Et.delete(e)}class Rt{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:r,width:n,height:s,elapsed:o}=e;St.resize(n,s),_t.isInitialized()&&_t.getPassCount()>0&&!_t.isBypassed()&&_t.resize(n,s),St.begin(r),St.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,o):St.submitSpine(t),St.flush();const i=Et;if(i.size>0){et.begin(r);const e=[];for(const[t,r]of i.entries())try{r(o)}catch(r){console.error(`[CustomDraw] callback '${t}' error:`,r),e.push(t)}et.end();for(const t of e)Mt(t)}St.end()}}class Ut{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 he,this.resources_=new K;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Ut}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_}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 ie(this.world_,this.resources_),this.resources_.insert(J,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1,Tt(),bt(),ft(),ct(),Ae(),Je()}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(J),r={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(J,r)}}const Ft=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Bt(e,t){for(let r=0;r<t;r++){if(!e.valid(r)||!e.hasCanvas(r))continue;return e.getCanvas(r)}return null}function It(e,t,r,n,s){const o=e*t/r,i=e;switch(n){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=s;return Math.pow(o,1-e)*Math.pow(i,e)}}}function Dt(e,t,r,n,s,o){const i=new Float32Array(16),a=t-e,l=n-r,c=o-s;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(n+r)/l,i[14]=-(o+s)/c,i[15]=1,i}function zt(e,t,r,n){const s=new Float32Array(16),o=1/Math.tan(e/2),i=r-n;return s[0]=o/t,s[5]=o,s[10]=(n+r)/i,s[11]=-1,s[14]=2*n*r/i,s}function Wt(e,t,r){const n=new Float32Array(16);return n[0]=1,n[5]=1,n[10]=1,n[15]=1,n[12]=-e,n[13]=-t,n[14]=-r,n}function kt(e,t){const r=new Float32Array(16);for(let n=0;n<4;n++)for(let s=0;s<4;s++)r[4*s+n]=e[0+n]*t[4*s+0]+e[4+n]*t[4*s+1]+e[8+n]*t[4*s+2]+e[12+n]*t[4*s+3];return r}async function Lt(e,t){if(t)return t();return(0,(await import(e)).default)()}const $t=j({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents");function Ht(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Ot(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Nt{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($t,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,r=new Map,n=Lt(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const s=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,se([q(J)],o=>{const i=s.getEntitiesWithComponents([S,z,W]),a=new Set;for(const o of i){a.add(o);const i=s.get(o,S),l=s.get(o,W);if(t.has(o)){const e=r.get(o);!e||e.bodyType===i.bodyType&&e.gravityScale===i.gravityScale&&e.linearDamping===i.linearDamping&&e.angularDamping===i.angularDamping&&e.fixedRotation===i.fixedRotation&&e.bullet===i.bullet||(n._physics_updateBodyProperties(o,i.bodyType,i.gravityScale,i.linearDamping,i.angularDamping,i.fixedRotation?1:0,i.bullet?1:0),e.bodyType=i.bodyType,e.gravityScale=i.gravityScale,e.linearDamping=i.linearDamping,e.angularDamping=i.angularDamping,e.fixedRotation=i.fixedRotation,e.bullet=i.bullet)}else{if(!i.enabled)continue;const s=Ht(l.rotation);n._physics_createBody(o,i.bodyType,l.position.x,l.position.y,s,i.gravityScale,i.linearDamping,i.angularDamping,i.fixedRotation?1:0,i.bullet?1:0),Vt(e,n,o),t.add(o),r.set(o,{bodyType:i.bodyType,gravityScale:i.gravityScale,linearDamping:i.linearDamping,angularDamping:i.angularDamping,fixedRotation:i.fixedRotation,bullet:i.bullet})}if(i.bodyType===A.Kinematic){const e=Ht(l.rotation);n._physics_setBodyTransform(o,l.position.x,l.position.y,e)}}for(const e of t)a.has(e)||(n._physics_destroyBody(e),t.delete(e),r.delete(e));n._physics_step(o.delta),function(e,t){const r=t._physics_getDynamicBodyCount();if(0===r)return;const n=t._physics_getDynamicBodyTransforms(),s=n>>2;for(let n=0;n<r;n++){const r=s+4*n,o=t.HEAPU32[r],i=t.HEAPF32[r+1],a=t.HEAPF32[r+2],l=t.HEAPF32[r+3];if(!e.world.valid(o))continue;const c=e.world.get(o,z);if(!c)continue;let u=i,h=a,d=l;if(e.world.has(o,O)){const t=e.world.get(o,O);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,W)){const r=e.world.get(t.entity,W),n=Ht(r.rotation),s=i-r.position.x,o=a-r.position.y,c=Math.cos(-n),p=Math.sin(-n);u=(s*c-o*p)/(0!==r.scale.x?r.scale.x:1),h=(s*p+o*c)/(0!==r.scale.y?r.scale.y:1),d=l-n}}c.position.x=u,c.position.y=h;const p=Ot(d);c.rotation.w=p.w,c.rotation.x=p.x,c.rotation.y=p.y,c.rotation.z=p.z,e.world.insert(o,z,c)}}(e,n),function(e,t){t._physics_collectEvents();const r=[],n=t._physics_getCollisionEnterCount();if(n>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let s=0;s<n;s++){const n=e+6*s;r.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1],normalX:t.HEAPF32[n+2],normalY:t.HEAPF32[n+3],contactX:t.HEAPF32[n+4],contactY:t.HEAPF32[n+5]})}}const s=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let r=0;r<o;r++){const n=e+2*r;s.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const i=[],a=t._physics_getSensorEnterCount();if(a>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let r=0;r<a;r++){const n=e+2*r;i.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const l=[],c=t._physics_getSensorExitCount();if(c>0){const e=t._physics_getSensorExitBuffer()>>2;for(let r=0;r<c;r++){const n=e+2*r;l.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource($t,{collisionEnters:r,collisionExits:s,sensorEnters:i,sensorExits:l})}(e,n)},{name:"PhysicsSystem"})),e.__physicsModule=n});e.__physicsInitPromise=n}}function Vt(e,t,r){const n=e.world;if(n.has(r,P)){const e=n.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(n.has(r,C)){const e=n.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(n.has(r,T)){const e=n.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)}}function Gt(e,t,r=!0){const n=e.getResourceManager(),s=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,s);const o=n.createTexture(t.width,t.height,s,t.pixels.length,1,r);return e._free(s),o}function Xt(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 jt(e,t,r,n){const s=e.scale.x*t*(r?-1:1),o=e.scale.y*t*(n?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,h=a+a,d=l+l,p=c+c,f=a*h,m=a*d,_=a*p,x=l*d,g=l*p,y=c*p,w=u*h,v=u*d,b=u*p;return new Float32Array([(1-(x+y))*s,(m+b)*s,(_-v)*s,0,(m-b)*o,(1-(f+y))*o,(g+w)*o,0,(_+v)*i,(g-w)*i,(1-(f+x))*i,0,e.position.x,e.position.y,e.position.z,1])}async function qt(e,t,r,n,s,o,i){const a=await async function(e,t,r){const n={};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!==n[s])continue;try{n[s]=Gt(e,await r.loadPixels(s))}catch{n[s]=0}}return n}(t,r,n);!function(e,t,r){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const s=r[e];if(s&&s>0){const r=t.textureMetadata[e];if(r?.sliceBorder){const e=r.sliceBorder;n.setTextureMetadata(s,e.left,e.right,e.top,e.bottom)}}}}(t,r,a);let l={},c=null;if(s&&(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"])}}(s),l=await async function(e,t,r,n,s){const o={};for(const i of n.entities)for(const n of i.components){if("SpineAnimation"!==n.type||!n.data)continue;const i=n.data.skeletonPath,a=n.data.atlasPath;if(!i||!a)continue;const l=s.resolvePath(i),c=s.resolvePath(a);try{const n=s.readText(a),u=l.endsWith(".skel");let h,d;if(u){const e=s.readBinary(i);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=s.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,n,n.length,u);if(t._free(h),p<0)continue;o[i]=p;const f=Xt(n),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=m+"/"+f[t];try{const o=s.loadPixelsRaw?await s.loadPixelsRaw(n):await s.loadPixels(n),i=Gt(e,o,!1),a=e.getResourceManager().getTextureGLId(i);r.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,s,c,r,n)),o){new Nt("",{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={},n={};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===r[s])try{const e=JSON.parse(t.readText(s));if(!e.vertexSource||!e.fragmentSource){r[s]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=n[o];i||(i=Me.createShader(e.vertexSource,e.fragmentSource),n[o]=i),r[s]=Me.createFromAsset(e,i)}catch{r[s]=0}}return r}(r,n),h=We(e.world,r);if(function(e,t,r,n){for(const s of t.entities){const t=n.get(s.id);if(void 0!==t)for(const n of s.components)if("Sprite"===n.type&&n.data.texture&&"string"==typeof n.data.texture){const s=e.get(t,k);s&&(s.texture=r[n.data.texture]||0,e.insert(t,k,s))}}}(e.world,r,a,h),function(e,t,r,n){for(const s of t.entities){const t=n.get(s.id);if(void 0!==t)for(const n of s.components){if(!n.data||"string"!=typeof n.data.material||!n.data.material)continue;const s=r[n.data.material]||0;if(s)if("Sprite"===n.type){const r=e.get(t,k);r&&(r.material=s,e.insert(t,k,r))}else if("SpineAnimation"===n.type){const r=e.get(t,V);r&&(r.material=s,e.insert(t,V,r))}}}}(e.world,r,u,h),s&&c){const n=function(e,t,r,n){const s={};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=n.get(o.id);void 0!==l&&(s[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 s}(c,r,l,h);!function(e,t,r,n,s){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 s){const o=Number(e),i=s[e],a=c.has(o,V)?c.get(o,V):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&n.update(i,l*h);let d=0;if(c.has(o,W)){const e=jt(c.get(o,W),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const p=n.getMeshBatchCount(i);for(let e=0;e<p;e++){const s=n.getMeshBatchVertexCount(i,e),o=n.getMeshBatchIndexCount(i,e);if(!s||!o)continue;const a=8*s*4,l=2*o,c=r._malloc(a),u=r._malloc(l),h=r._malloc(4),p=r._malloc(4);n.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*s),x=new Uint16Array(r.HEAPU8.buffer,u,o),g=t._malloc(a),y=t._malloc(l);t.HEAPF32.set(_,g>>2),new Uint16Array(t.HEAPU8.buffer,y,o).set(x),t.renderer_submitTriangles(g,s,y,o,f,m,d),t._free(g),t._free(y),r._free(c),r._free(u),r._free(h),r._free(p)}d&&t._free(d)}})}(e,t,s,c,n)}}class Yt{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 n of e.entities)for(const e of n.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,s=e.data.atlasPath;n&&(n.endsWith(".skel")?r.add(n):t.add(n)),s&&t.add(s)}"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const n=[];for(const e of t)n.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of r)n.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(n)}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),n=await r.blob(),s=await createImageBitmap(n),o=new OffscreenCanvas(s.width,s.height).getContext("2d");o.drawImage(s,0,0);const i=o.getImageData(0,0,s.width,s.height);return s.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 Kt={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),r=St.createRenderTarget(e.width,e.height,t);return{_handle:r,textureId:St.getTargetTexture(r),width:e.width,height:e.height}},release(e){St.releaseRenderTarget(e._handle)},resize:(e,t,r)=>(St.releaseRenderTarget(e._handle),Kt.create({width:t,height:r,depth:!0})),begin(e,t){St.begin(t,e._handle)},end(){St.end()},getDepthTexture:e=>St.getTargetDepthTexture(e._handle)};let Jt=!1;var Qt;y||(y=!0,void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const r="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},s=await l(r,n);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: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 n=0;for(let t=0;t<e.length;t++){let s=e.charCodeAt(t);s<128?r[n++]=s:s<2048?(r[n++]=192|s>>6,r[n++]=128|63&s):s>=55296&&s<=56319?(s=e.charCodeAt(++t)-56320+(s-55296<<10)+65536,r[n++]=240|s>>18,r[n++]=128|s>>12&63,r[n++]=128|s>>6&63,r[n++]=128|63&s):(r[n++]=224|s>>12,r[n++]=128|s>>6&63,r[n++]=128|63&s)}return r.subarray(0,n)}}),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 n=t[e];if(n<128)r+=String.fromCharCode(n),e++;else if(192==(224&n))r+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))r+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const s=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;r+=String.fromCharCode(55296+(s>>10),56320+(1023&s)),e+=4}}return r}})}(),console.log("[ESEngine] WeChat platform initialized")),e=Qt=w,console.log(`[ESEngine] Platform: ${Qt.name}`),exports.App=Ut,exports.AssetPlugin=Ne,exports.AssetServer=He,exports.Assets=Oe,exports.AsyncCache=$e,exports.BodyType=A,exports.BoxCollider=P,exports.Camera=L,exports.Canvas=$,exports.CapsuleCollider=T,exports.Children=N,exports.CircleCollider=C,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=te,exports.Draw=et,exports.EntityCommands=ee,exports.GLDebug=At,exports.Geometry=ht,exports.INVALID_ENTITY=0,exports.INVALID_TEXTURE=v,exports.Input=le,exports.InputPlugin=ce,exports.InputState=ae,exports.LocalTransform=z,exports.Material=Me,exports.MaterialLoader=ze,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Parent=O,exports.Physics=class{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}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)}},exports.PhysicsEvents=$t,exports.PhysicsPlugin=Nt,exports.PostProcess=_t,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(),n=new Yt(this.baseUrl_);await n.prefetch(t);let s=null;const o=this.app_.__spineInitPromise;if(o){s=(await o).controller.raw}await qt(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 r=e.getEntitiesWithComponents([L]);for(const n of r){if(e.get(n,L).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,r=1920/1080;const n=e.getEntitiesWithComponents([$]);for(const s of n){const n=e.get(s,$);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,r=n.designResolution.x/n.designResolution.y;break}}const s=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(s,z,o);const i={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:r,priority:0,showFrustum:!0};e.insert(s,L,i)}}},exports.Query=function(...e){return function(e,t=[],r=[]){const n=[];return e.forEach((e,t)=>{Q(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:r}}(e)},exports.QueryInstance=Z,exports.RenderPipeline=Rt,exports.RenderTexture=Kt,exports.Renderer=St,exports.Res=q,exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.RigidBody=S,exports.ShaderSources=De,exports.SpineAnimation=V,exports.Sprite=k,exports.SystemRunner=ie,exports.Text=me,exports.TextPlugin=ge,exports.TextRenderer=_e,exports.Time=J,exports.UIRect=xe,exports.Velocity=H,exports.WebAssetProvider=Yt,exports.World=he,exports.WorldTransform=W,exports.addStartupSystem=function(e){oe().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){oe().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){oe().push({schedule:e,system:t})},exports.assetPlugin=Ve,exports.clearDrawCallbacks=function(){Et.clear()},exports.clearUserComponents=function(){R().clear()},exports.color=(e=1,t=1,r=1,n=1)=>({x:e,y:t,z:r,w:n}),exports.createWebApp=function(e,t){const r=Ut.new(),n=new e.Registry;r.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ke(e),Te(e),lt(e),pt(e),vt(e),Ct(e);const s=new Rt;r.pipeline_=s;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:e,height:t}=i(),r=n.entityCount(),l=Bt(n,r+1e3);if(l){const e=l.backgroundColor;St.setClearColor(e.x,e.y,e.z,e.w)}const c=function(e,t,r){const n=e.entityCount(),s=n+1e3;for(let n=0;n<s;n++){if(!e.valid(n)||!e.hasCamera(n)||!e.hasLocalTransform(n))continue;const o=e.getCamera(n);if(!o.isActive)continue;const i=e.getLocalTransform(n),a=t/r;let l;if(1===o.projectionType){let t=o.orthoSize;const r=Bt(e,s);if(r){t=It(r.designResolution.y/2,r.designResolution.x/r.designResolution.y,a,r.scaleMode,r.matchWidthOrHeight)}const n=t*a;l=Dt(-n,n,-t,t,-o.farPlane,o.farPlane)}else l=zt(o.fov*Math.PI/180,a,o.nearPlane,o.farPlane);return kt(l,Wt(i.position.x,i.position.y,i.position.z))}return Ft}(n,e,t),u=(a()-o)/1e3;s.render({registry:{_cpp:n},viewProjection:c,width:e,height:t,elapsed:u})}};return r.addSystemToSchedule(exports.Schedule.Last,l),r.addPlugin(Ve),r.addPlugin(ue),r.addPlugin(ye),r},exports.defineComponent=U,exports.defineResource=j,exports.defineSystem=se,exports.defineTag=function(e){const t=R(),r=t.get(e);if(r)return r;const n=M(e,{});return t.set(e,n),B(e,{},!0),n},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=Ke,exports.initGLDebugAPI=Ct,exports.initGeometryAPI=lt,exports.initMaterialAPI=Te,exports.initPostProcessAPI=pt,exports.initRendererAPI=vt,exports.inputPlugin=ue,exports.isBuiltinComponent=D,exports.isEditor=function(){return Jt},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!Jt},exports.isTextureRef=ve,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=Le,exports.loadPhysicsModule=Lt,exports.loadRuntimeScene=qt,exports.loadSceneData=We,exports.loadSceneWithAssets=ke,exports.platformFetch=r,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,r){return t().instantiateWasm(e,r)},exports.platformReadFile=n,exports.platformReadTextFile=s,exports.quat=(e=1,t=0,r=0,n=0)=>({w:e,x:t,y:r,z:n}),exports.registerDrawCallback=function(e,t){Et.set(e,t)},exports.registerEmbeddedAssets=function(e,t){const r=e.getResource(Oe);r&&r.registerEmbeddedAssets(t)},exports.registerMaterialCallback=Ie,exports.setEditorMode=function(e){Jt=e},exports.shutdownDrawAPI=Je,exports.shutdownGLDebugAPI=Tt,exports.shutdownGeometryAPI=ct,exports.shutdownMaterialAPI=Ae,exports.shutdownPostProcessAPI=ft,exports.shutdownRendererAPI=bt,exports.textPlugin=ye,exports.unregisterDrawCallback=Mt,exports.updateCameraAspectRatio=function(e,t){const r=e.getEntitiesWithComponents([L]);for(const n of r){const r=e.get(n,L);r&&(r.aspectRatio=t,e.insert(n,L,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,n=1)=>({x:e,y:t,z:r,w:n}),exports.wxFileExists=f,exports.wxFileExistsSync=function(e){const t=h();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=g,exports.wxLoadImage=x,exports.wxLoadImagePixels=async function(e){return g(await x(e))},exports.wxReadFile=d,exports.wxReadTextFile=p,exports.wxWriteFile=function(e,t){return new Promise((r,n)=>{h().writeFile({filePath:e,data:t,success:()=>r(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};
+"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function r(e,r){return t().fetch(e,r)}async function n(e){return t().readFile(e)}async function s(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,n)=>{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,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];r({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,r="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(r).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function c(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const 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,n)=>{h().readFile({filePath:e,encoding:t,success:e=>{r(e.data)},fail:t=>{n(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 n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>r(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function x(e){const{width:t,height:r}=e,{ctx:n}=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);n.clearRect(0,0,t,r),n.drawImage(e,0,0);const s=n.getImageData(0,0,t,r);return{width:t,height:r,pixels:new Uint8Array(s.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(),n=r.get(e);if(n)return n;const s=M(e,t);return r.set(e,s),B(e,t,!1),s}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}),L=I("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0}),$=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}),G={LocalTransform:W,WorldTransform:k,Sprite:z,Camera:L,Canvas:$,Velocity:H,Parent:O,Children:N,SpineAnimation:V,RigidBody:S,BoxCollider:P,CircleCollider:C,CapsuleCollider:T};let X=0;function j(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 Y{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 K{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 Y(this.get(e),t=>this.set(e,t))}}const J=j({delta:0,elapsed:0,frameCount:0},"Time");function Q(e){return"object"==typeof e&&null!==e&&"mut"===e._type}class Z{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return Q(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:n}=this.descriptor_,s=e.map(e=>this.getActualComponent(e)),o=[...s,...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 n)if(this.world_.has(e,t)){r=!0;break}if(r)continue;const o=s.map(t=>this.world_.get(e,t));for(const e of t)l.push({component:s[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 ee{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let 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 te{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ee(this,null);return this.spawned_.push(e),e}entity(e){return new ee(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,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 re;exports.Schedule=void 0,(re=exports.Schedule||(exports.Schedule={}))[re.Startup=0]="Startup",re[re.First=1]="First",re[re.PreUpdate=2]="PreUpdate",re[re.Update=3]="Update",re[re.PostUpdate=4]="PostUpdate",re[re.Last=5]="Last",re[re.FixedPreUpdate=10]="FixedPreUpdate",re[re.FixedUpdate=11]="FixedUpdate",re[re.FixedPostUpdate=12]="FixedPostUpdate";let ne=0;function se(e,t,r){const n=++ne;return{_id:Symbol(`System_${n}_${r?.name??""}`),_params:e,_fn:t,_name:r?.name??`System_${n}`}}function oe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class ie{constructor(e,t){this.world_=e,this.resources_=t}run(e){const t=e._params.map(e=>this.resolveParam(e));e._fn(...t);for(const e of t)e instanceof te&&e.flush()}resolveParam(e){switch(e._type){case"query":return new Z(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new te(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class ae{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const le=j(new ae,"Input");class ce{constructor(e){this.target_=e??null}build(e){const r=new ae;e.insertResource(le,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,n){r.mouseX=t,r.mouseY=n,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,se([],()=>{r.keysPressed.clear(),r.keysReleased.clear(),r.mouseButtonsPressed.clear(),r.mouseButtonsReleased.clear(),r.scrollDeltaX=0,r.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ue=new ce;class he{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 n={...t._default,...r};if(this.cppRegistry_){const r=`add${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e,n)}return n}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const r=`get${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const r=`has${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const r=`remove${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e)}insertScript(e,t,r){const n=t.create(r);return this.getStorage(t).set(e,n),n}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 n=!0;for(const t of e)if(!this.has(r,t)){n=!1;break}n&&t.push(r)}return t}}var de,pe,fe;exports.TextAlign=void 0,(de=exports.TextAlign||(exports.TextAlign={}))[de.Left=0]="Left",de[de.Center=1]="Center",de[de.Right=2]="Right",exports.TextVerticalAlign=void 0,(pe=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[pe.Top=0]="Top",pe[pe.Middle=1]="Middle",pe[pe.Bottom=2]="Bottom",exports.TextOverflow=void 0,(fe=exports.TextOverflow||(exports.TextOverflow={}))[fe.Visible=0]="Visible",fe[fe.Clip=1]="Clip",fe[fe.Ellipsis=2]="Ellipsis";const me=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 _e{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,n=this.canvas;r.font=`${e.fontSize}px ${e.fontFamily}`;const s=t&&t.size.x>0&&t.size.y>0,o=s?t.size.x:0,i=s?t.size.y:0,a=e.wordWrap&&s;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=s?Math.ceil(o):h+2*u,f=s?Math.ceil(i):d+2*u;if(s&&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(n.width<p||n.height<f){const e=Math.max(n.width,this.nextPowerOf2(p)),t=Math.max(n.height,this.nextPowerOf2(f));n.width=e,n.height=t}const 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,n.width,n.height),r.font=`${e.fontSize}px ${e.fontFamily}`,r.textAlign=this.mapAlign(e.align),r.textBaseline="top",r.fillStyle=`rgba(${m}, ${_}, ${g}, ${x})`,s&&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(s)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 n;switch(e.align){case exports.TextAlign.Left:n=u;break;case exports.TextAlign.Center:n=p/2;break;case exports.TextAlign.Right:n=p-u;break;default:n=u}r.fillText(t,n,v),v+=c}s&&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 n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const s=this.renderText(t,r);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 r=e.split("\n"),n=[];for(const e of r){if(!e){n.push("");continue}let r="";for(const s of e){const e=r+s;this.ctx.measureText(e).width>t&&r?(n.push(r),r=s):r=e}r&&n.push(r)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const r of e){const e=this.ctx.measureText(r),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const ge=U("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 r=new _e(t),n=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,se([],()=>{const e=n.getEntitiesWithComponents([me]);for(const t of e){const e=n.get(t,me);if(!e.dirty)continue;n.has(t,z)||n.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 s=n.has(t,ge)?n.get(t,ge):null,o=r.renderForEntity(t,e,s),i=n.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},n.insert(t,z,i),e.dirty=!1}}))}}const ye=new xe;var we;function ve(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(we=exports.BlendMode||(exports.BlendMode={}))[we.Normal=0]="Normal",we[we.Additive=1]="Additive",we[we.Multiply=2]="Multiply",we[we.Screen=3]="Screen",we[we.PremultipliedAlpha=4]="PremultipliedAlpha";let be=null,Se=null,Pe=1;const Ce=new Map;function Te(e){be=e,Se=e.getResourceManager(),Ie()}function Ae(){0!==Ue&&be&&(be._free(Ue),Ue=0),Ce.clear(),Pe=1,Re=!1,Se=null,be=null}function Ee(){if(!Se)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Se}const Me={createShader:(e,t)=>Ee().createShader(e,t),releaseShader(e){e>0&&Ee().releaseShader(e)},create(e){const t=Pe++,r={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))r.uniforms.set(t,n);return Ce.set(t,r),t},get:e=>Ce.get(e),setUniform(e,t,r){const n=Ce.get(e);n&&n.uniforms.set(t,r)},getUniform(e,t){const r=Ce.get(e);return r?.uniforms.get(t)},setBlendMode(e,t){const r=Ce.get(e);r&&(r.blendMode=t)},getBlendMode(e){const t=Ce.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const r=Ce.get(e);r&&(r.depthTest=t)},getShader(e){const t=Ce.get(e);return t?.shader??0},release(e){Ce.delete(e)},isValid:e=>Ce.has(e),createFromAsset(e,t){const r={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)r[t]=n;else if("object"==typeof n&&null!==n){const e=n;"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=Ce.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const r=Pe++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Ce.set(r,n),r},toAssetData(e,t){const r=Ce.get(e);if(!r)return null;const n={};for(const[e,t]of r.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:r.blendMode,depthTest:r.depthTest,properties:n}},getUniforms(e){const t=Ce.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Re=!1,Ue=0;const Fe=4096;function Be(e){const t=(0===Ue&&be&&(Ue=be._malloc(Fe)),Ue);if(0===t||!be)return{ptr:0,count:0};let r=0,n=0;const s=be.HEAPU8,o=be.HEAPU32,i=be.HEAPF32;for(const[a,l]of e){if(r+128>Fe)break;const e=(new TextEncoder).encode(a),c=e.length,u=4*Math.ceil(c/4);o[t+r>>2]=c,r+=4,s.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;n++}return{ptr:t,count:n}}function Ie(){if(!be||Re)return;be.materialDataProvider=(e,t,r,n,s)=>{const o=Ce.get(e);if(!o)return be.HEAPU32[t>>2]=0,be.HEAPU32[r>>2]=0,be.HEAPU32[n>>2]=0,void(be.HEAPU32[s>>2]=0);be.HEAPU32[t>>2]=o.shader,be.HEAPU32[r>>2]=o.blendMode;const{ptr:i,count:a}=Be(o.uniforms);be.HEAPU32[n>>2]=i,be.HEAPU32[s>>2]=a},Re=!0}const De={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 We{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 n=this.loadInternal(e);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)}release(e){const t=this.cache_.get(e);t&&(Me.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Me.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 s(t);if(!r)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(r);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const i=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(i);return{handle:Me.createFromAsset(n,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const r=e.substring(0,e.lastIndexOf("/"));return r?`${r}/${t}`:t}}function ke(e,t){const r=new Map;for(const n of t.entities){const t=e.spawn();r.set(n.id,t);for(const r of n.components)Le(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)}return r}async function ze(e,t,r){const n=new Map,s=r?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();n.set(i.id,t);for(const n of i.components){if("Sprite"===n.type&&s){const e=n.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,n=t.startsWith("data:")?t:r?.assetBaseUrl?`${r.assetBaseUrl}/${t}`:`/${t}`;try{const r=await s.loadTexture(n);e.texture=r.handle,o.set(t,n)}catch(t){console.warn(`Failed to load texture: ${n}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await s.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"===n.type&&s){const e=n.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await s.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 s.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Le(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)}if(s&&t.textureMetadata)for(const[e,r]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&r.sliceBorder&&s.setTextureMetadataByPath(t,r.sliceBorder)}return n}function Le(e,t,r){const n=r.data;switch(r.type){case"LocalTransform":e.insert(t,W,n);break;case"Sprite":e.insert(t,z,n);break;case"Camera":e.insert(t,L,n);break;case"Canvas":e.insert(t,$,n);break;case"Text":e.insert(t,me,n);break;case"SpineAnimation":e.insert(t,V,n);break;case"UIRect":e.insert(t,ge,n);break;case"RigidBody":e.insert(t,S,n);break;case"BoxCollider":e.insert(t,P,n);break;case"CircleCollider":e.insert(t,C,n);break;case"CapsuleCollider":e.insert(t,T,n);break;default:{const s=F(r.type);s?e.insert(t,s,n):console.warn(`Unknown component type: ${r.type}`);break}}}class $e{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 n=this.pending_.get(e);if(n)return n;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 He{constructor(e){this.textureCache_=new $e,this.shaderCache_=new $e,this.jsonCache_=new $e,this.textCache_=new $e,this.binaryCache_=new $e,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 We(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 n=this.textureCacheKey(e,r),s=this.textureCache_.get(n);s&&(t.releaseTexture(s.handle),this.textureCache_.delete(n))}}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 n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const s=this.resolveUrl(t,r),o=await this.fetchText(s);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,n=this.resolveUrl(t,r);try{const e=await this.loadTextureRaw(n);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(n),{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 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},r=[];if(e.textures)for(const n of e.textures)r.push(this.loadTexture(n).then(e=>{t.textures.set(n,e)}));if(e.materials)for(const n of e.materials)r.push(this.loadMaterial(n).then(e=>{t.materials.set(n,e)}));if(e.spine)for(const n of e.spine){const e=`${n.skeleton}:${n.atlas}`;r.push(this.loadSpine(n.skeleton,n.atlas,n.baseUrl).then(r=>{t.spine.set(e,r)}))}if(e.json)for(const n of e.json)r.push(this.loadJson(n).then(e=>{t.json.set(n,e)}));if(e.text)for(const n of e.text)r.push(this.loadText(n).then(e=>{t.text.set(n,e)}));if(e.binary)for(const n of e.binary)r.push(this.loadBinary(n).then(e=>{t.binary.set(n,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,n=this.embedded_.get(r)??r;return new Promise((r,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void r(e)}catch{}r(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=n})}createTextureFromImage(e,t){const{width:r,height:n}=e,s=this.getWebGL2Context();return s?this.createTextureWebGL2(s,e,r,n,t):this.createTextureFallback(e,r,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,r,n,s){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),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 i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,r,n),width:r,height:n}}createTextureFallback(e,t,r,n){(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 s=this.ctx_.getImageData(0,0,t,r),o=new Uint8Array(s.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,n);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 n=255/r;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e;if(!await o(t))throw new Error(`Shader file not found: ${e}`);const r=await s(t);if(!r)throw new Error(`Failed to read shader file: ${e}`);const{vertex:n,fragment:i}=this.parseEsShader(r);if(!n||!i)throw new Error(`Invalid shader format: ${e}`);return Me.createShader(n,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 s(t);return JSON.parse(r)}const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):s(t)}const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):n(t)}const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const 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 n=r.split("/").filter(e=>e);let s="";for(const e of n){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 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 Oe=j(null,"Assets");class Ne{build(e){const t=e.wasmModule;t?e.insertResource(Oe,new He(t)):console.warn("AssetPlugin: No WASM module available")}}const Ve=new Ne;let Ge=null,Xe=0,je=0,qe=0;const Ye=new Float32Array(256);function Ke(e){Ge=e,Xe=Ge._malloc(64),je=Ge._malloc(64),qe=Ge._malloc(1024)}function Je(){Ge&&(Xe&&(Ge._free(Xe),Xe=0),je&&(Ge._free(je),je=0),qe&&(Ge._free(qe),qe=0)),Ge=null}function Qe(){if(!Ge)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Ge}const Ze={r:1,g:1,b:1,a:1},et={begin(e){const t=Qe();t.HEAPF32.set(e,Xe/4),t.draw_begin(Xe)},end(){Qe().draw_end()},line(e,t,r,n=1){Qe().draw_line(e.x,e.y,t.x,t.y,r.r,r.g,r.b,r.a,n)},rect(e,t,r,n=!0){Qe().draw_rect(e.x,e.y,t.x,t.y,r.r,r.g,r.b,r.a,n)},rectOutline(e,t,r,n=1){Qe().draw_rectOutline(e.x,e.y,t.x,t.y,r.r,r.g,r.b,r.a,n)},circle(e,t,r,n=!0,s=32){Qe().draw_circle(e.x,e.y,t,r.r,r.g,r.b,r.a,n,s)},circleOutline(e,t,r,n=1,s=32){Qe().draw_circleOutline(e.x,e.y,t,r.r,r.g,r.b,r.a,n,s)},texture(e,t,r,n=Ze){Qe().draw_texture(e.x,e.y,t.x,t.y,r,n.r,n.g,n.b,n.a)},textureRotated(e,t,r,n,s=Ze){Qe().draw_textureRotated(e.x,e.y,t.x,t.y,r,n,s.r,s.g,s.b,s.a)},setLayer(e){Qe().draw_setLayer(e)},setDepth(e){Qe().draw_setDepth(e)},getDrawCallCount:()=>Ge?Ge.draw_getDrawCallCount():0,getPrimitiveCount:()=>Ge?Ge.draw_getPrimitiveCount():0,setBlendMode(e){Qe().draw_setBlendMode(e)},setDepthTest(e){Qe().draw_setDepthTest(e)},drawMesh(e,t,r){const n=Qe();n.HEAPF32.set(r,je/4),n.draw_mesh(e,t,je)},drawMeshWithMaterial(e,t,r){const n=Qe(),s=Me.get(t);if(!s)return;if(et.setBlendMode(s.blendMode),et.setDepthTest(s.depthTest),0===s.uniforms.size)return void et.drawMesh(e,s.shader,r);n.HEAPF32.set(r,je/4);let o=0,i=0;for(const[e,t]of s.uniforms){const r=rt(e);if(!(r<0)){if(ve(t))Ye[o++]=10,Ye[o++]=r,Ye[o++]=t.slot??i++,Ye[o++]=t.textureId;else if("number"==typeof t)Ye[o++]=1,Ye[o++]=r,Ye[o++]=t;else if(Array.isArray(t)){Ye[o++]=t.length,Ye[o++]=r;for(let e=0;e<t.length;e++)Ye[o++]=t[e]}else"w"in t?(Ye[o++]=4,Ye[o++]=r,Ye[o++]=t.x,Ye[o++]=t.y,Ye[o++]=t.z,Ye[o++]=t.w):"z"in t?(Ye[o++]=3,Ye[o++]=r,Ye[o++]=t.x,Ye[o++]=t.y,Ye[o++]=t.z):(Ye[o++]=2,Ye[o++]=r,Ye[o++]=t.x,Ye[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(n.HEAPF32.set(Ye.subarray(0,o),qe/4),n.draw_meshWithUniforms(e,s.shader,je,qe,o)):n.draw_mesh(e,s.shader,je)}},tt={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 rt(e){return tt[e]??-1}var nt;exports.DataType=void 0,(nt=exports.DataType||(exports.DataType={}))[nt.Float=1]="Float",nt[nt.Float2=2]="Float2",nt[nt.Float3=3]="Float3",nt[nt.Float4=4]="Float4",nt[nt.Int=5]="Int",nt[nt.Int2=6]="Int2",nt[nt.Int3=7]="Int3",nt[nt.Int4=8]="Int4";let st=null,ot=0,it=0,at=0;function lt(e){st=e,ot=st._malloc(262144),it=st._malloc(65536),at=st._malloc(256)}function ct(){st&&(ot&&st._free(ot),it&&st._free(it),at&&st._free(at),ot=0,it=0,at=0),st=null}function ut(){if(!st)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return st}const ht={create(e){const t=ut(),r=t.geometry_create();if(0===r)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,ot/4);const s=e.layout.length,o=new Int32Array(s);for(let t=0;t<s;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,at,s).set(o),t.geometry_init(r,ot,n,at,s,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,it,n).set(e.indices),t.geometry_setIndices16(r,it,n)}else{new Uint32Array(t.HEAPU8.buffer,it,n).set(e.indices),t.geometry_setIndices32(r,it,n)}}return r},updateVertices(e,t,r=0){const n=ut(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);n.HEAPF32.set(t,ot/4),n.geometry_updateVertices(e,ot,s,r)},release(e){e>0&&ut().geometry_release(e)},isValid:e=>!(!st||e<=0)&&st.geometry_isValid(e),createQuad(e=1,t=1){const r=e/2,n=t/2;return ht.create({vertices:new Float32Array([-r,-n,0,0,r,-n,1,0,r,n,1,1,-r,n,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const r=[],n=[];r.push(0,0,.5,.5);for(let n=0;n<=t;n++){const s=n/t*Math.PI*2,o=Math.cos(s)*e,i=Math.sin(s)*e,a=(Math.cos(s)+1)/2,l=(Math.sin(s)+1)/2;r.push(o,i,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return ht.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,r=1/0,n=-1/0,s=-1/0;for(const o of e)t=Math.min(t,o.x),r=Math.min(r,o.y),n=Math.max(n,o.x),s=Math.max(s,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-r)/(s-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 ht.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 dt=null;function pt(e){dt=e}function ft(){dt&&_t.isInitialized()&&_t.shutdown(),dt=null}function mt(){if(!dt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return dt}const _t={init:(e,t)=>mt().postprocess_init(e,t),shutdown(){mt().postprocess_shutdown()},resize(e,t){mt().postprocess_resize(e,t)},addPass:(e,t)=>mt().postprocess_addPass(e,t),removePass(e){mt().postprocess_removePass(e)},setEnabled(e,t){mt().postprocess_setPassEnabled(e,t)},isEnabled:e=>mt().postprocess_isPassEnabled(e),setUniform(e,t,r){mt().postprocess_setUniformFloat(e,t,r)},setUniformVec4(e,t,r){mt().postprocess_setUniformVec4(e,t,r.x,r.y,r.z,r.w)},begin(){mt().postprocess_begin()},end(){mt().postprocess_end()},getPassCount:()=>mt().postprocess_getPassCount(),isInitialized:()=>!!dt&&dt.postprocess_isInitialized(),setBypass(e){mt().postprocess_setBypass(e)},isBypassed:()=>!dt||dt.postprocess_isBypassed(),createBlur:()=>Me.createShader(gt,"#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:()=>Me.createShader(gt,"#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:()=>Me.createShader(gt,"#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:()=>Me.createShader(gt,"#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")},gt="#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 xt;exports.RenderStage=void 0,(xt=exports.RenderStage||(exports.RenderStage={}))[xt.Background=0]="Background",xt[xt.Opaque=1]="Opaque",xt[xt.Transparent=2]="Transparent",xt[xt.Overlay=3]="Overlay";let yt=null,wt=0;function vt(e){yt=e,wt=yt._malloc(64)}function bt(){yt&&wt&&(yt._free(wt),wt=0),yt=null}const St={init(e,t){yt?.renderer_init(e,t)},resize(e,t){yt?.renderer_resize(e,t)},begin(e,t){yt&&wt&&(yt.HEAPF32.set(e,wt/4),yt.renderer_begin(wt,t??0))},flush(){yt?.renderer_flush()},end(){yt?.renderer_end()},submitSprites(e){yt&&yt.renderer_submitSprites(e._cpp)},submitSpine(e){yt&&yt.renderer_submitSpine?.(e._cpp)},setStage(e){yt?.renderer_setStage(e)},createRenderTarget:(e,t,r=1)=>yt?.renderer_createTarget(e,t,r)??0,releaseRenderTarget(e){yt?.renderer_releaseTarget(e)},getTargetTexture:e=>yt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>yt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,r,n){yt?.renderer_setClearColor?.(e,t,r,n)},getStats:()=>yt?{drawCalls:yt.renderer_getDrawCalls(),triangles:yt.renderer_getTriangles(),sprites:yt.renderer_getSprites(),spine:yt.renderer_getSpine?.()??0,meshes:yt.renderer_getMeshes(),culled:yt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let Pt=null;function Ct(e){Pt=e}function Tt(){Pt=null}const At={enable(){Pt?.gl_enableErrorCheck(!0)},disable(){Pt?.gl_enableErrorCheck(!1)},check:e=>Pt?.gl_checkErrors(e)??0,diagnose(){Pt?.renderer_diagnose()}},Et=new Map;function Mt(e){Et.delete(e)}class Rt{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:r,width:n,height:s,elapsed:o}=e;St.resize(n,s),_t.isInitialized()&&_t.getPassCount()>0&&!_t.isBypassed()&&_t.resize(n,s),St.begin(r),St.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,o):St.submitSpine(t),St.flush();const i=Et;if(i.size>0){et.begin(r);const e=[];for(const[t,r]of i.entries())try{r(o)}catch(r){console.error(`[CustomDraw] callback '${t}' error:`,r),e.push(t)}et.end();for(const t of e)Mt(t)}St.end()}}class Ut{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 he,this.resources_=new K;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Ut}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_}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 ie(this.world_,this.resources_),this.resources_.insert(J,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1,Tt(),bt(),ft(),ct(),Ae(),Je()}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(J),r={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(J,r)}}const Ft=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Bt(e,t){for(let r=0;r<t;r++){if(!e.valid(r)||!e.hasCanvas(r))continue;return e.getCanvas(r)}return null}function It(e,t,r,n,s){const o=e*t/r,i=e;switch(n){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=s;return Math.pow(o,1-e)*Math.pow(i,e)}}}function Dt(e,t,r,n,s,o){const i=new Float32Array(16),a=t-e,l=n-r,c=o-s;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(n+r)/l,i[14]=-(o+s)/c,i[15]=1,i}function Wt(e,t,r,n){const s=new Float32Array(16),o=1/Math.tan(e/2),i=r-n;return s[0]=o/t,s[5]=o,s[10]=(n+r)/i,s[11]=-1,s[14]=2*n*r/i,s}function kt(e,t,r){const n=new Float32Array(16);return n[0]=1,n[5]=1,n[10]=1,n[15]=1,n[12]=-e,n[13]=-t,n[14]=-r,n}function zt(e,t){const r=new Float32Array(16);for(let n=0;n<4;n++)for(let s=0;s<4;s++)r[4*s+n]=e[0+n]*t[4*s+0]+e[4+n]*t[4*s+1]+e[8+n]*t[4*s+2]+e[12+n]*t[4*s+3];return r}async function Lt(e,t){if(t)return t();return(0,(await import(e)).default)()}const $t=j({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents");function Ht(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Ot(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Nt{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($t,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,r=new Map,n=Lt(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const s=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,se([q(J)],o=>{const i=s.getEntitiesWithComponents([S,W,k]),a=new Set;for(const o of i){a.add(o);const i=s.get(o,S),l=s.get(o,k);if(t.has(o)){const e=r.get(o);!e||e.bodyType===i.bodyType&&e.gravityScale===i.gravityScale&&e.linearDamping===i.linearDamping&&e.angularDamping===i.angularDamping&&e.fixedRotation===i.fixedRotation&&e.bullet===i.bullet||(n._physics_updateBodyProperties(o,i.bodyType,i.gravityScale,i.linearDamping,i.angularDamping,i.fixedRotation?1:0,i.bullet?1:0),e.bodyType=i.bodyType,e.gravityScale=i.gravityScale,e.linearDamping=i.linearDamping,e.angularDamping=i.angularDamping,e.fixedRotation=i.fixedRotation,e.bullet=i.bullet)}else{if(!i.enabled)continue;const s=Ht(l.rotation);n._physics_createBody(o,i.bodyType,l.position.x,l.position.y,s,i.gravityScale,i.linearDamping,i.angularDamping,i.fixedRotation?1:0,i.bullet?1:0),Vt(e,n,o),t.add(o),r.set(o,{bodyType:i.bodyType,gravityScale:i.gravityScale,linearDamping:i.linearDamping,angularDamping:i.angularDamping,fixedRotation:i.fixedRotation,bullet:i.bullet})}if(i.bodyType===A.Kinematic){const e=Ht(l.rotation);n._physics_setBodyTransform(o,l.position.x,l.position.y,e)}}for(const e of t)a.has(e)||(n._physics_destroyBody(e),t.delete(e),r.delete(e));n._physics_step(o.delta),function(e,t){const r=t._physics_getDynamicBodyCount();if(0===r)return;const n=t._physics_getDynamicBodyTransforms(),s=n>>2;for(let n=0;n<r;n++){const r=s+4*n,o=t.HEAPU32[r],i=t.HEAPF32[r+1],a=t.HEAPF32[r+2],l=t.HEAPF32[r+3];if(!e.world.valid(o))continue;const c=e.world.get(o,W);if(!c)continue;let u=i,h=a,d=l;if(e.world.has(o,O)){const t=e.world.get(o,O);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,k)){const r=e.world.get(t.entity,k),n=Ht(r.rotation),s=i-r.position.x,o=a-r.position.y,c=Math.cos(-n),p=Math.sin(-n);u=(s*c-o*p)/(0!==r.scale.x?r.scale.x:1),h=(s*p+o*c)/(0!==r.scale.y?r.scale.y:1),d=l-n}}c.position.x=u,c.position.y=h;const p=Ot(d);c.rotation.w=p.w,c.rotation.x=p.x,c.rotation.y=p.y,c.rotation.z=p.z,e.world.insert(o,W,c)}}(e,n),function(e,t){t._physics_collectEvents();const r=[],n=t._physics_getCollisionEnterCount();if(n>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let s=0;s<n;s++){const n=e+6*s;r.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1],normalX:t.HEAPF32[n+2],normalY:t.HEAPF32[n+3],contactX:t.HEAPF32[n+4],contactY:t.HEAPF32[n+5]})}}const s=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let r=0;r<o;r++){const n=e+2*r;s.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const i=[],a=t._physics_getSensorEnterCount();if(a>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let r=0;r<a;r++){const n=e+2*r;i.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const l=[],c=t._physics_getSensorExitCount();if(c>0){const e=t._physics_getSensorExitBuffer()>>2;for(let r=0;r<c;r++){const n=e+2*r;l.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource($t,{collisionEnters:r,collisionExits:s,sensorEnters:i,sensorExits:l})}(e,n)},{name:"PhysicsSystem"})),e.__physicsModule=n});e.__physicsInitPromise=n}}function Vt(e,t,r){const n=e.world;if(n.has(r,P)){const e=n.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(n.has(r,C)){const e=n.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(n.has(r,T)){const e=n.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)}}function Gt(e,t,r=!0){const n=e.getResourceManager(),s=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,s);const o=n.createTexture(t.width,t.height,s,t.pixels.length,1,r);return e._free(s),o}function Xt(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 jt(e,t,r,n){const s=e.scale.x*t*(r?-1:1),o=e.scale.y*t*(n?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,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))*s,(m+b)*s,(_-v)*s,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 qt(e,t,r,n,s,o,i){const a=await async function(e,t,r){const n={};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!==n[s])continue;try{n[s]=Gt(e,await r.loadPixels(s))}catch{n[s]=0}}return n}(t,r,n);!function(e,t,r){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const s=r[e];if(s&&s>0){const r=t.textureMetadata[e];if(r?.sliceBorder){const e=r.sliceBorder;n.setTextureMetadata(s,e.left,e.right,e.top,e.bottom)}}}}(t,r,a);let l={},c=null;if(s&&(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"])}}(s),l=await async function(e,t,r,n,s){const o={};for(const i of n.entities)for(const n of i.components){if("SpineAnimation"!==n.type||!n.data)continue;const i=n.data.skeletonPath,a=n.data.atlasPath;if(!i||!a)continue;const l=s.resolvePath(i),c=s.resolvePath(a);try{const n=s.readText(a),u=l.endsWith(".skel");let h,d;if(u){const e=s.readBinary(i);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=s.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,n,n.length,u);if(t._free(h),p<0)continue;o[i]=p;const f=Xt(n),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=m+"/"+f[t];try{const o=s.loadPixelsRaw?await s.loadPixelsRaw(n):await s.loadPixels(n),i=Gt(e,o,!1),a=e.getResourceManager().getTextureGLId(i);r.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,s,c,r,n)),o){new Nt("",{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={},n={};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===r[s])try{const e=JSON.parse(t.readText(s));if(!e.vertexSource||!e.fragmentSource){r[s]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=n[o];i||(i=Me.createShader(e.vertexSource,e.fragmentSource),n[o]=i),r[s]=Me.createFromAsset(e,i)}catch{r[s]=0}}return r}(r,n),h=ke(e.world,r);if(function(e,t,r,n){for(const s of t.entities){const t=n.get(s.id);if(void 0!==t)for(const n of s.components)if("Sprite"===n.type&&n.data.texture&&"string"==typeof n.data.texture){const s=e.get(t,z);s&&(s.texture=r[n.data.texture]||0,e.insert(t,z,s))}}}(e.world,r,a,h),function(e,t,r,n){for(const s of t.entities){const t=n.get(s.id);if(void 0!==t)for(const n of s.components){if(!n.data||"string"!=typeof n.data.material||!n.data.material)continue;const s=r[n.data.material]||0;if(s)if("Sprite"===n.type){const r=e.get(t,z);r&&(r.material=s,e.insert(t,z,r))}else if("SpineAnimation"===n.type){const r=e.get(t,V);r&&(r.material=s,e.insert(t,V,r))}}}}(e.world,r,u,h),s&&c){const n=function(e,t,r,n){const s={};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=n.get(o.id);void 0!==l&&(s[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 s}(c,r,l,h);!function(e,t,r,n,s){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 s){const o=Number(e),i=s[e],a=c.has(o,V)?c.get(o,V):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&n.update(i,l*h);let d=0;if(c.has(o,k)){const e=jt(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=n.getMeshBatchCount(i);for(let e=0;e<p;e++){const s=n.getMeshBatchVertexCount(i,e),o=n.getMeshBatchIndexCount(i,e);if(!s||!o)continue;const a=8*s*4,l=2*o,c=r._malloc(a),u=r._malloc(l),h=r._malloc(4),p=r._malloc(4);n.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*s),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,s,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,s,c,n)}}class Yt{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 n of e.entities)for(const e of n.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,s=e.data.atlasPath;n&&(n.endsWith(".skel")?r.add(n):t.add(n)),s&&t.add(s)}"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const n=[];for(const e of t)n.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of r)n.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(n)}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),n=await r.blob(),s=await createImageBitmap(n),o=new OffscreenCanvas(s.width,s.height).getContext("2d");o.drawImage(s,0,0);const i=o.getImageData(0,0,s.width,s.height);return s.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 Kt={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),r=St.createRenderTarget(e.width,e.height,t);return{_handle:r,textureId:St.getTargetTexture(r),width:e.width,height:e.height}},release(e){St.releaseRenderTarget(e._handle)},resize:(e,t,r)=>(St.releaseRenderTarget(e._handle),Kt.create({width:t,height:r,depth:!0})),begin(e,t){St.begin(t,e._handle)},end(){St.end()},getDepthTexture:e=>St.getTargetDepthTexture(e._handle)};let Jt=!1;var Qt;y||(y=!0,void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const r="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},s=await l(r,n);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: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 n=0;for(let t=0;t<e.length;t++){let s=e.charCodeAt(t);s<128?r[n++]=s:s<2048?(r[n++]=192|s>>6,r[n++]=128|63&s):s>=55296&&s<=56319?(s=e.charCodeAt(++t)-56320+(s-55296<<10)+65536,r[n++]=240|s>>18,r[n++]=128|s>>12&63,r[n++]=128|s>>6&63,r[n++]=128|63&s):(r[n++]=224|s>>12,r[n++]=128|s>>6&63,r[n++]=128|63&s)}return r.subarray(0,n)}}),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 n=t[e];if(n<128)r+=String.fromCharCode(n),e++;else if(192==(224&n))r+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))r+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const s=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;r+=String.fromCharCode(55296+(s>>10),56320+(1023&s)),e+=4}}return r}})}(),console.log("[ESEngine] WeChat platform initialized")),e=Qt=w,console.log(`[ESEngine] Platform: ${Qt.name}`),exports.App=Ut,exports.AssetPlugin=Ne,exports.AssetServer=He,exports.Assets=Oe,exports.AsyncCache=$e,exports.BodyType=A,exports.BoxCollider=P,exports.Camera=L,exports.Canvas=$,exports.CapsuleCollider=T,exports.Children=N,exports.CircleCollider=C,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=te,exports.Draw=et,exports.EntityCommands=ee,exports.GLDebug=At,exports.Geometry=ht,exports.INVALID_ENTITY=0,exports.INVALID_TEXTURE=v,exports.Input=le,exports.InputPlugin=ce,exports.InputState=ae,exports.LocalTransform=W,exports.Material=Me,exports.MaterialLoader=We,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Parent=O,exports.Physics=class{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}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)}},exports.PhysicsEvents=$t,exports.PhysicsPlugin=Nt,exports.PostProcess=_t,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(),n=new Yt(this.baseUrl_);await n.prefetch(t);let s=null;const o=this.app_.__spineInitPromise;if(o){s=(await o).controller.raw}await qt(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 r=e.getEntitiesWithComponents([L]);for(const n of r){if(e.get(n,L).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,r=1920/1080;const n=e.getEntitiesWithComponents([$]);for(const s of n){const n=e.get(s,$);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,r=n.designResolution.x/n.designResolution.y;break}}const s=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(s,W,o);const i={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:r,priority:0,showFrustum:!0};e.insert(s,L,i)}}},exports.Query=function(...e){return function(e,t=[],r=[]){const n=[];return e.forEach((e,t)=>{Q(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:r}}(e)},exports.QueryInstance=Z,exports.RenderPipeline=Rt,exports.RenderTexture=Kt,exports.Renderer=St,exports.Res=q,exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.RigidBody=S,exports.ShaderSources=De,exports.SpineAnimation=V,exports.Sprite=z,exports.SystemRunner=ie,exports.Text=me,exports.TextPlugin=xe,exports.TextRenderer=_e,exports.Time=J,exports.UIRect=ge,exports.Velocity=H,exports.WebAssetProvider=Yt,exports.World=he,exports.WorldTransform=k,exports.addStartupSystem=function(e){oe().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){oe().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){oe().push({schedule:e,system:t})},exports.assetPlugin=Ve,exports.clearDrawCallbacks=function(){Et.clear()},exports.clearUserComponents=function(){R().clear()},exports.color=(e=1,t=1,r=1,n=1)=>({r:e,g:t,b:r,a:n}),exports.createWebApp=function(e,t){const r=Ut.new(),n=new e.Registry;r.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ke(e),Te(e),lt(e),pt(e),vt(e),Ct(e);const s=new Rt;r.pipeline_=s;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:e,height:t}=i(),r=n.entityCount(),l=Bt(n,r+1e3);if(l){const e=l.backgroundColor;St.setClearColor(e.r,e.g,e.b,e.a)}const c=function(e,t,r){const n=e.entityCount(),s=n+1e3;for(let n=0;n<s;n++){if(!e.valid(n)||!e.hasCamera(n)||!e.hasLocalTransform(n))continue;const o=e.getCamera(n);if(!o.isActive)continue;const i=e.getLocalTransform(n),a=t/r;let l;if(1===o.projectionType){let t=o.orthoSize;const r=Bt(e,s);if(r){t=It(r.designResolution.y/2,r.designResolution.x/r.designResolution.y,a,r.scaleMode,r.matchWidthOrHeight)}const n=t*a;l=Dt(-n,n,-t,t,-o.farPlane,o.farPlane)}else l=Wt(o.fov*Math.PI/180,a,o.nearPlane,o.farPlane);return zt(l,kt(i.position.x,i.position.y,i.position.z))}return Ft}(n,e,t),u=(a()-o)/1e3;s.render({registry:{_cpp:n},viewProjection:c,width:e,height:t,elapsed:u})}};return r.addSystemToSchedule(exports.Schedule.Last,l),r.addPlugin(Ve),r.addPlugin(ue),r.addPlugin(ye),r},exports.defineComponent=U,exports.defineResource=j,exports.defineSystem=se,exports.defineTag=function(e){const t=R(),r=t.get(e);if(r)return r;const n=M(e,{});return t.set(e,n),B(e,{},!0),n},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=Ke,exports.initGLDebugAPI=Ct,exports.initGeometryAPI=lt,exports.initMaterialAPI=Te,exports.initPostProcessAPI=pt,exports.initRendererAPI=vt,exports.inputPlugin=ue,exports.isBuiltinComponent=D,exports.isEditor=function(){return Jt},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!Jt},exports.isTextureRef=ve,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=Le,exports.loadPhysicsModule=Lt,exports.loadRuntimeScene=qt,exports.loadSceneData=ke,exports.loadSceneWithAssets=ze,exports.platformFetch=r,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,r){return t().instantiateWasm(e,r)},exports.platformReadFile=n,exports.platformReadTextFile=s,exports.quat=(e=1,t=0,r=0,n=0)=>({w:e,x:t,y:r,z:n}),exports.registerDrawCallback=function(e,t){Et.set(e,t)},exports.registerEmbeddedAssets=function(e,t){const r=e.getResource(Oe);r&&r.registerEmbeddedAssets(t)},exports.registerMaterialCallback=Ie,exports.setEditorMode=function(e){Jt=e},exports.shutdownDrawAPI=Je,exports.shutdownGLDebugAPI=Tt,exports.shutdownGeometryAPI=ct,exports.shutdownMaterialAPI=Ae,exports.shutdownPostProcessAPI=ft,exports.shutdownRendererAPI=bt,exports.textPlugin=ye,exports.unregisterDrawCallback=Mt,exports.updateCameraAspectRatio=function(e,t){const r=e.getEntitiesWithComponents([L]);for(const n of r){const r=e.get(n,L);r&&(r.aspectRatio=t,e.insert(n,L,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,n=1)=>({x:e,y:t,z:r,w:n}),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,n)=>{h().writeFile({filePath:e,data:t,success:()=>r(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};
//# sourceMappingURL=index.wechat.cjs.js.map
diff --git a/desktop/public/sdk/cjs/index.wechat.js b/desktop/public/sdk/cjs/index.wechat.js
index ea77e578f..6372a79b4 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,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 b||(b=wx.createCanvas(),b.width=e,b.height=t,S=b.getContext("2d")),(b.width<e||b.height<t)&&(b.width=Math.max(b.width,e),b.height=Math.max(b.height,t)),{canvas:b,ctx:S}}(t,n);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,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)=>({x:e,y:t,z:n,w:r}),z=(e=1,t=0,n=0,r=0)=>({w:e,x:t,y:n,z:r});function W(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const k=W("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),D=W("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),$=W("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),L=W("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 X(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function j(e,t){const n=X(),r=n.get(e);if(r)return r;const s=N(e,t);return n.set(e,s),Y(e,t,!1),s}function V(e){const t=X(),n=t.get(e);if(n)return n;const r=N(e,{});return t.set(e,r),Y(e,{},!0),r}function G(e){return X().get(e)}function q(){X().clear()}function Y(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:{x:1,y:1,z:1,w: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}),ne=K("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w: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:{x:1,y:1,z:1,w:1},layer:0,skeletonScale:1,material:0}),ae={LocalTransform:Q,WorldTransform:Z,Sprite:ee,Camera:te,Canvas:ne,Velocity:re,Parent:se,Children:ie,SpineAnimation:oe,RigidBody:k,BoxCollider:D,CircleCollider:$,CapsuleCollider:L};function ce(e){const t=ae[e];if(t)return{...t._default};const n=G(e);return n?{...n._default}:null}let le=0;function ue(e,t){const n=++le;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function he(e){return{_type:"res",_resource:e}}function de(e){return{_type:"res_mut",_resource:e}}class fe{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 pe{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 fe(this.get(e),t=>this.set(e,t))}}const _e=ue({delta:0,elapsed:0,frameCount:0},"Time");function me(e){return{_type:"mut",_component:e}}function ge(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function ye(...e){return function(e,t=[],n=[]){const r=[];return e.forEach((e,t)=>{ge(e)&&r.push(t)}),{_type:"query",_components:e,_mutIndices:r,_with:t,_without:n}}(e)}class we{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return ge(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 xe(){return{_type:"commands"}}class ve{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 be{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ve(this,null);return this.spawned_.push(e),e}entity(e){return new ve(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 Pe=0;function Ce(e,t,n){const r=++Pe;return{_id:Symbol(`System_${r}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${r}`}}function Ee(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Te(e){Ee().push({schedule:Se.Update,system:e})}function Ae(e){Ee().push({schedule:Se.Startup,system:e})}function Me(e,t){Ee().push({schedule:e,system:t})}class Re{constructor(e,t){this.world_=e,this.resources_=t}run(e){const t=e._params.map(e=>this.resolveParam(e));e._fn(...t);for(const e of t)e instanceof be&&e.flush()}resolveParam(e){switch(e._type){case"query":return new we(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new be(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ue{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 Fe=ue(new Ue,"Input");class Be{constructor(e){this.target_=e??null}build(e){const n=new Ue;e.insertResource(Fe,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,Ce([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Ie=new Be;class ze{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,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 We,ke,De;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(We||(We={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(ke||(ke={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(De||(De={}));const $e=j("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:We.Left,verticalAlign:ke.Top,wordWrap:!0,overflow:De.Visible,lineHeight:1.2,dirty:!0});class Le{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===De.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.x),m=Math.round(255*e.color.y),g=Math.round(255*e.color.z),y=e.color.w;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===De.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 ke.Top:x=u;break;case ke.Middle:x=(p-w)/2;break;case ke.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 We.Left:r=u;break;case We.Center:r=f/2;break;case We.Right:r=f-u;break;default:r=u}n.fillText(t,r,v),v+=l}s&&e.overflow===De.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 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 We.Left:return"left";case We.Center:return"center";case We.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const He=j("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class Oe{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Le(t),r=e.world;e.addSystemToSchedule(Se.PreUpdate,Ce([],()=>{const e=r.getEntitiesWithComponents([$e]);for(const t of e){const e=r.get(t,$e);if(!e.dirty)continue;r.has(t,ee)||r.insert(t,ee,{texture:R,size:{x:0,y:0},color:{x:1,y:1,z:1,w:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const s=r.has(t,He)?r.get(t,He):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 Ne=new Oe;var Xe;function je(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 Ve=null,Ge=null,qe=1;const Ye=new Map;function Ke(e){Ve=e,Ge=e.getResourceManager(),st()}function Je(){0!==tt&&Ve&&(Ve._free(tt),tt=0),Ye.clear(),qe=1,et=!1,Ge=null,Ve=null}function Qe(){if(!Ge)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ge}const Ze={createShader:(e,t)=>Qe().createShader(e,t),releaseShader(e){e>0&&Qe().releaseShader(e)},create(e){const t=qe++,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 Ye.set(t,n),t},get:e=>Ye.get(e),setUniform(e,t,n){const r=Ye.get(e);r&&r.uniforms.set(t,n)},getUniform(e,t){const n=Ye.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Ye.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Ye.get(e);return t?.blendMode??Xe.Normal},setDepthTest(e,t){const n=Ye.get(e);n&&(n.depthTest=t)},getShader(e){const t=Ye.get(e);return t?.shader??0},release(e){Ye.delete(e)},isValid:e=>Ye.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;"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=Ye.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 Ye.set(n,r),n},toAssetData(e,t){const n=Ye.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=Ye.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let et=!1,tt=0;const nt=4096;function rt(e){const t=(0===tt&&Ve&&(tt=Ve._malloc(nt)),tt);if(0===t||!Ve)return{ptr:0,count:0};let n=0,r=0;const s=Ve.HEAPU8,i=Ve.HEAPU32,o=Ve.HEAPF32;for(const[a,c]of e){if(n+128>nt)break;const e=(new TextEncoder).encode(a),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 st(){if(!Ve||et)return;Ve.materialDataProvider=(e,t,n,r,s)=>{const i=Ye.get(e);if(!i)return Ve.HEAPU32[t>>2]=0,Ve.HEAPU32[n>>2]=0,Ve.HEAPU32[r>>2]=0,void(Ve.HEAPU32[s>>2]=0);Ve.HEAPU32[t>>2]=i.shader,Ve.HEAPU32[n>>2]=i.blendMode;const{ptr:o,count:a}=rt(i.uniforms);Ve.HEAPU32[r>>2]=o,Ve.HEAPU32[s>>2]=a},et=!0}const it={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class ot{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const n=this.pending_.get(e);if(n)return n;const 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&&(Ze.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ze.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:Ze.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 at(e,t){const n=new Map;for(const r of t.entities){const t=e.spawn();n.set(r.id,t);for(const n of r.components)lt(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 ct(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);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}}lt(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 lt(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,$e,r);break;case"SpineAnimation":e.insert(t,oe,r);break;case"UIRect":e.insert(t,He,r);break;case"RigidBody":e.insert(t,k,r);break;case"BoxCollider":e.insert(t,D,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 ut(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))}}class ht{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 dt{constructor(e){this.textureCache_=new ht,this.shaderCache_=new ht,this.jsonCache_=new ht,this.textCache_=new ht,this.binaryCache_=new ht,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.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 ot(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n)}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const 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 ct(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 Ze.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 ft=ue(null,"Assets");class pt{build(e){const t=e.wasmModule;t?e.insertResource(ft,new dt(t)):console.warn("AssetPlugin: No WASM module available")}}const _t=new pt;function mt(e,t){const n=e.getResource(ft);n&&n.registerEmbeddedAssets(t)}let gt=null,yt=0,wt=0,xt=0;const vt=new Float32Array(256);function bt(e){gt=e,yt=gt._malloc(64),wt=gt._malloc(64),xt=gt._malloc(1024)}function St(){gt&&(yt&&(gt._free(yt),yt=0),wt&&(gt._free(wt),wt=0),xt&&(gt._free(xt),xt=0)),gt=null}function Pt(){if(!gt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return gt}const Ct={x:1,y:1,z:1,w:1},Et={begin(e){const t=Pt();t.HEAPF32.set(e,yt/4),t.draw_begin(yt)},end(){Pt().draw_end()},line(e,t,n,r=1){Pt().draw_line(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,r)},rect(e,t,n,r=!0){Pt().draw_rect(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,r)},rectOutline(e,t,n,r=1){Pt().draw_rectOutline(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,r)},circle(e,t,n,r=!0,s=32){Pt().draw_circle(e.x,e.y,t,n.x,n.y,n.z,n.w,r,s)},circleOutline(e,t,n,r=1,s=32){Pt().draw_circleOutline(e.x,e.y,t,n.x,n.y,n.z,n.w,r,s)},texture(e,t,n,r=Ct){Pt().draw_texture(e.x,e.y,t.x,t.y,n,r.x,r.y,r.z,r.w)},textureRotated(e,t,n,r,s=Ct){Pt().draw_textureRotated(e.x,e.y,t.x,t.y,n,r,s.x,s.y,s.z,s.w)},setLayer(e){Pt().draw_setLayer(e)},setDepth(e){Pt().draw_setDepth(e)},getDrawCallCount:()=>gt?gt.draw_getDrawCallCount():0,getPrimitiveCount:()=>gt?gt.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,wt/4),r.draw_mesh(e,t,wt)},drawMeshWithMaterial(e,t,n){const r=Pt(),s=Ze.get(t);if(!s)return;if(Et.setBlendMode(s.blendMode),Et.setDepthTest(s.depthTest),0===s.uniforms.size)return void Et.drawMesh(e,s.shader,n);r.HEAPF32.set(n,wt/4);let i=0,o=0;for(const[e,t]of s.uniforms){const n=At(e);if(!(n<0)){if(je(t))vt[i++]=10,vt[i++]=n,vt[i++]=t.slot??o++,vt[i++]=t.textureId;else if("number"==typeof t)vt[i++]=1,vt[i++]=n,vt[i++]=t;else if(Array.isArray(t)){vt[i++]=t.length,vt[i++]=n;for(let e=0;e<t.length;e++)vt[i++]=t[e]}else"w"in t?(vt[i++]=4,vt[i++]=n,vt[i++]=t.x,vt[i++]=t.y,vt[i++]=t.z,vt[i++]=t.w):"z"in t?(vt[i++]=3,vt[i++]=n,vt[i++]=t.x,vt[i++]=t.y,vt[i++]=t.z):(vt[i++]=2,vt[i++]=n,vt[i++]=t.x,vt[i++]=t.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==i?(r.HEAPF32.set(vt.subarray(0,i),xt/4),r.draw_meshWithUniforms(e,s.shader,wt,xt,i)):r.draw_mesh(e,s.shader,wt)}},Tt={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 Tt[e]??-1}var Mt;!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"}(Mt||(Mt={}));let Rt=null,Ut=0,Ft=0,Bt=0;function It(e){Rt=e,Ut=Rt._malloc(262144),Ft=Rt._malloc(65536),Bt=Rt._malloc(256)}function zt(){Rt&&(Ut&&Rt._free(Ut),Ft&&Rt._free(Ft),Bt&&Rt._free(Bt),Ut=0,Ft=0,Bt=0),Rt=null}function Wt(){if(!Rt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Rt}const kt={create(e){const t=Wt(),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,Ut/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,Bt,s).set(i),t.geometry_init(n,Ut,r,Bt,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,Ft,r).set(e.indices),t.geometry_setIndices16(n,Ft,r)}else{new Uint32Array(t.HEAPU8.buffer,Ft,r).set(e.indices),t.geometry_setIndices32(n,Ft,r)}}return n},updateVertices(e,t,n=0){const r=Wt(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);r.HEAPF32.set(t,Ut/4),r.geometry_updateVertices(e,Ut,s,n)},release(e){e>0&&Wt().geometry_release(e)},isValid:e=>!(!Rt||e<=0)&&Rt.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,r=t/2;return kt.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:Mt.Float2},{name:"a_texCoord",type:Mt.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 kt.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Mt.Float2},{name:"a_texCoord",type:Mt.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 kt.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:Mt.Float2},{name:"a_texCoord",type:Mt.Float2}],indices:new Uint16Array(o)})}};let Dt=null;function $t(e){Dt=e}function Lt(){Dt&&Ot.isInitialized()&&Ot.shutdown(),Dt=null}function Ht(){if(!Dt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Dt}const Ot={init:(e,t)=>Ht().postprocess_init(e,t),shutdown(){Ht().postprocess_shutdown()},resize(e,t){Ht().postprocess_resize(e,t)},addPass:(e,t)=>Ht().postprocess_addPass(e,t),removePass(e){Ht().postprocess_removePass(e)},setEnabled(e,t){Ht().postprocess_setPassEnabled(e,t)},isEnabled:e=>Ht().postprocess_isPassEnabled(e),setUniform(e,t,n){Ht().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Ht().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Ht().postprocess_begin()},end(){Ht().postprocess_end()},getPassCount:()=>Ht().postprocess_getPassCount(),isInitialized:()=>!!Dt&&Dt.postprocess_isInitialized(),setBypass(e){Ht().postprocess_setBypass(e)},isBypassed:()=>!Dt||Dt.postprocess_isBypassed(),createBlur:()=>Ze.createShader(Nt,"#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:()=>Ze.createShader(Nt,"#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:()=>Ze.createShader(Nt,"#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:()=>Ze.createShader(Nt,"#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")},Nt="#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 Xt;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Xt||(Xt={}));let jt=null,Vt=0;function Gt(e){jt=e,Vt=jt._malloc(64)}function qt(){jt&&Vt&&(jt._free(Vt),Vt=0),jt=null}const Yt={init(e,t){jt?.renderer_init(e,t)},resize(e,t){jt?.renderer_resize(e,t)},begin(e,t){jt&&Vt&&(jt.HEAPF32.set(e,Vt/4),jt.renderer_begin(Vt,t??0))},flush(){jt?.renderer_flush()},end(){jt?.renderer_end()},submitSprites(e){jt&&jt.renderer_submitSprites(e._cpp)},submitSpine(e){jt&&jt.renderer_submitSpine?.(e._cpp)},setStage(e){jt?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>jt?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){jt?.renderer_releaseTarget(e)},getTargetTexture:e=>jt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>jt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,r){jt?.renderer_setClearColor?.(e,t,n,r)},getStats:()=>jt?{drawCalls:jt.renderer_getDrawCalls(),triangles:jt.renderer_getTriangles(),sprites:jt.renderer_getSprites(),spine:jt.renderer_getSpine?.()??0,meshes:jt.renderer_getMeshes(),culled:jt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let Kt=null;function Jt(e){Kt=e}function Qt(){Kt=null}const Zt={enable(){Kt?.gl_enableErrorCheck(!0)},disable(){Kt?.gl_enableErrorCheck(!1)},check:e=>Kt?.gl_checkErrors(e)??0,diagnose(){Kt?.renderer_diagnose()}},en=new Map;function tn(e,t){en.set(e,t)}function nn(e){en.delete(e)}function rn(){en.clear()}class sn{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:n,width:r,height:s,elapsed:i}=e;Yt.resize(r,s),Ot.isInitialized()&&Ot.getPassCount()>0&&!Ot.isBypassed()&&Ot.resize(r,s),Yt.begin(n),Yt.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,i):Yt.submitSpine(t),Yt.flush();const o=en;if(o.size>0){Et.begin(n);const e=[];for(const[t,n]of o.entries())try{n(i)}catch(n){console.error(`[CustomDraw] callback '${t}' error:`,n),e.push(t)}Et.end();for(const t of e)nn(t)}Yt.end()}}class on{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 ze,this.resources_=new pe;for(const e of Object.values(Se))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new on}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_}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 Re(this.world_,this.resources_),this.resources_.insert(_e,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Se.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Qt(),qt(),Lt(),zt(),Je(),St()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(_e),n={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(_e,n)}}function an(e,t){const n=on.new(),r=new e.Registry;n.connectCpp(r,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),bt(e),Ke(e),It(e),$t(e),Gt(e),Jt(e);const s=new sn;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:e,height:t}=o(),n=r.entityCount(),a=un(r,n+1e3);if(a){const e=a.backgroundColor;Yt.setClearColor(e.x,e.y,e.z,e.w)}const c=function(e,t,n){const r=e.entityCount(),s=r+1e3;for(let r=0;r<s;r++){if(!e.valid(r)||!e.hasCamera(r)||!e.hasLocalTransform(r))continue;const i=e.getCamera(r);if(!i.isActive)continue;const o=e.getLocalTransform(r),a=t/n;let c;if(1===i.projectionType){let t=i.orthoSize;const n=un(e,s);if(n){t=hn(n.designResolution.y/2,n.designResolution.x/n.designResolution.y,a,n.scaleMode,n.matchWidthOrHeight)}const r=t*a;c=dn(-r,r,-t,t,-i.farPlane,i.farPlane)}else c=fn(i.fov*Math.PI/180,a,i.nearPlane,i.farPlane);return _n(c,pn(o.position.x,o.position.y,o.position.z))}return ln}(r,e,t),l=(d()-i)/1e3;s.render({registry:{_cpp:r},viewProjection:c,width:e,height:t,elapsed:l})}};return n.addSystemToSchedule(Se.Last,a),n.addPlugin(_t),n.addPlugin(Ie),n.addPlugin(Ne),n}function cn(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 ln=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function un(e,t){for(let n=0;n<t;n++){if(!e.valid(n)||!e.hasCanvas(n))continue;return e.getCanvas(n)}return null}function hn(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 dn(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 fn(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 pn(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 _n(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 mn(e,t){if(t)return t();return(0,(await import(e)).default)()}const gn=ue({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents");function yn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function wn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class xn{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(gn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,r=mn(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=e.world;e.addSystemToSchedule(Se.PostUpdate,Ce([he(_e)],i=>{const o=s.getEntitiesWithComponents([k,Q,Z]),a=new Set;for(const i of o){a.add(i);const o=s.get(i,k),c=s.get(i,Z);if(t.has(i)){const e=n.get(i);!e||e.bodyType===o.bodyType&&e.gravityScale===o.gravityScale&&e.linearDamping===o.linearDamping&&e.angularDamping===o.angularDamping&&e.fixedRotation===o.fixedRotation&&e.bullet===o.bullet||(r._physics_updateBodyProperties(i,o.bodyType,o.gravityScale,o.linearDamping,o.angularDamping,o.fixedRotation?1:0,o.bullet?1:0),e.bodyType=o.bodyType,e.gravityScale=o.gravityScale,e.linearDamping=o.linearDamping,e.angularDamping=o.angularDamping,e.fixedRotation=o.fixedRotation,e.bullet=o.bullet)}else{if(!o.enabled)continue;const s=yn(c.rotation);r._physics_createBody(i,o.bodyType,c.position.x,c.position.y,s,o.gravityScale,o.linearDamping,o.angularDamping,o.fixedRotation?1:0,o.bullet?1:0),vn(e,r,i),t.add(i),n.set(i,{bodyType:o.bodyType,gravityScale:o.gravityScale,linearDamping:o.linearDamping,angularDamping:o.angularDamping,fixedRotation:o.fixedRotation,bullet:o.bullet})}if(o.bodyType===H.Kinematic){const e=yn(c.rotation);r._physics_setBodyTransform(i,c.position.x,c.position.y,e)}}for(const e of t)a.has(e)||(r._physics_destroyBody(e),t.delete(e),n.delete(e));r._physics_step(i.delta),function(e,t){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),s=r>>2;for(let r=0;r<n;r++){const n=s+4*r,i=t.HEAPU32[n],o=t.HEAPF32[n+1],a=t.HEAPF32[n+2],c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const l=e.world.get(i,Q);if(!l)continue;let u=o,h=a,d=c;if(e.world.has(i,se)){const t=e.world.get(i,se);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,Z)){const n=e.world.get(t.entity,Z),r=yn(n.rotation),s=o-n.position.x,i=a-n.position.y,l=Math.cos(-r),f=Math.sin(-r);u=(s*l-i*f)/(0!==n.scale.x?n.scale.x:1),h=(s*f+i*l)/(0!==n.scale.y?n.scale.y:1),d=c-r}}l.position.x=u,l.position.y=h;const f=wn(d);l.rotation.w=f.w,l.rotation.x=f.x,l.rotation.y=f.y,l.rotation.z=f.z,e.world.insert(i,Q,l)}}(e,r),function(e,t){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let s=0;s<r;s++){const r=e+6*s;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4],contactY:t.HEAPF32[r+5]})}}const s=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const r=e+2*n;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1]})}}const o=[],a=t._physics_getSensorEnterCount();if(a>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<a;n++){const r=e+2*n;o.push({sensorEntity:t.HEAPU32[r],visitorEntity:t.HEAPU32[r+1]})}}const c=[],l=t._physics_getSensorExitCount();if(l>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<l;n++){const r=e+2*n;c.push({sensorEntity:t.HEAPU32[r],visitorEntity:t.HEAPU32[r+1]})}}e.insertResource(gn,{collisionEnters:n,collisionExits:s,sensorEnters:o,sensorExits:c})}(e,r)},{name:"PhysicsSystem"})),e.__physicsModule=r});e.__physicsInitPromise=r}}function vn(e,t,n){const r=e.world;if(r.has(n,D)){const e=r.get(n,D);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(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 bn{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}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 Sn(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 Cn(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 En(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]=Sn(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=Sn(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 xn("",{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=Ze.createShader(e.vertexSource,e.fragmentSource),r[i]=o),n[s]=Ze.createFromAsset(e,o)}catch{n[s]=0}}return n}(n,r),h=at(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=Cn(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 Tn{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 An{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 Tn(this.baseUrl_);await n.prefetch(t);let r=null;const s=this.app_.__spineInitPromise;if(s){r=(await s).controller.raw}await En(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};e.insert(s,te,o)}}}const Mn={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Yt.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Yt.getTargetTexture(n),width:e.width,height:e.height}},release(e){Yt.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Yt.releaseRenderTarget(e._handle),Mn.create({width:t,height:n,depth:!0})),begin(e,t){Yt.begin(t,e._handle)},end(){Yt.end()},getDepthTexture:e=>Yt.getTargetDepthTexture(e._handle)};let Rn=!1;function Un(e){Rn=e}function Fn(){return Rn}function Bn(){return!Rn}var In;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=In=A,console.log(`[ESEngine] Platform: ${In.name}`);export{on as App,pt as AssetPlugin,dt as AssetServer,ft as Assets,ht as AsyncCache,Xe as BlendMode,H as BodyType,D as BoxCollider,te as Camera,ne as Canvas,L as CapsuleCollider,ie as Children,$ as CircleCollider,xe as Commands,be as CommandsInstance,Mt as DataType,Et as Draw,ve as EntityCommands,Zt as GLDebug,kt as Geometry,M as INVALID_ENTITY,R as INVALID_TEXTURE,Fe as Input,Be as InputPlugin,Ue as InputState,Q as LocalTransform,Ze as Material,ot as MaterialLoader,me as Mut,se as Parent,bn as Physics,gn as PhysicsEvents,xn as PhysicsPlugin,Ot as PostProcess,An as PreviewPlugin,ye as Query,we as QueryInstance,sn as RenderPipeline,Xt as RenderStage,Mn as RenderTexture,Yt as Renderer,he as Res,de as ResMut,k as RigidBody,Se as Schedule,it as ShaderSources,oe as SpineAnimation,ee as Sprite,Re as SystemRunner,$e as Text,We as TextAlign,De as TextOverflow,Oe as TextPlugin,Le as TextRenderer,ke as TextVerticalAlign,_e as Time,He as UIRect,re as Velocity,Tn as WebAssetProvider,ze as World,Z as WorldTransform,Ae as addStartupSystem,Te as addSystem,Me as addSystemToSchedule,_t as assetPlugin,rn as clearDrawCallbacks,q as clearUserComponents,I as color,an as createWebApp,j as defineComponent,ue as defineResource,Ce as defineSystem,V as defineTag,cn as flushPendingSystems,ce as getComponentDefaults,t as getPlatform,r as getPlatformType,G as getUserComponent,bt as initDrawAPI,Jt as initGLDebugAPI,It as initGeometryAPI,Ke as initMaterialAPI,$t as initPostProcessAPI,Gt as initRendererAPI,Ie as inputPlugin,J as isBuiltinComponent,Fn as isEditor,n as isPlatformInitialized,Bn as isRuntime,je as isTextureRef,s as isWeChat,i as isWeb,lt as loadComponent,mn as loadPhysicsModule,En as loadRuntimeScene,at as loadSceneData,ct as loadSceneWithAssets,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,z as quat,tn as registerDrawCallback,mt as registerEmbeddedAssets,st as registerMaterialCallback,Un as setEditorMode,St as shutdownDrawAPI,Qt as shutdownGLDebugAPI,zt as shutdownGeometryAPI,Je as shutdownMaterialAPI,Lt as shutdownPostProcessAPI,qt as shutdownRendererAPI,Ne as textPlugin,nn as unregisterDrawCallback,ut as updateCameraAspectRatio,U as vec2,F as vec3,B as vec4,w as wxFileExists,x as wxFileExistsSync,C as wxGetImagePixels,P 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,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 X(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function j(e,t){const n=X(),r=n.get(e);if(r)return r;const s=N(e,t);return n.set(e,s),Y(e,t,!1),s}function V(e){const t=X(),n=t.get(e);if(n)return n;const r=N(e,{});return t.set(e,r),Y(e,{},!0),r}function G(e){return X().get(e)}function q(){X().clear()}function Y(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}),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={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 ce(e){const t=ae[e];if(t)return{...t._default};const n=G(e);return n?{...n._default}:null}let le=0;function ue(e,t){const n=++le;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function he(e){return{_type:"res",_resource:e}}function de(e){return{_type:"res_mut",_resource:e}}class fe{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 pe{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 fe(this.get(e),t=>this.set(e,t))}}const _e=ue({delta:0,elapsed:0,frameCount:0},"Time");function me(e){return{_type:"mut",_component:e}}function ge(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function ye(...e){return function(e,t=[],n=[]){const r=[];return e.forEach((e,t)=>{ge(e)&&r.push(t)}),{_type:"query",_components:e,_mutIndices:r,_with:t,_without:n}}(e)}class we{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return ge(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 xe(){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 ve{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 Pe=0;function Ce(e,t,n){const r=++Pe;return{_id:Symbol(`System_${r}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${r}`}}function Ee(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Te(e){Ee().push({schedule:Se.Update,system:e})}function Ae(e){Ee().push({schedule:Se.Startup,system:e})}function Me(e,t){Ee().push({schedule:e,system:t})}class Re{constructor(e,t){this.world_=e,this.resources_=t}run(e){const t=e._params.map(e=>this.resolveParam(e));e._fn(...t);for(const e of t)e instanceof ve&&e.flush()}resolveParam(e){switch(e._type){case"query":return new we(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new ve(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ue{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 Fe=ue(new Ue,"Input");class Be{constructor(e){this.target_=e??null}build(e){const n=new Ue;e.insertResource(Fe,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,Ce([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Ie=new Be;class We{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,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 ke,De,ze;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(ke||(ke={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(De||(De={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(ze||(ze={}));const $e=j("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:ke.Left,verticalAlign:De.Top,wordWrap:!0,overflow:ze.Visible,lineHeight:1.2,dirty:!0});class Le{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===ze.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===ze.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 De.Top:x=u;break;case De.Middle:x=(p-w)/2;break;case De.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 ke.Left:r=u;break;case ke.Center:r=f/2;break;case ke.Right:r=f-u;break;default:r=u}n.fillText(t,r,b),b+=l}s&&e.overflow===ze.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)}}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 ke.Left:return"left";case ke.Center:return"center";case ke.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const He=j("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class Oe{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Le(t),r=e.world;e.addSystemToSchedule(Se.PreUpdate,Ce([],()=>{const e=r.getEntitiesWithComponents([$e]);for(const t of e){const e=r.get(t,$e);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,He)?r.get(t,He):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 Ne=new Oe;var Xe;function je(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 Ve=null,Ge=null,qe=1;const Ye=new Map;function Ke(e){Ve=e,Ge=e.getResourceManager(),st()}function Je(){0!==tt&&Ve&&(Ve._free(tt),tt=0),Ye.clear(),qe=1,et=!1,Ge=null,Ve=null}function Qe(){if(!Ge)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ge}const Ze={createShader:(e,t)=>Qe().createShader(e,t),releaseShader(e){e>0&&Qe().releaseShader(e)},create(e){const t=qe++,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 Ye.set(t,n),t},get:e=>Ye.get(e),setUniform(e,t,n){const r=Ye.get(e);r&&r.uniforms.set(t,n)},getUniform(e,t){const n=Ye.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Ye.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Ye.get(e);return t?.blendMode??Xe.Normal},setDepthTest(e,t){const n=Ye.get(e);n&&(n.depthTest=t)},getShader(e){const t=Ye.get(e);return t?.shader??0},release(e){Ye.delete(e)},isValid:e=>Ye.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=Ye.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 Ye.set(n,r),n},toAssetData(e,t){const n=Ye.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=Ye.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let et=!1,tt=0;const nt=4096;function rt(e){const t=(0===tt&&Ve&&(tt=Ve._malloc(nt)),tt);if(0===t||!Ve)return{ptr:0,count:0};let n=0,r=0;const s=Ve.HEAPU8,i=Ve.HEAPU32,o=Ve.HEAPF32;for(const[a,c]of e){if(n+128>nt)break;const e=(new TextEncoder).encode(a),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 st(){if(!Ve||et)return;Ve.materialDataProvider=(e,t,n,r,s)=>{const i=Ye.get(e);if(!i)return Ve.HEAPU32[t>>2]=0,Ve.HEAPU32[n>>2]=0,Ve.HEAPU32[r>>2]=0,void(Ve.HEAPU32[s>>2]=0);Ve.HEAPU32[t>>2]=i.shader,Ve.HEAPU32[n>>2]=i.blendMode;const{ptr:o,count:a}=rt(i.uniforms);Ve.HEAPU32[r>>2]=o,Ve.HEAPU32[s>>2]=a},et=!0}const it={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class ot{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const n=this.pending_.get(e);if(n)return n;const 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&&(Ze.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ze.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:Ze.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 at(e,t){const n=new Map;for(const r of t.entities){const t=e.spawn();n.set(r.id,t);for(const n of r.components)lt(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 ct(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);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}}lt(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 lt(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,$e,r);break;case"SpineAnimation":e.insert(t,oe,r);break;case"UIRect":e.insert(t,He,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 ut(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))}}class ht{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 dt{constructor(e){this.textureCache_=new ht,this.shaderCache_=new ht,this.jsonCache_=new ht,this.textCache_=new ht,this.binaryCache_=new ht,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.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 ot(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n)}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const 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 ct(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 Ze.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 ft=ue(null,"Assets");class pt{build(e){const t=e.wasmModule;t?e.insertResource(ft,new dt(t)):console.warn("AssetPlugin: No WASM module available")}}const _t=new pt;function mt(e,t){const n=e.getResource(ft);n&&n.registerEmbeddedAssets(t)}let gt=null,yt=0,wt=0,xt=0;const bt=new Float32Array(256);function vt(e){gt=e,yt=gt._malloc(64),wt=gt._malloc(64),xt=gt._malloc(1024)}function St(){gt&&(yt&&(gt._free(yt),yt=0),wt&&(gt._free(wt),wt=0),xt&&(gt._free(xt),xt=0)),gt=null}function Pt(){if(!gt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return gt}const Ct={r:1,g:1,b:1,a:1},Et={begin(e){const t=Pt();t.HEAPF32.set(e,yt/4),t.draw_begin(yt)},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=Ct){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=Ct){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:()=>gt?gt.draw_getDrawCallCount():0,getPrimitiveCount:()=>gt?gt.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,wt/4),r.draw_mesh(e,t,wt)},drawMeshWithMaterial(e,t,n){const r=Pt(),s=Ze.get(t);if(!s)return;if(Et.setBlendMode(s.blendMode),Et.setDepthTest(s.depthTest),0===s.uniforms.size)return void Et.drawMesh(e,s.shader,n);r.HEAPF32.set(n,wt/4);let i=0,o=0;for(const[e,t]of s.uniforms){const n=At(e);if(!(n<0)){if(je(t))bt[i++]=10,bt[i++]=n,bt[i++]=t.slot??o++,bt[i++]=t.textureId;else if("number"==typeof t)bt[i++]=1,bt[i++]=n,bt[i++]=t;else if(Array.isArray(t)){bt[i++]=t.length,bt[i++]=n;for(let e=0;e<t.length;e++)bt[i++]=t[e]}else"w"in t?(bt[i++]=4,bt[i++]=n,bt[i++]=t.x,bt[i++]=t.y,bt[i++]=t.z,bt[i++]=t.w):"z"in t?(bt[i++]=3,bt[i++]=n,bt[i++]=t.x,bt[i++]=t.y,bt[i++]=t.z):(bt[i++]=2,bt[i++]=n,bt[i++]=t.x,bt[i++]=t.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==i?(r.HEAPF32.set(bt.subarray(0,i),xt/4),r.draw_meshWithUniforms(e,s.shader,wt,xt,i)):r.draw_mesh(e,s.shader,wt)}},Tt={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 Tt[e]??-1}var Mt;!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"}(Mt||(Mt={}));let Rt=null,Ut=0,Ft=0,Bt=0;function It(e){Rt=e,Ut=Rt._malloc(262144),Ft=Rt._malloc(65536),Bt=Rt._malloc(256)}function Wt(){Rt&&(Ut&&Rt._free(Ut),Ft&&Rt._free(Ft),Bt&&Rt._free(Bt),Ut=0,Ft=0,Bt=0),Rt=null}function kt(){if(!Rt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Rt}const Dt={create(e){const t=kt(),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,Ut/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,Bt,s).set(i),t.geometry_init(n,Ut,r,Bt,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,Ft,r).set(e.indices),t.geometry_setIndices16(n,Ft,r)}else{new Uint32Array(t.HEAPU8.buffer,Ft,r).set(e.indices),t.geometry_setIndices32(n,Ft,r)}}return n},updateVertices(e,t,n=0){const r=kt(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);r.HEAPF32.set(t,Ut/4),r.geometry_updateVertices(e,Ut,s,n)},release(e){e>0&&kt().geometry_release(e)},isValid:e=>!(!Rt||e<=0)&&Rt.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,r=t/2;return Dt.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:Mt.Float2},{name:"a_texCoord",type:Mt.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 Dt.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Mt.Float2},{name:"a_texCoord",type:Mt.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 Dt.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:Mt.Float2},{name:"a_texCoord",type:Mt.Float2}],indices:new Uint16Array(o)})}};let zt=null;function $t(e){zt=e}function Lt(){zt&&Ot.isInitialized()&&Ot.shutdown(),zt=null}function Ht(){if(!zt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return zt}const Ot={init:(e,t)=>Ht().postprocess_init(e,t),shutdown(){Ht().postprocess_shutdown()},resize(e,t){Ht().postprocess_resize(e,t)},addPass:(e,t)=>Ht().postprocess_addPass(e,t),removePass(e){Ht().postprocess_removePass(e)},setEnabled(e,t){Ht().postprocess_setPassEnabled(e,t)},isEnabled:e=>Ht().postprocess_isPassEnabled(e),setUniform(e,t,n){Ht().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Ht().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Ht().postprocess_begin()},end(){Ht().postprocess_end()},getPassCount:()=>Ht().postprocess_getPassCount(),isInitialized:()=>!!zt&&zt.postprocess_isInitialized(),setBypass(e){Ht().postprocess_setBypass(e)},isBypassed:()=>!zt||zt.postprocess_isBypassed(),createBlur:()=>Ze.createShader(Nt,"#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:()=>Ze.createShader(Nt,"#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:()=>Ze.createShader(Nt,"#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:()=>Ze.createShader(Nt,"#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")},Nt="#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 Xt;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Xt||(Xt={}));let jt=null,Vt=0;function Gt(e){jt=e,Vt=jt._malloc(64)}function qt(){jt&&Vt&&(jt._free(Vt),Vt=0),jt=null}const Yt={init(e,t){jt?.renderer_init(e,t)},resize(e,t){jt?.renderer_resize(e,t)},begin(e,t){jt&&Vt&&(jt.HEAPF32.set(e,Vt/4),jt.renderer_begin(Vt,t??0))},flush(){jt?.renderer_flush()},end(){jt?.renderer_end()},submitSprites(e){jt&&jt.renderer_submitSprites(e._cpp)},submitSpine(e){jt&&jt.renderer_submitSpine?.(e._cpp)},setStage(e){jt?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>jt?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){jt?.renderer_releaseTarget(e)},getTargetTexture:e=>jt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>jt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,r){jt?.renderer_setClearColor?.(e,t,n,r)},getStats:()=>jt?{drawCalls:jt.renderer_getDrawCalls(),triangles:jt.renderer_getTriangles(),sprites:jt.renderer_getSprites(),spine:jt.renderer_getSpine?.()??0,meshes:jt.renderer_getMeshes(),culled:jt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let Kt=null;function Jt(e){Kt=e}function Qt(){Kt=null}const Zt={enable(){Kt?.gl_enableErrorCheck(!0)},disable(){Kt?.gl_enableErrorCheck(!1)},check:e=>Kt?.gl_checkErrors(e)??0,diagnose(){Kt?.renderer_diagnose()}},en=new Map;function tn(e,t){en.set(e,t)}function nn(e){en.delete(e)}function rn(){en.clear()}class sn{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:n,width:r,height:s,elapsed:i}=e;Yt.resize(r,s),Ot.isInitialized()&&Ot.getPassCount()>0&&!Ot.isBypassed()&&Ot.resize(r,s),Yt.begin(n),Yt.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,i):Yt.submitSpine(t),Yt.flush();const o=en;if(o.size>0){Et.begin(n);const e=[];for(const[t,n]of o.entries())try{n(i)}catch(n){console.error(`[CustomDraw] callback '${t}' error:`,n),e.push(t)}Et.end();for(const t of e)nn(t)}Yt.end()}}class on{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 We,this.resources_=new pe;for(const e of Object.values(Se))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new on}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_}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 Re(this.world_,this.resources_),this.resources_.insert(_e,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Se.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Qt(),qt(),Lt(),Wt(),Je(),St()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(_e),n={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(_e,n)}}function an(e,t){const n=on.new(),r=new e.Registry;n.connectCpp(r,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),vt(e),Ke(e),It(e),$t(e),Gt(e),Jt(e);const s=new sn;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:e,height:t}=o(),n=r.entityCount(),a=un(r,n+1e3);if(a){const e=a.backgroundColor;Yt.setClearColor(e.r,e.g,e.b,e.a)}const c=function(e,t,n){const r=e.entityCount(),s=r+1e3;for(let r=0;r<s;r++){if(!e.valid(r)||!e.hasCamera(r)||!e.hasLocalTransform(r))continue;const i=e.getCamera(r);if(!i.isActive)continue;const o=e.getLocalTransform(r),a=t/n;let c;if(1===i.projectionType){let t=i.orthoSize;const n=un(e,s);if(n){t=hn(n.designResolution.y/2,n.designResolution.x/n.designResolution.y,a,n.scaleMode,n.matchWidthOrHeight)}const r=t*a;c=dn(-r,r,-t,t,-i.farPlane,i.farPlane)}else c=fn(i.fov*Math.PI/180,a,i.nearPlane,i.farPlane);return _n(c,pn(o.position.x,o.position.y,o.position.z))}return ln}(r,e,t),l=(d()-i)/1e3;s.render({registry:{_cpp:r},viewProjection:c,width:e,height:t,elapsed:l})}};return n.addSystemToSchedule(Se.Last,a),n.addPlugin(_t),n.addPlugin(Ie),n.addPlugin(Ne),n}function cn(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 ln=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function un(e,t){for(let n=0;n<t;n++){if(!e.valid(n)||!e.hasCanvas(n))continue;return e.getCanvas(n)}return null}function hn(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 dn(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 fn(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 pn(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 _n(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 mn(e,t){if(t)return t();return(0,(await import(e)).default)()}const gn=ue({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents");function yn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function wn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class xn{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(gn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,r=mn(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=e.world;e.addSystemToSchedule(Se.PostUpdate,Ce([he(_e)],i=>{const o=s.getEntitiesWithComponents([D,Q,Z]),a=new Set;for(const i of o){a.add(i);const o=s.get(i,D),c=s.get(i,Z);if(t.has(i)){const e=n.get(i);!e||e.bodyType===o.bodyType&&e.gravityScale===o.gravityScale&&e.linearDamping===o.linearDamping&&e.angularDamping===o.angularDamping&&e.fixedRotation===o.fixedRotation&&e.bullet===o.bullet||(r._physics_updateBodyProperties(i,o.bodyType,o.gravityScale,o.linearDamping,o.angularDamping,o.fixedRotation?1:0,o.bullet?1:0),e.bodyType=o.bodyType,e.gravityScale=o.gravityScale,e.linearDamping=o.linearDamping,e.angularDamping=o.angularDamping,e.fixedRotation=o.fixedRotation,e.bullet=o.bullet)}else{if(!o.enabled)continue;const s=yn(c.rotation);r._physics_createBody(i,o.bodyType,c.position.x,c.position.y,s,o.gravityScale,o.linearDamping,o.angularDamping,o.fixedRotation?1:0,o.bullet?1:0),bn(e,r,i),t.add(i),n.set(i,{bodyType:o.bodyType,gravityScale:o.gravityScale,linearDamping:o.linearDamping,angularDamping:o.angularDamping,fixedRotation:o.fixedRotation,bullet:o.bullet})}if(o.bodyType===H.Kinematic){const e=yn(c.rotation);r._physics_setBodyTransform(i,c.position.x,c.position.y,e)}}for(const e of t)a.has(e)||(r._physics_destroyBody(e),t.delete(e),n.delete(e));r._physics_step(i.delta),function(e,t){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),s=r>>2;for(let r=0;r<n;r++){const n=s+4*r,i=t.HEAPU32[n],o=t.HEAPF32[n+1],a=t.HEAPF32[n+2],c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const l=e.world.get(i,Q);if(!l)continue;let u=o,h=a,d=c;if(e.world.has(i,se)){const t=e.world.get(i,se);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,Z)){const n=e.world.get(t.entity,Z),r=yn(n.rotation),s=o-n.position.x,i=a-n.position.y,l=Math.cos(-r),f=Math.sin(-r);u=(s*l-i*f)/(0!==n.scale.x?n.scale.x:1),h=(s*f+i*l)/(0!==n.scale.y?n.scale.y:1),d=c-r}}l.position.x=u,l.position.y=h;const f=wn(d);l.rotation.w=f.w,l.rotation.x=f.x,l.rotation.y=f.y,l.rotation.z=f.z,e.world.insert(i,Q,l)}}(e,r),function(e,t){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let s=0;s<r;s++){const r=e+6*s;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4],contactY:t.HEAPF32[r+5]})}}const s=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const r=e+2*n;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1]})}}const o=[],a=t._physics_getSensorEnterCount();if(a>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<a;n++){const r=e+2*n;o.push({sensorEntity:t.HEAPU32[r],visitorEntity:t.HEAPU32[r+1]})}}const c=[],l=t._physics_getSensorExitCount();if(l>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<l;n++){const r=e+2*n;c.push({sensorEntity:t.HEAPU32[r],visitorEntity:t.HEAPU32[r+1]})}}e.insertResource(gn,{collisionEnters:n,collisionExits:s,sensorEnters:o,sensorExits:c})}(e,r)},{name:"PhysicsSystem"})),e.__physicsModule=r});e.__physicsInitPromise=r}}function bn(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 vn{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}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 Sn(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 Cn(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 En(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]=Sn(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=Sn(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 xn("",{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=Ze.createShader(e.vertexSource,e.fragmentSource),r[i]=o),n[s]=Ze.createFromAsset(e,o)}catch{n[s]=0}}return n}(n,r),h=at(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=Cn(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 Tn{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 An{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 Tn(this.baseUrl_);await n.prefetch(t);let r=null;const s=this.app_.__spineInitPromise;if(s){r=(await s).controller.raw}await En(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};e.insert(s,te,o)}}}const Mn={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Yt.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Yt.getTargetTexture(n),width:e.width,height:e.height}},release(e){Yt.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Yt.releaseRenderTarget(e._handle),Mn.create({width:t,height:n,depth:!0})),begin(e,t){Yt.begin(t,e._handle)},end(){Yt.end()},getDepthTexture:e=>Yt.getTargetDepthTexture(e._handle)};let Rn=!1;function Un(e){Rn=e}function Fn(){return Rn}function Bn(){return!Rn}var In;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=In=A,console.log(`[ESEngine] Platform: ${In.name}`);export{on as App,pt as AssetPlugin,dt as AssetServer,ft as Assets,ht 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,xe as Commands,ve as CommandsInstance,Mt as DataType,Et as Draw,be as EntityCommands,Zt as GLDebug,Dt as Geometry,M as INVALID_ENTITY,R as INVALID_TEXTURE,Fe as Input,Be as InputPlugin,Ue as InputState,Q as LocalTransform,Ze as Material,ot as MaterialLoader,me as Mut,se as Parent,vn as Physics,gn as PhysicsEvents,xn as PhysicsPlugin,Ot as PostProcess,An as PreviewPlugin,ye as Query,we as QueryInstance,sn as RenderPipeline,Xt as RenderStage,Mn as RenderTexture,Yt as Renderer,he as Res,de as ResMut,D as RigidBody,Se as Schedule,it as ShaderSources,oe as SpineAnimation,ee as Sprite,Re as SystemRunner,$e as Text,ke as TextAlign,ze as TextOverflow,Oe as TextPlugin,Le as TextRenderer,De as TextVerticalAlign,_e as Time,He as UIRect,re as Velocity,Tn as WebAssetProvider,We as World,Z as WorldTransform,Ae as addStartupSystem,Te as addSystem,Me as addSystemToSchedule,_t as assetPlugin,rn as clearDrawCallbacks,q as clearUserComponents,I as color,an as createWebApp,j as defineComponent,ue as defineResource,Ce as defineSystem,V as defineTag,cn as flushPendingSystems,ce as getComponentDefaults,t as getPlatform,r as getPlatformType,G as getUserComponent,vt as initDrawAPI,Jt as initGLDebugAPI,It as initGeometryAPI,Ke as initMaterialAPI,$t as initPostProcessAPI,Gt as initRendererAPI,Ie as inputPlugin,J as isBuiltinComponent,Fn as isEditor,n as isPlatformInitialized,Bn as isRuntime,je as isTextureRef,s as isWeChat,i as isWeb,lt as loadComponent,mn as loadPhysicsModule,En as loadRuntimeScene,at as loadSceneData,ct as loadSceneWithAssets,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,W as quat,tn as registerDrawCallback,mt as registerEmbeddedAssets,st as registerMaterialCallback,Un as setEditorMode,St as shutdownDrawAPI,Qt as shutdownGLDebugAPI,Wt as shutdownGeometryAPI,Je as shutdownMaterialAPI,Lt as shutdownPostProcessAPI,qt as shutdownRendererAPI,Ne as textPlugin,nn as unregisterDrawCallback,ut as updateCameraAspectRatio,U as vec2,F as vec3,B 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 0d103fce6..a601f5352 100644
--- a/desktop/public/sdk/esm/esengine.d.ts
+++ b/desktop/public/sdk/esm/esengine.d.ts
@@ -27,7 +27,12 @@ interface Quat {
y: number;
z: number;
}
-type Color = Vec4;
+interface Color {
+ r: number;
+ g: number;
+ b: number;
+ a: number;
+}
declare const vec2: (x?: number, y?: number) => Vec2;
declare const vec3: (x?: number, y?: number, z?: number) => Vec3;
declare const vec4: (x?: number, y?: number, z?: number, w?: number) => Vec4;
@@ -121,7 +126,7 @@ interface WorldTransformData {
}
interface SpriteData {
texture: number;
- color: Vec4;
+ color: Color;
size: Vec2;
uvOffset: Vec2;
uvScale: Vec2;
@@ -146,7 +151,7 @@ interface CanvasData {
pixelsPerUnit: number;
scaleMode: number;
matchWidthOrHeight: number;
- backgroundColor: Vec4;
+ backgroundColor: Color;
}
interface VelocityData {
linear: Vec3;
@@ -168,7 +173,7 @@ interface SpineAnimationData {
playing: boolean;
flipX: boolean;
flipY: boolean;
- color: Vec4;
+ color: Color;
layer: number;
skeletonScale: number;
material: number;
@@ -704,7 +709,7 @@ interface TextData {
content: string;
fontFamily: string;
fontSize: number;
- color: Vec4;
+ color: Color;
align: TextAlign;
verticalAlign: TextVerticalAlign;
wordWrap: boolean;
diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.js
index 8ca86f0b0..9ea247c13 100644
--- a/desktop/public/sdk/esm/esengine.js
+++ b/desktop/public/sdk/esm/esengine.js
@@ -1,2 +1,2 @@
-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function 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}),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){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 s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}}),n.addEventListener("touchmove",t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.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,s=1)=>({x:e,y:t,z:n,w:s}),w=(e=1,t=1,n=1,s=1)=>({x:e,y:t,z:n,w:s}),x=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});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}),S=v("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),P=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(),s=n.get(e);if(s)return s;const r=A(e,t);return n.set(e,r),z(e,t,!1),r}function U(e){const t=M(),n=t.get(e);if(n)return n;const s=A(e,{});return t.set(e,s),z(e,{},!0),s}function F(e){return M().get(e)}function B(){M().clear()}function z(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function I(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function k(e){return!0===e._builtin}const D=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}}),L=I("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),$=I("Sprite",{texture:_,color:{x:1,y:1,z:1,w: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=I("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0}),W=I("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),O=I("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),N=I("Parent",{entity:0}),V=I("Children",{entities:[]}),X=I("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{x:1,y:1,z:1,w:1},layer:0,skeletonScale:1,material:0}),j={LocalTransform:D,WorldTransform:L,Sprite:$,Camera:H,Canvas:W,Velocity:O,Parent:N,Children:V,SpineAnimation:X,RigidBody:b,BoxCollider:S,CircleCollider:P,CapsuleCollider:C};function G(e){const t=j[e];if(t)return{...t._default};const n=F(e);return n?{...n._default}:null}let Y=0;function K(e,t){const n=++Y;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function q(e){return{_type:"res",_resource:e}}function J(e){return{_type:"res_mut",_resource:e}}class Q{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 Z{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 Q(this.get(e),t=>this.set(e,t))}}const ee=K({delta:0,elapsed:0,frameCount:0},"Time");function te(e){return{_type:"mut",_component:e}}function ne(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function se(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{ne(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class re{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return ne(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:s}=this.descriptor_,r=e.map(e=>this.getActualComponent(e)),i=[...r,...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 s)if(this.world_.has(e,t)){n=!0;break}if(n)continue;const i=r.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:r[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 ie(){return{_type:"commands"}}class oe{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=k(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 ae{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new oe(this,null);return this.spawned_.push(e),e}entity(e){return new oe(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 ce;!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"}(ce||(ce={}));let le=0;function ue(e,t,n){const s=++le;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function he(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function de(e){he().push({schedule:ce.Update,system:e})}function fe(e){he().push({schedule:ce.Startup,system:e})}function pe(e,t){he().push({schedule:e,system:t})}class _e{constructor(e,t){this.world_=e,this.resources_=t}run(e){const t=e._params.map(e=>this.resolveParam(e));e._fn(...t);for(const e of t)e instanceof ae&&e.flush()}resolveParam(e){switch(e._type){case"query":return new re(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new ae(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class me{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 ge=K(new me,"Input");class ye{constructor(e){this.target_=e??null}build(e){const n=new me;e.insertResource(ge,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(ce.First,ue([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const we=new ye;class xe{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 k(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return k(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return k(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){k(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,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();const t=[];for(const n of this.entities_){let s=!0;for(const t of e)if(!this.has(n,t)){s=!1;break}s&&t.push(n)}return t}}var ve,be,Se;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(ve||(ve={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(be||(be={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Se||(Se={}));const Pe=R("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:ve.Left,verticalAlign:be.Top,wordWrap:!0,overflow:Se.Visible,lineHeight:1.2,dirty:!0});class Ce{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===Se.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.x),m=Math.round(255*e.color.y),g=Math.round(255*e.color.z),y=e.color.w;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===Se.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 be.Top:x=u;break;case be.Middle:x=(p-w)/2;break;case be.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 ve.Left:s=u;break;case ve.Center:s=f/2;break;case ve.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=l}r&&e.overflow===Se.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)}}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 ve.Left:return"left";case ve.Center:return"center";case ve.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const Ee=R("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class Te{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Ce(t),s=e.world;e.addSystemToSchedule(ce.PreUpdate,ue([],()=>{const e=s.getEntitiesWithComponents([Pe]);for(const t of e){const e=s.get(t,Pe);if(!e.dirty)continue;s.has(t,$)||s.insert(t,$,{texture:_,size:{x:0,y:0},color:{x:1,y:1,z:1,w:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const r=s.has(t,Ee)?s.get(t,Ee):null,i=n.renderForEntity(t,e,r),o=s.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},s.insert(t,$,o),e.dirty=!1}}))}}const Ae=new Te;var Me;function Re(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"}(Me||(Me={}));let Ue=null,Fe=null,Be=1;const ze=new Map;function Ie(e){Ue=e,Fe=e.getResourceManager(),Ne()}function ke(){0!==He&&Ue&&(Ue._free(He),He=0),ze.clear(),Be=1,$e=!1,Fe=null,Ue=null}function De(){if(!Fe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Fe}const Le={createShader:(e,t)=>De().createShader(e,t),releaseShader(e){e>0&&De().releaseShader(e)},create(e){const t=Be++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Me.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return ze.set(t,n),t},get:e=>ze.get(e),setUniform(e,t,n){const s=ze.get(e);s&&s.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??Me.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,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"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??Me.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=ze.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Be++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return ze.set(n,s),n},toAssetData(e,t){const n=ze.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=ze.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let $e=!1,He=0;const We=4096;function Oe(e){const t=(0===He&&Ue&&(He=Ue._malloc(We)),He);if(0===t||!Ue)return{ptr:0,count:0};let n=0,s=0;const r=Ue.HEAPU8,i=Ue.HEAPU32,o=Ue.HEAPF32;for(const[a,c]of e){if(n+128>We)break;const e=(new TextEncoder).encode(a),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 Ne(){if(!Ue||$e)return;Ue.materialDataProvider=(e,t,n,s,r)=>{const i=ze.get(e);if(!i)return Ue.HEAPU32[t>>2]=0,Ue.HEAPU32[n>>2]=0,Ue.HEAPU32[s>>2]=0,void(Ue.HEAPU32[r>>2]=0);Ue.HEAPU32[t>>2]=i.shader,Ue.HEAPU32[n>>2]=i.blendMode;const{ptr:o,count:a}=Oe(i.uniforms);Ue.HEAPU32[s>>2]=o,Ue.HEAPU32[r>>2]=a},$e=!0}const Ve={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 Xe{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&&(Le.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Le.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:Le.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 je(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();n.set(s.id,t);for(const n of s.components)Ye(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 Ge(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);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("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}}Ye(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 Ye(e,t,n){const s=n.data;switch(n.type){case"LocalTransform":e.insert(t,D,s);break;case"Sprite":e.insert(t,$,s);break;case"Camera":e.insert(t,H,s);break;case"Canvas":e.insert(t,W,s);break;case"Text":e.insert(t,Pe,s);break;case"SpineAnimation":e.insert(t,X,s);break;case"UIRect":e.insert(t,Ee,s);break;case"RigidBody":e.insert(t,b,s);break;case"BoxCollider":e.insert(t,S,s);break;case"CircleCollider":e.insert(t,P,s);break;case"CapsuleCollider":e.insert(t,C,s);break;default:{const r=F(n.type);r?e.insert(t,r,s):console.warn(`Unknown component type: ${n.type}`);break}}}function Ke(e,t){const n=e.getEntitiesWithComponents([H]);for(const s of n){const n=e.get(s,H);n&&(n.aspectRatio=t,e.insert(s,H,n))}}class qe{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 Je{constructor(e){this.textureCache_=new qe,this.shaderCache_=new qe,this.jsonCache_=new qe,this.textCache_=new qe,this.binaryCache_=new qe,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 Xe(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);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 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 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 Ge(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 Le.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 Qe=K(null,"Assets");class Ze{build(e){const t=e.wasmModule;t?e.insertResource(Qe,new Je(t)):console.warn("AssetPlugin: No WASM module available")}}const et=new Ze;function tt(e,t){const n=e.getResource(Qe);n&&n.registerEmbeddedAssets(t)}let nt=null,st=0,rt=0,it=0;const ot=new Float32Array(256);function at(e){nt=e,st=nt._malloc(64),rt=nt._malloc(64),it=nt._malloc(1024)}function ct(){nt&&(st&&(nt._free(st),st=0),rt&&(nt._free(rt),rt=0),it&&(nt._free(it),it=0)),nt=null}function lt(){if(!nt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return nt}const ut={x:1,y:1,z:1,w:1},ht={begin(e){const t=lt();t.HEAPF32.set(e,st/4),t.draw_begin(st)},end(){lt().draw_end()},line(e,t,n,s=1){lt().draw_line(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,s)},rect(e,t,n,s=!0){lt().draw_rect(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,s)},rectOutline(e,t,n,s=1){lt().draw_rectOutline(e.x,e.y,t.x,t.y,n.x,n.y,n.z,n.w,s)},circle(e,t,n,s=!0,r=32){lt().draw_circle(e.x,e.y,t,n.x,n.y,n.z,n.w,s,r)},circleOutline(e,t,n,s=1,r=32){lt().draw_circleOutline(e.x,e.y,t,n.x,n.y,n.z,n.w,s,r)},texture(e,t,n,s=ut){lt().draw_texture(e.x,e.y,t.x,t.y,n,s.x,s.y,s.z,s.w)},textureRotated(e,t,n,s,r=ut){lt().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.x,r.y,r.z,r.w)},setLayer(e){lt().draw_setLayer(e)},setDepth(e){lt().draw_setDepth(e)},getDrawCallCount:()=>nt?nt.draw_getDrawCallCount():0,getPrimitiveCount:()=>nt?nt.draw_getPrimitiveCount():0,setBlendMode(e){lt().draw_setBlendMode(e)},setDepthTest(e){lt().draw_setDepthTest(e)},drawMesh(e,t,n){const s=lt();s.HEAPF32.set(n,rt/4),s.draw_mesh(e,t,rt)},drawMeshWithMaterial(e,t,n){const s=lt(),r=Le.get(t);if(!r)return;if(ht.setBlendMode(r.blendMode),ht.setDepthTest(r.depthTest),0===r.uniforms.size)return void ht.drawMesh(e,r.shader,n);s.HEAPF32.set(n,rt/4);let i=0,o=0;for(const[e,t]of r.uniforms){const n=ft(e);if(!(n<0)){if(Re(t))ot[i++]=10,ot[i++]=n,ot[i++]=t.slot??o++,ot[i++]=t.textureId;else if("number"==typeof t)ot[i++]=1,ot[i++]=n,ot[i++]=t;else if(Array.isArray(t)){ot[i++]=t.length,ot[i++]=n;for(let e=0;e<t.length;e++)ot[i++]=t[e]}else"w"in t?(ot[i++]=4,ot[i++]=n,ot[i++]=t.x,ot[i++]=t.y,ot[i++]=t.z,ot[i++]=t.w):"z"in t?(ot[i++]=3,ot[i++]=n,ot[i++]=t.x,ot[i++]=t.y,ot[i++]=t.z):(ot[i++]=2,ot[i++]=n,ot[i++]=t.x,ot[i++]=t.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==i?(s.HEAPF32.set(ot.subarray(0,i),it/4),s.draw_meshWithUniforms(e,r.shader,rt,it,i)):s.draw_mesh(e,r.shader,rt)}},dt={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 ft(e){return dt[e]??-1}var pt;!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"}(pt||(pt={}));let _t=null,mt=0,gt=0,yt=0;function wt(e){_t=e,mt=_t._malloc(262144),gt=_t._malloc(65536),yt=_t._malloc(256)}function xt(){_t&&(mt&&_t._free(mt),gt&&_t._free(gt),yt&&_t._free(yt),mt=0,gt=0,yt=0),_t=null}function vt(){if(!_t)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return _t}const bt={create(e){const t=vt(),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,mt/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,yt,r).set(i),t.geometry_init(n,mt,s,yt,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,gt,s).set(e.indices),t.geometry_setIndices16(n,gt,s)}else{new Uint32Array(t.HEAPU8.buffer,gt,s).set(e.indices),t.geometry_setIndices32(n,gt,s)}}return n},updateVertices(e,t,n=0){const s=vt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,mt/4),s.geometry_updateVertices(e,mt,r,n)},release(e){e>0&&vt().geometry_release(e)},isValid:e=>!(!_t||e<=0)&&_t.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return bt.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:pt.Float2},{name:"a_texCoord",type:pt.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 bt.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:pt.Float2},{name:"a_texCoord",type:pt.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 bt.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:pt.Float2},{name:"a_texCoord",type:pt.Float2}],indices:new Uint16Array(o)})}};let St=null;function Pt(e){St=e}function Ct(){St&&Tt.isInitialized()&&Tt.shutdown(),St=null}function Et(){if(!St)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return St}const Tt={init:(e,t)=>Et().postprocess_init(e,t),shutdown(){Et().postprocess_shutdown()},resize(e,t){Et().postprocess_resize(e,t)},addPass:(e,t)=>Et().postprocess_addPass(e,t),removePass(e){Et().postprocess_removePass(e)},setEnabled(e,t){Et().postprocess_setPassEnabled(e,t)},isEnabled:e=>Et().postprocess_isPassEnabled(e),setUniform(e,t,n){Et().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Et().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Et().postprocess_begin()},end(){Et().postprocess_end()},getPassCount:()=>Et().postprocess_getPassCount(),isInitialized:()=>!!St&&St.postprocess_isInitialized(),setBypass(e){Et().postprocess_setBypass(e)},isBypassed:()=>!St||St.postprocess_isBypassed(),createBlur:()=>Le.createShader(At,"#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:()=>Le.createShader(At,"#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:()=>Le.createShader(At,"#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:()=>Le.createShader(At,"#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")},At="#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 Mt;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Mt||(Mt={}));let Rt=null,Ut=0;function Ft(e){Rt=e,Ut=Rt._malloc(64)}function Bt(){Rt&&Ut&&(Rt._free(Ut),Ut=0),Rt=null}const zt={init(e,t){Rt?.renderer_init(e,t)},resize(e,t){Rt?.renderer_resize(e,t)},begin(e,t){Rt&&Ut&&(Rt.HEAPF32.set(e,Ut/4),Rt.renderer_begin(Ut,t??0))},flush(){Rt?.renderer_flush()},end(){Rt?.renderer_end()},submitSprites(e){Rt&&Rt.renderer_submitSprites(e._cpp)},submitSpine(e){Rt&&Rt.renderer_submitSpine?.(e._cpp)},setStage(e){Rt?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Rt?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Rt?.renderer_releaseTarget(e)},getTargetTexture:e=>Rt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Rt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Rt?.renderer_setClearColor?.(e,t,n,s)},getStats:()=>Rt?{drawCalls:Rt.renderer_getDrawCalls(),triangles:Rt.renderer_getTriangles(),sprites:Rt.renderer_getSprites(),spine:Rt.renderer_getSpine?.()??0,meshes:Rt.renderer_getMeshes(),culled:Rt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let It=null;function kt(e){It=e}function Dt(){It=null}const Lt={enable(){It?.gl_enableErrorCheck(!0)},disable(){It?.gl_enableErrorCheck(!1)},check:e=>It?.gl_checkErrors(e)??0,diagnose(){It?.renderer_diagnose()}},$t=new Map;function Ht(e,t){$t.set(e,t)}function Wt(e){$t.delete(e)}function Ot(){$t.clear()}class Nt{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:i}=e;zt.resize(s,r),Tt.isInitialized()&&Tt.getPassCount()>0&&!Tt.isBypassed()&&Tt.resize(s,r),zt.begin(n),zt.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,i):zt.submitSpine(t),zt.flush();const o=$t;if(o.size>0){ht.begin(n);const e=[];for(const[t,n]of o.entries())try{n(i)}catch(n){console.error(`[CustomDraw] callback '${t}' error:`,n),e.push(t)}ht.end();for(const t of e)Wt(t)}zt.end()}}class Vt{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(ce.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ce.FixedPreUpdate),this.runSchedule(ce.FixedUpdate),this.runSchedule(ce.FixedPostUpdate);this.runSchedule(ce.PreUpdate),this.runSchedule(ce.Update),this.runSchedule(ce.PostUpdate),this.runSchedule(ce.Last),requestAnimationFrame(this.mainLoop)},this.world_=new xe,this.resources_=new Z;for(const e of Object.values(ce))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Vt}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(ce.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(ce.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_}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 _e(this.world_,this.resources_),this.resources_.insert(ee,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(ce.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Dt(),Bt(),Ct(),xt(),ke(),ct()}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(ee),n={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(ee,n)}}function Xt(e,t){const n=Vt.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),at(e),Ie(e),wt(e),Pt(e),Ft(e),kt(e);const r=new Nt;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:e,height:t}=o(),n=s.entityCount(),a=Yt(s,n+1e3);if(a){const e=a.backgroundColor;zt.setClearColor(e.x,e.y,e.z,e.w)}const c=function(e,t,n){const s=e.entityCount(),r=s+1e3;for(let s=0;s<r;s++){if(!e.valid(s)||!e.hasCamera(s)||!e.hasLocalTransform(s))continue;const i=e.getCamera(s);if(!i.isActive)continue;const o=e.getLocalTransform(s),a=t/n;let c;if(1===i.projectionType){let t=i.orthoSize;const n=Yt(e,r);if(n){t=Kt(n.designResolution.y/2,n.designResolution.x/n.designResolution.y,a,n.scaleMode,n.matchWidthOrHeight)}const s=t*a;c=qt(-s,s,-t,t,-i.farPlane,i.farPlane)}else c=Jt(i.fov*Math.PI/180,a,i.nearPlane,i.farPlane);return Zt(c,Qt(o.position.x,o.position.y,o.position.z))}return Gt}(s,e,t),l=(d()-i)/1e3;r.render({registry:{_cpp:s},viewProjection:c,width:e,height:t,elapsed:l})}};return n.addSystemToSchedule(ce.Last,a),n.addPlugin(et),n.addPlugin(we),n.addPlugin(Ae),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 Gt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Yt(e,t){for(let n=0;n<t;n++){if(!e.valid(n)||!e.hasCanvas(n))continue;return e.getCanvas(n)}return null}function Kt(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 qt(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 Jt(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 Qt(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 Zt(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 en(e,t){if(t)return t();return(0,(await import(e)).default)()}const tn=K({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents");function nn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function sn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class rn{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(tn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=en(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=e.world;e.addSystemToSchedule(ce.PostUpdate,ue([q(ee)],i=>{const o=r.getEntitiesWithComponents([b,D,L]),a=new Set;for(const i of o){a.add(i);const o=r.get(i,b),c=r.get(i,L);if(t.has(i)){const e=n.get(i);!e||e.bodyType===o.bodyType&&e.gravityScale===o.gravityScale&&e.linearDamping===o.linearDamping&&e.angularDamping===o.angularDamping&&e.fixedRotation===o.fixedRotation&&e.bullet===o.bullet||(s._physics_updateBodyProperties(i,o.bodyType,o.gravityScale,o.linearDamping,o.angularDamping,o.fixedRotation?1:0,o.bullet?1:0),e.bodyType=o.bodyType,e.gravityScale=o.gravityScale,e.linearDamping=o.linearDamping,e.angularDamping=o.angularDamping,e.fixedRotation=o.fixedRotation,e.bullet=o.bullet)}else{if(!o.enabled)continue;const r=nn(c.rotation);s._physics_createBody(i,o.bodyType,c.position.x,c.position.y,r,o.gravityScale,o.linearDamping,o.angularDamping,o.fixedRotation?1:0,o.bullet?1:0),on(e,s,i),t.add(i),n.set(i,{bodyType:o.bodyType,gravityScale:o.gravityScale,linearDamping:o.linearDamping,angularDamping:o.angularDamping,fixedRotation:o.fixedRotation,bullet:o.bullet})}if(o.bodyType===E.Kinematic){const e=nn(c.rotation);s._physics_setBodyTransform(i,c.position.x,c.position.y,e)}}for(const e of t)a.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(i.delta),function(e,t){const n=t._physics_getDynamicBodyCount();if(0===n)return;const s=t._physics_getDynamicBodyTransforms(),r=s>>2;for(let s=0;s<n;s++){const n=r+4*s,i=t.HEAPU32[n],o=t.HEAPF32[n+1],a=t.HEAPF32[n+2],c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const l=e.world.get(i,D);if(!l)continue;let u=o,h=a,d=c;if(e.world.has(i,N)){const t=e.world.get(i,N);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,L)){const n=e.world.get(t.entity,L),s=nn(n.rotation),r=o-n.position.x,i=a-n.position.y,l=Math.cos(-s),f=Math.sin(-s);u=(r*l-i*f)/(0!==n.scale.x?n.scale.x:1),h=(r*f+i*l)/(0!==n.scale.y?n.scale.y:1),d=c-s}}l.position.x=u,l.position.y=h;const f=sn(d);l.rotation.w=f.w,l.rotation.x=f.x,l.rotation.y=f.y,l.rotation.z=f.z,e.world.insert(i,D,l)}}(e,s),function(e,t){t._physics_collectEvents();const n=[],s=t._physics_getCollisionEnterCount();if(s>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let r=0;r<s;r++){const s=e+6*r;n.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],contactY:t.HEAPF32[s+5]})}}const r=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;r.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const o=[],a=t._physics_getSensorEnterCount();if(a>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<a;n++){const s=e+2*n;o.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],l=t._physics_getSensorExitCount();if(l>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(tn,{collisionEnters:n,collisionExits:r,sensorEnters:o,sensorExits:c})}(e,s)},{name:"PhysicsSystem"})),e.__physicsModule=s});e.__physicsInitPromise=s}}function on(e,t,n){const s=e.world;if(s.has(n,S)){const e=s.get(n,S);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,P)){const e=s.get(n,P);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,C)){const e=s.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 an{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}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 cn(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 ln(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,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 hn(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]=cn(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=ln(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=cn(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 rn("",{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=Le.createShader(e.vertexSource,e.fragmentSource),s[i]=o),n[r]=Le.createFromAsset(e,o)}catch{n[r]=0}}return n}(n,s),h=je(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,$);r&&(r.texture=n[s.data.texture]||0,e.insert(t,$,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,$);n&&(n.material=r,e.insert(t,$,n))}else if("SpineAnimation"===s.type){const n=e.get(t,X);n&&(n.material=r,e.insert(t,X,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,X)?l.get(i,X):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&s.update(o,c*h);let d=0;if(l.has(i,L)){const e=un(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=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 dn{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 fn{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 dn(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.__spineInitPromise;if(r){s=(await r).controller.raw}await hn(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([H]);for(const s of n){if(e.get(s,H).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const s=e.getEntitiesWithComponents([W]);for(const r of s){const s=e.get(r,W);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};e.insert(r,H,o)}}}const pn={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=zt.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:zt.getTargetTexture(n),width:e.width,height:e.height}},release(e){zt.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(zt.releaseRenderTarget(e._handle),pn.create({width:t,height:n,depth:!0})),begin(e,t){zt.begin(t,e._handle)},end(){zt.end()},getDepthTexture:e=>zt.getTargetDepthTexture(e._handle)};let _n=!1;function mn(e){_n=e}function gn(){return _n}function yn(){return!_n}var wn;e=wn=f,console.log(`[ESEngine] Platform: ${wn.name}`);export{Vt as App,Ze as AssetPlugin,Je as AssetServer,Qe as Assets,qe as AsyncCache,Me as BlendMode,E as BodyType,S as BoxCollider,H as Camera,W as Canvas,C as CapsuleCollider,V as Children,P as CircleCollider,ie as Commands,ae as CommandsInstance,pt as DataType,ht as Draw,oe as EntityCommands,Lt as GLDebug,bt as Geometry,p as INVALID_ENTITY,_ as INVALID_TEXTURE,ge as Input,ye as InputPlugin,me as InputState,D as LocalTransform,Le as Material,Xe as MaterialLoader,te as Mut,N as Parent,an as Physics,tn as PhysicsEvents,rn as PhysicsPlugin,Tt as PostProcess,fn as PreviewPlugin,se as Query,re as QueryInstance,Nt as RenderPipeline,Mt as RenderStage,pn as RenderTexture,zt as Renderer,q as Res,J as ResMut,b as RigidBody,ce as Schedule,Ve as ShaderSources,X as SpineAnimation,$ as Sprite,_e as SystemRunner,Pe as Text,ve as TextAlign,Se as TextOverflow,Te as TextPlugin,Ce as TextRenderer,be as TextVerticalAlign,ee as Time,Ee as UIRect,O as Velocity,dn as WebAssetProvider,xe as World,L as WorldTransform,fe as addStartupSystem,de as addSystem,pe as addSystemToSchedule,et as assetPlugin,Ot as clearDrawCallbacks,B as clearUserComponents,w as color,Xt as createWebApp,R as defineComponent,K as defineResource,ue as defineSystem,U as defineTag,jt as flushPendingSystems,G as getComponentDefaults,t as getPlatform,s as getPlatformType,F as getUserComponent,at as initDrawAPI,kt as initGLDebugAPI,wt as initGeometryAPI,Ie as initMaterialAPI,Pt as initPostProcessAPI,Ft as initRendererAPI,we as inputPlugin,k as isBuiltinComponent,gn as isEditor,n as isPlatformInitialized,yn as isRuntime,Re as isTextureRef,r as isWeChat,i as isWeb,Ye as loadComponent,en as loadPhysicsModule,hn as loadRuntimeScene,je as loadSceneData,Ge as loadSceneWithAssets,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,x as quat,Ht as registerDrawCallback,tt as registerEmbeddedAssets,Ne as registerMaterialCallback,mn as setEditorMode,ct as shutdownDrawAPI,Dt as shutdownGLDebugAPI,xt as shutdownGeometryAPI,ke as shutdownMaterialAPI,Ct as shutdownPostProcessAPI,Bt as shutdownRendererAPI,Ae as textPlugin,Wt as unregisterDrawCallback,Ke 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"}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){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 s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}}),n.addEventListener("touchmove",t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.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,s=1)=>({x:e,y:t,z:n,w:s}),w=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),x=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});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}),S=v("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),P=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(),s=n.get(e);if(s)return s;const r=A(e,t);return n.set(e,r),I(e,t,!1),r}function U(e){const t=M(),n=t.get(e);if(n)return n;const s=A(e,{});return t.set(e,s),I(e,{},!0),s}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 D(e){return!0===e._builtin}const z=k("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),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}),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:[]}),X=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}),j={LocalTransform:z,WorldTransform:L,Sprite:$,Camera:H,Canvas:W,Velocity:O,Parent:N,Children:V,SpineAnimation:X,RigidBody:b,BoxCollider:S,CircleCollider:P,CapsuleCollider:C};function G(e){const t=j[e];if(t)return{...t._default};const n=F(e);return n?{...n._default}:null}let Y=0;function K(e,t){const n=++Y;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function q(e){return{_type:"res",_resource:e}}function J(e){return{_type:"res_mut",_resource:e}}class Q{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 Z{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 Q(this.get(e),t=>this.set(e,t))}}const ee=K({delta:0,elapsed:0,frameCount:0},"Time");function te(e){return{_type:"mut",_component:e}}function ne(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function se(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{ne(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class re{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return ne(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:s}=this.descriptor_,r=e.map(e=>this.getActualComponent(e)),i=[...r,...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 s)if(this.world_.has(e,t)){n=!0;break}if(n)continue;const i=r.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:r[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 ie(){return{_type:"commands"}}class oe{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=D(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class ae{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new oe(this,null);return this.spawned_.push(e),e}entity(e){return new oe(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 ce;!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"}(ce||(ce={}));let le=0;function ue(e,t,n){const s=++le;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function he(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function de(e){he().push({schedule:ce.Update,system:e})}function fe(e){he().push({schedule:ce.Startup,system:e})}function pe(e,t){he().push({schedule:e,system:t})}class _e{constructor(e,t){this.world_=e,this.resources_=t}run(e){const t=e._params.map(e=>this.resolveParam(e));e._fn(...t);for(const e of t)e instanceof ae&&e.flush()}resolveParam(e){switch(e._type){case"query":return new re(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new ae(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class me{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 ge=K(new me,"Input");class ye{constructor(e){this.target_=e??null}build(e){const n=new me;e.insertResource(ge,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(ce.First,ue([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const we=new ye;class xe{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 D(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return D(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return D(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){D(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const s={...t._default,...n};if(this.cppRegistry_){const n=`add${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e,s)}return s}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const n=`get${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const n=`has${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const n=`remove${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e)}insertScript(e,t,n){const s=t.create(n);return this.getStorage(t).set(e,s),s}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=[];for(const n of this.entities_){let s=!0;for(const t of e)if(!this.has(n,t)){s=!1;break}s&&t.push(n)}return t}}var ve,be,Se;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(ve||(ve={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(be||(be={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Se||(Se={}));const Pe=R("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:ve.Left,verticalAlign:be.Top,wordWrap:!0,overflow:Se.Visible,lineHeight:1.2,dirty:!0});class Ce{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===Se.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===Se.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 be.Top:x=u;break;case be.Middle:x=(p-w)/2;break;case be.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 ve.Left:s=u;break;case ve.Center:s=f/2;break;case ve.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=l}r&&e.overflow===Se.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)}}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 ve.Left:return"left";case ve.Center:return"center";case ve.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const Ee=R("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class Te{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Ce(t),s=e.world;e.addSystemToSchedule(ce.PreUpdate,ue([],()=>{const e=s.getEntitiesWithComponents([Pe]);for(const t of e){const e=s.get(t,Pe);if(!e.dirty)continue;s.has(t,$)||s.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 r=s.has(t,Ee)?s.get(t,Ee):null,i=n.renderForEntity(t,e,r),o=s.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},s.insert(t,$,o),e.dirty=!1}}))}}const Ae=new Te;var Me;function Re(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"}(Me||(Me={}));let Ue=null,Fe=null,Be=1;const Ie=new Map;function ke(e){Ue=e,Fe=e.getResourceManager(),Ne()}function De(){0!==He&&Ue&&(Ue._free(He),He=0),Ie.clear(),Be=1,$e=!1,Fe=null,Ue=null}function ze(){if(!Fe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Fe}const Le={createShader:(e,t)=>ze().createShader(e,t),releaseShader(e){e>0&&ze().releaseShader(e)},create(e){const t=Be++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Me.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return Ie.set(t,n),t},get:e=>Ie.get(e),setUniform(e,t,n){const s=Ie.get(e);s&&s.uniforms.set(t,n)},getUniform(e,t){const n=Ie.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Ie.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Ie.get(e);return t?.blendMode??Me.Normal},setDepthTest(e,t){const n=Ie.get(e);n&&(n.depthTest=t)},getShader(e){const t=Ie.get(e);return t?.shader??0},release(e){Ie.delete(e)},isValid:e=>Ie.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??Me.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ie.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Be++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Ie.set(n,s),n},toAssetData(e,t){const n=Ie.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=Ie.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let $e=!1,He=0;const We=4096;function Oe(e){const t=(0===He&&Ue&&(He=Ue._malloc(We)),He);if(0===t||!Ue)return{ptr:0,count:0};let n=0,s=0;const r=Ue.HEAPU8,i=Ue.HEAPU32,o=Ue.HEAPF32;for(const[a,c]of e){if(n+128>We)break;const e=(new TextEncoder).encode(a),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 Ne(){if(!Ue||$e)return;Ue.materialDataProvider=(e,t,n,s,r)=>{const i=Ie.get(e);if(!i)return Ue.HEAPU32[t>>2]=0,Ue.HEAPU32[n>>2]=0,Ue.HEAPU32[s>>2]=0,void(Ue.HEAPU32[r>>2]=0);Ue.HEAPU32[t>>2]=i.shader,Ue.HEAPU32[n>>2]=i.blendMode;const{ptr:o,count:a}=Oe(i.uniforms);Ue.HEAPU32[s>>2]=o,Ue.HEAPU32[r>>2]=a},$e=!0}const Ve={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 Xe{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&&(Le.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Le.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:Le.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 je(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();n.set(s.id,t);for(const n of s.components)Ye(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 Ge(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);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("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}}Ye(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 Ye(e,t,n){const s=n.data;switch(n.type){case"LocalTransform":e.insert(t,z,s);break;case"Sprite":e.insert(t,$,s);break;case"Camera":e.insert(t,H,s);break;case"Canvas":e.insert(t,W,s);break;case"Text":e.insert(t,Pe,s);break;case"SpineAnimation":e.insert(t,X,s);break;case"UIRect":e.insert(t,Ee,s);break;case"RigidBody":e.insert(t,b,s);break;case"BoxCollider":e.insert(t,S,s);break;case"CircleCollider":e.insert(t,P,s);break;case"CapsuleCollider":e.insert(t,C,s);break;default:{const r=F(n.type);r?e.insert(t,r,s):console.warn(`Unknown component type: ${n.type}`);break}}}function Ke(e,t){const n=e.getEntitiesWithComponents([H]);for(const s of n){const n=e.get(s,H);n&&(n.aspectRatio=t,e.insert(s,H,n))}}class qe{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 Je{constructor(e){this.textureCache_=new qe,this.shaderCache_=new qe,this.jsonCache_=new qe,this.textCache_=new qe,this.binaryCache_=new qe,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 Xe(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);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 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 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 Ge(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 Le.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 Qe=K(null,"Assets");class Ze{build(e){const t=e.wasmModule;t?e.insertResource(Qe,new Je(t)):console.warn("AssetPlugin: No WASM module available")}}const et=new Ze;function tt(e,t){const n=e.getResource(Qe);n&&n.registerEmbeddedAssets(t)}let nt=null,st=0,rt=0,it=0;const ot=new Float32Array(256);function at(e){nt=e,st=nt._malloc(64),rt=nt._malloc(64),it=nt._malloc(1024)}function ct(){nt&&(st&&(nt._free(st),st=0),rt&&(nt._free(rt),rt=0),it&&(nt._free(it),it=0)),nt=null}function lt(){if(!nt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return nt}const ut={r:1,g:1,b:1,a:1},ht={begin(e){const t=lt();t.HEAPF32.set(e,st/4),t.draw_begin(st)},end(){lt().draw_end()},line(e,t,n,s=1){lt().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){lt().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){lt().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){lt().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){lt().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=ut){lt().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=ut){lt().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){lt().draw_setLayer(e)},setDepth(e){lt().draw_setDepth(e)},getDrawCallCount:()=>nt?nt.draw_getDrawCallCount():0,getPrimitiveCount:()=>nt?nt.draw_getPrimitiveCount():0,setBlendMode(e){lt().draw_setBlendMode(e)},setDepthTest(e){lt().draw_setDepthTest(e)},drawMesh(e,t,n){const s=lt();s.HEAPF32.set(n,rt/4),s.draw_mesh(e,t,rt)},drawMeshWithMaterial(e,t,n){const s=lt(),r=Le.get(t);if(!r)return;if(ht.setBlendMode(r.blendMode),ht.setDepthTest(r.depthTest),0===r.uniforms.size)return void ht.drawMesh(e,r.shader,n);s.HEAPF32.set(n,rt/4);let i=0,o=0;for(const[e,t]of r.uniforms){const n=ft(e);if(!(n<0)){if(Re(t))ot[i++]=10,ot[i++]=n,ot[i++]=t.slot??o++,ot[i++]=t.textureId;else if("number"==typeof t)ot[i++]=1,ot[i++]=n,ot[i++]=t;else if(Array.isArray(t)){ot[i++]=t.length,ot[i++]=n;for(let e=0;e<t.length;e++)ot[i++]=t[e]}else"w"in t?(ot[i++]=4,ot[i++]=n,ot[i++]=t.x,ot[i++]=t.y,ot[i++]=t.z,ot[i++]=t.w):"z"in t?(ot[i++]=3,ot[i++]=n,ot[i++]=t.x,ot[i++]=t.y,ot[i++]=t.z):(ot[i++]=2,ot[i++]=n,ot[i++]=t.x,ot[i++]=t.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==i?(s.HEAPF32.set(ot.subarray(0,i),it/4),s.draw_meshWithUniforms(e,r.shader,rt,it,i)):s.draw_mesh(e,r.shader,rt)}},dt={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 ft(e){return dt[e]??-1}var pt;!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"}(pt||(pt={}));let _t=null,mt=0,gt=0,yt=0;function wt(e){_t=e,mt=_t._malloc(262144),gt=_t._malloc(65536),yt=_t._malloc(256)}function xt(){_t&&(mt&&_t._free(mt),gt&&_t._free(gt),yt&&_t._free(yt),mt=0,gt=0,yt=0),_t=null}function vt(){if(!_t)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return _t}const bt={create(e){const t=vt(),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,mt/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,yt,r).set(i),t.geometry_init(n,mt,s,yt,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,gt,s).set(e.indices),t.geometry_setIndices16(n,gt,s)}else{new Uint32Array(t.HEAPU8.buffer,gt,s).set(e.indices),t.geometry_setIndices32(n,gt,s)}}return n},updateVertices(e,t,n=0){const s=vt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,mt/4),s.geometry_updateVertices(e,mt,r,n)},release(e){e>0&&vt().geometry_release(e)},isValid:e=>!(!_t||e<=0)&&_t.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return bt.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:pt.Float2},{name:"a_texCoord",type:pt.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 bt.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:pt.Float2},{name:"a_texCoord",type:pt.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 bt.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:pt.Float2},{name:"a_texCoord",type:pt.Float2}],indices:new Uint16Array(o)})}};let St=null;function Pt(e){St=e}function Ct(){St&&Tt.isInitialized()&&Tt.shutdown(),St=null}function Et(){if(!St)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return St}const Tt={init:(e,t)=>Et().postprocess_init(e,t),shutdown(){Et().postprocess_shutdown()},resize(e,t){Et().postprocess_resize(e,t)},addPass:(e,t)=>Et().postprocess_addPass(e,t),removePass(e){Et().postprocess_removePass(e)},setEnabled(e,t){Et().postprocess_setPassEnabled(e,t)},isEnabled:e=>Et().postprocess_isPassEnabled(e),setUniform(e,t,n){Et().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Et().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Et().postprocess_begin()},end(){Et().postprocess_end()},getPassCount:()=>Et().postprocess_getPassCount(),isInitialized:()=>!!St&&St.postprocess_isInitialized(),setBypass(e){Et().postprocess_setBypass(e)},isBypassed:()=>!St||St.postprocess_isBypassed(),createBlur:()=>Le.createShader(At,"#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:()=>Le.createShader(At,"#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:()=>Le.createShader(At,"#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:()=>Le.createShader(At,"#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")},At="#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 Mt;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Mt||(Mt={}));let Rt=null,Ut=0;function Ft(e){Rt=e,Ut=Rt._malloc(64)}function Bt(){Rt&&Ut&&(Rt._free(Ut),Ut=0),Rt=null}const It={init(e,t){Rt?.renderer_init(e,t)},resize(e,t){Rt?.renderer_resize(e,t)},begin(e,t){Rt&&Ut&&(Rt.HEAPF32.set(e,Ut/4),Rt.renderer_begin(Ut,t??0))},flush(){Rt?.renderer_flush()},end(){Rt?.renderer_end()},submitSprites(e){Rt&&Rt.renderer_submitSprites(e._cpp)},submitSpine(e){Rt&&Rt.renderer_submitSpine?.(e._cpp)},setStage(e){Rt?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Rt?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Rt?.renderer_releaseTarget(e)},getTargetTexture:e=>Rt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Rt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Rt?.renderer_setClearColor?.(e,t,n,s)},getStats:()=>Rt?{drawCalls:Rt.renderer_getDrawCalls(),triangles:Rt.renderer_getTriangles(),sprites:Rt.renderer_getSprites(),spine:Rt.renderer_getSpine?.()??0,meshes:Rt.renderer_getMeshes(),culled:Rt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let kt=null;function Dt(e){kt=e}function zt(){kt=null}const Lt={enable(){kt?.gl_enableErrorCheck(!0)},disable(){kt?.gl_enableErrorCheck(!1)},check:e=>kt?.gl_checkErrors(e)??0,diagnose(){kt?.renderer_diagnose()}},$t=new Map;function Ht(e,t){$t.set(e,t)}function Wt(e){$t.delete(e)}function Ot(){$t.clear()}class Nt{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:i}=e;It.resize(s,r),Tt.isInitialized()&&Tt.getPassCount()>0&&!Tt.isBypassed()&&Tt.resize(s,r),It.begin(n),It.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,i):It.submitSpine(t),It.flush();const o=$t;if(o.size>0){ht.begin(n);const e=[];for(const[t,n]of o.entries())try{n(i)}catch(n){console.error(`[CustomDraw] callback '${t}' error:`,n),e.push(t)}ht.end();for(const t of e)Wt(t)}It.end()}}class Vt{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(ce.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ce.FixedPreUpdate),this.runSchedule(ce.FixedUpdate),this.runSchedule(ce.FixedPostUpdate);this.runSchedule(ce.PreUpdate),this.runSchedule(ce.Update),this.runSchedule(ce.PostUpdate),this.runSchedule(ce.Last),requestAnimationFrame(this.mainLoop)},this.world_=new xe,this.resources_=new Z;for(const e of Object.values(ce))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Vt}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(ce.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(ce.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_}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 _e(this.world_,this.resources_),this.resources_.insert(ee,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(ce.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,zt(),Bt(),Ct(),xt(),De(),ct()}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(ee),n={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(ee,n)}}function Xt(e,t){const n=Vt.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),at(e),ke(e),wt(e),Pt(e),Ft(e),Dt(e);const r=new Nt;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:e,height:t}=o(),n=s.entityCount(),a=Yt(s,n+1e3);if(a){const e=a.backgroundColor;It.setClearColor(e.r,e.g,e.b,e.a)}const c=function(e,t,n){const s=e.entityCount(),r=s+1e3;for(let s=0;s<r;s++){if(!e.valid(s)||!e.hasCamera(s)||!e.hasLocalTransform(s))continue;const i=e.getCamera(s);if(!i.isActive)continue;const o=e.getLocalTransform(s),a=t/n;let c;if(1===i.projectionType){let t=i.orthoSize;const n=Yt(e,r);if(n){t=Kt(n.designResolution.y/2,n.designResolution.x/n.designResolution.y,a,n.scaleMode,n.matchWidthOrHeight)}const s=t*a;c=qt(-s,s,-t,t,-i.farPlane,i.farPlane)}else c=Jt(i.fov*Math.PI/180,a,i.nearPlane,i.farPlane);return Zt(c,Qt(o.position.x,o.position.y,o.position.z))}return Gt}(s,e,t),l=(d()-i)/1e3;r.render({registry:{_cpp:s},viewProjection:c,width:e,height:t,elapsed:l})}};return n.addSystemToSchedule(ce.Last,a),n.addPlugin(et),n.addPlugin(we),n.addPlugin(Ae),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 Gt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Yt(e,t){for(let n=0;n<t;n++){if(!e.valid(n)||!e.hasCanvas(n))continue;return e.getCanvas(n)}return null}function Kt(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 qt(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 Jt(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 Qt(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 Zt(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 en(e,t){if(t)return t();return(0,(await import(e)).default)()}const tn=K({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents");function nn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function sn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class rn{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(tn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=en(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=e.world;e.addSystemToSchedule(ce.PostUpdate,ue([q(ee)],i=>{const o=r.getEntitiesWithComponents([b,z,L]),a=new Set;for(const i of o){a.add(i);const o=r.get(i,b),c=r.get(i,L);if(t.has(i)){const e=n.get(i);!e||e.bodyType===o.bodyType&&e.gravityScale===o.gravityScale&&e.linearDamping===o.linearDamping&&e.angularDamping===o.angularDamping&&e.fixedRotation===o.fixedRotation&&e.bullet===o.bullet||(s._physics_updateBodyProperties(i,o.bodyType,o.gravityScale,o.linearDamping,o.angularDamping,o.fixedRotation?1:0,o.bullet?1:0),e.bodyType=o.bodyType,e.gravityScale=o.gravityScale,e.linearDamping=o.linearDamping,e.angularDamping=o.angularDamping,e.fixedRotation=o.fixedRotation,e.bullet=o.bullet)}else{if(!o.enabled)continue;const r=nn(c.rotation);s._physics_createBody(i,o.bodyType,c.position.x,c.position.y,r,o.gravityScale,o.linearDamping,o.angularDamping,o.fixedRotation?1:0,o.bullet?1:0),on(e,s,i),t.add(i),n.set(i,{bodyType:o.bodyType,gravityScale:o.gravityScale,linearDamping:o.linearDamping,angularDamping:o.angularDamping,fixedRotation:o.fixedRotation,bullet:o.bullet})}if(o.bodyType===E.Kinematic){const e=nn(c.rotation);s._physics_setBodyTransform(i,c.position.x,c.position.y,e)}}for(const e of t)a.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(i.delta),function(e,t){const n=t._physics_getDynamicBodyCount();if(0===n)return;const s=t._physics_getDynamicBodyTransforms(),r=s>>2;for(let s=0;s<n;s++){const n=r+4*s,i=t.HEAPU32[n],o=t.HEAPF32[n+1],a=t.HEAPF32[n+2],c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const l=e.world.get(i,z);if(!l)continue;let u=o,h=a,d=c;if(e.world.has(i,N)){const t=e.world.get(i,N);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,L)){const n=e.world.get(t.entity,L),s=nn(n.rotation),r=o-n.position.x,i=a-n.position.y,l=Math.cos(-s),f=Math.sin(-s);u=(r*l-i*f)/(0!==n.scale.x?n.scale.x:1),h=(r*f+i*l)/(0!==n.scale.y?n.scale.y:1),d=c-s}}l.position.x=u,l.position.y=h;const f=sn(d);l.rotation.w=f.w,l.rotation.x=f.x,l.rotation.y=f.y,l.rotation.z=f.z,e.world.insert(i,z,l)}}(e,s),function(e,t){t._physics_collectEvents();const n=[],s=t._physics_getCollisionEnterCount();if(s>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let r=0;r<s;r++){const s=e+6*r;n.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],contactY:t.HEAPF32[s+5]})}}const r=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;r.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const o=[],a=t._physics_getSensorEnterCount();if(a>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<a;n++){const s=e+2*n;o.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],l=t._physics_getSensorExitCount();if(l>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(tn,{collisionEnters:n,collisionExits:r,sensorEnters:o,sensorExits:c})}(e,s)},{name:"PhysicsSystem"})),e.__physicsModule=s});e.__physicsInitPromise=s}}function on(e,t,n){const s=e.world;if(s.has(n,S)){const e=s.get(n,S);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,P)){const e=s.get(n,P);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,C)){const e=s.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 an{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}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 cn(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 ln(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,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 hn(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]=cn(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=ln(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=cn(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 rn("",{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=Le.createShader(e.vertexSource,e.fragmentSource),s[i]=o),n[r]=Le.createFromAsset(e,o)}catch{n[r]=0}}return n}(n,s),h=je(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,$);r&&(r.texture=n[s.data.texture]||0,e.insert(t,$,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,$);n&&(n.material=r,e.insert(t,$,n))}else if("SpineAnimation"===s.type){const n=e.get(t,X);n&&(n.material=r,e.insert(t,X,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,X)?l.get(i,X):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&s.update(o,c*h);let d=0;if(l.has(i,L)){const e=un(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=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 dn{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 fn{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 dn(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.__spineInitPromise;if(r){s=(await r).controller.raw}await hn(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([H]);for(const s of n){if(e.get(s,H).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const s=e.getEntitiesWithComponents([W]);for(const r of s){const s=e.get(r,W);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,z,i);const o={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0};e.insert(r,H,o)}}}const pn={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=It.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:It.getTargetTexture(n),width:e.width,height:e.height}},release(e){It.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(It.releaseRenderTarget(e._handle),pn.create({width:t,height:n,depth:!0})),begin(e,t){It.begin(t,e._handle)},end(){It.end()},getDepthTexture:e=>It.getTargetDepthTexture(e._handle)};let _n=!1;function mn(e){_n=e}function gn(){return _n}function yn(){return!_n}var wn;e=wn=f,console.log(`[ESEngine] Platform: ${wn.name}`);export{Vt as App,Ze as AssetPlugin,Je as AssetServer,Qe as Assets,qe as AsyncCache,Me as BlendMode,E as BodyType,S as BoxCollider,H as Camera,W as Canvas,C as CapsuleCollider,V as Children,P as CircleCollider,ie as Commands,ae as CommandsInstance,pt as DataType,ht as Draw,oe as EntityCommands,Lt as GLDebug,bt as Geometry,p as INVALID_ENTITY,_ as INVALID_TEXTURE,ge as Input,ye as InputPlugin,me as InputState,z as LocalTransform,Le as Material,Xe as MaterialLoader,te as Mut,N as Parent,an as Physics,tn as PhysicsEvents,rn as PhysicsPlugin,Tt as PostProcess,fn as PreviewPlugin,se as Query,re as QueryInstance,Nt as RenderPipeline,Mt as RenderStage,pn as RenderTexture,It as Renderer,q as Res,J as ResMut,b as RigidBody,ce as Schedule,Ve as ShaderSources,X as SpineAnimation,$ as Sprite,_e as SystemRunner,Pe as Text,ve as TextAlign,Se as TextOverflow,Te as TextPlugin,Ce as TextRenderer,be as TextVerticalAlign,ee as Time,Ee as UIRect,O as Velocity,dn as WebAssetProvider,xe as World,L as WorldTransform,fe as addStartupSystem,de as addSystem,pe as addSystemToSchedule,et as assetPlugin,Ot as clearDrawCallbacks,B as clearUserComponents,w as color,Xt as createWebApp,R as defineComponent,K as defineResource,ue as defineSystem,U as defineTag,jt as flushPendingSystems,G as getComponentDefaults,t as getPlatform,s as getPlatformType,F as getUserComponent,at as initDrawAPI,Dt as initGLDebugAPI,wt as initGeometryAPI,ke as initMaterialAPI,Pt as initPostProcessAPI,Ft as initRendererAPI,we as inputPlugin,D as isBuiltinComponent,gn as isEditor,n as isPlatformInitialized,yn as isRuntime,Re as isTextureRef,r as isWeChat,i as isWeb,Ye as loadComponent,en as loadPhysicsModule,hn as loadRuntimeScene,je as loadSceneData,Ge as loadSceneWithAssets,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,x as quat,Ht as registerDrawCallback,tt as registerEmbeddedAssets,Ne as registerMaterialCallback,mn as setEditorMode,ct as shutdownDrawAPI,zt as shutdownGLDebugAPI,xt as shutdownGeometryAPI,De as shutdownMaterialAPI,Ct as shutdownPostProcessAPI,Bt as shutdownRendererAPI,Ae as textPlugin,Wt as unregisterDrawCallback,Ke as updateCameraAspectRatio,m as vec2,g as vec3,y as vec4};
//# sourceMappingURL=index.js.map
diff --git a/desktop/public/sdk/esm/spine/index.d.ts b/desktop/public/sdk/esm/spine/index.d.ts
index 30d934924..11583e2aa 100644
--- a/desktop/public/sdk/esm/spine/index.d.ts
+++ b/desktop/public/sdk/esm/spine/index.d.ts
@@ -498,10 +498,10 @@ declare class SpinePlugin implements Plugin {
build(app: App): void;
}
declare function submitSpineMeshesToCore(coreModule: ESEngineModule, controller: SpineModuleController, instanceId: number, transform?: Float32Array, color?: {
- x: number;
- y: number;
- z: number;
- w: number;
+ r: number;
+ g: number;
+ b: number;
+ a: number;
}): void;
export { SpineModuleController, SpinePlugin, SpineResource, loadSpineModule, submitSpineMeshesToCore, wrapSpineModule };
diff --git a/desktop/public/sdk/esm/spine/index.js b/desktop/public/sdk/esm/spine/index.js
index cbb77504b..b4a241724 100644
--- a/desktop/public/sdk/esm/spine/index.js
+++ b/desktop/public/sdk/esm/spine/index.js
@@ -1,2 +1,2 @@
-let e=0;function t(t,n){const r=++e;return{_id:Symbol(`Resource_${r}_${n??""}`),_name:n??`Resource_${r}`,_default:t}}function n(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}async function r(e,t){let r;if(t)r=await t();else{const t=(await import(e)).default;r=await t()}return{raw:r,api:n(r)}}t({delta:0,elapsed:0,frameCount:0},"Time");class s{constructor(e,t){this.raw_=e,this.api_=t,this.listeners_=new Map}get raw(){return this.raw_}loadSkeleton(e,t,n){let r,s;if("string"==typeof e){const t=(new TextEncoder).encode(e);s=t.length,r=this.raw_._malloc(s+1),this.raw_.HEAPU8.set(t,r),this.raw_.HEAPU8[r+s]=0}else s=e.length,r=this.raw_._malloc(s),this.raw_.HEAPU8.set(e,r);const i=this.api_.loadSkeleton(r,s,t,t.length,n);return this.raw_._free(r),i}getLastError(){return this.api_.getLastError()}unloadSkeleton(e){this.api_.unloadSkeleton(e)}getAtlasPageCount(e){return this.api_.getAtlasPageCount(e)}getAtlasPageTextureName(e,t){return this.api_.getAtlasPageTextureName(e,t)}setAtlasPageTexture(e,t,n,r,s){this.api_.setAtlasPageTexture(e,t,n,r,s)}createInstance(e){return this.api_.createInstance(e)}destroyInstance(e){this.api_.destroyInstance(e),this.listeners_.delete(e)}play(e,t,n=!0,r=0){return!!this.api_.playAnimation(e,t,n,r)}addAnimation(e,t,n=!0,r=0,s=0){return!!this.api_.addAnimation(e,t,n,r,s)}setSkin(e,t){this.api_.setSkin(e,t)}update(e,t){this.api_.update(e,t)}getAnimations(e){const t=this.api_.getAnimations(e);try{return JSON.parse(t)}catch{return[]}}getSkins(e){const t=this.api_.getSkins(e);try{return JSON.parse(t)}catch{return[]}}getBonePosition(e,t){const n=this.raw_._malloc(4),r=this.raw_._malloc(4);if(!this.api_.getBonePosition(e,t,n,r))return this.raw_._free(n),this.raw_._free(r),null;const s=this.raw_.HEAPF32[n>>2],i=this.raw_.HEAPF32[r>>2];return this.raw_._free(n),this.raw_._free(r),{x:s,y:i}}getBoneRotation(e,t){return this.api_.getBoneRotation(e,t)}getBounds(e){const t=this.raw_._malloc(16);this.api_.getBounds(e,t,t+4,t+8,t+12);const n=this.raw_.HEAPF32,r=t>>2,s={x:n[r],y:n[r+1],width:n[r+2],height:n[r+3]};return this.raw_._free(t),s}extractMeshBatches(e){const t=this.api_.getMeshBatchCount(e),n=[],r=this.raw_._malloc(8),s=r,i=r+4;for(let r=0;r<t;r++){const t=this.api_.getMeshBatchVertexCount(e,r),a=this.api_.getMeshBatchIndexCount(e,r);if(t<=0||a<=0)continue;const o=8*t*4,u=2*a,l=this.raw_._malloc(o),_=this.raw_._malloc(u);this.api_.getMeshBatchData(e,r,l,_,s,i);const h=new Float32Array(this.raw_.HEAPF32.buffer,l,8*t),c=new Uint16Array(this.raw_.HEAPU8.buffer,_,a);n.push({vertices:new Float32Array(h),indices:new Uint16Array(c),textureId:this.raw_.HEAPU32[s>>2],blendMode:this.raw_.HEAPU32[i>>2]}),this.raw_._free(l),this.raw_._free(_)}return this.raw_._free(r),n}on(e,t,n){this.listeners_.has(e)||this.listeners_.set(e,new Map);const r=this.listeners_.get(e);r.has(t)||r.set(t,new Set),r.get(t).add(n)}off(e,t,n){const r=this.listeners_.get(e);if(!r)return;const s=r.get(t);s&&s.delete(n)}removeAllListeners(e){this.listeners_.delete(e)}}const i=t(null,"SpineController");class a{constructor(e,t){this.wasmUrl_=e,this.factory_=t}build(e){const t=e.wasmModule,n=r(this.wasmUrl_,this.factory_).then(({raw:n,api:r})=>{const a=new s(n,r);return e.insertResource(i,a),{controller:a,coreModule:t}});e.insertResource(i,null),e.__spineInitPromise=n}}function o(e,t,n,r,s){const i=t.extractMeshBatches(n);let a=0;r&&(a=e._malloc(64),e.HEAPF32.set(r,a>>2));const o=s&&(1!==s.x||1!==s.y||1!==s.z||1!==s.w);for(const t of i){let n=t.vertices;if(o){n=new Float32Array(n);for(let e=0;e<n.length;e+=8)n[e+4]*=s.x,n[e+5]*=s.y,n[e+6]*=s.z,n[e+7]*=s.w}const r=n.byteLength,i=t.indices.byteLength,u=e._malloc(r),l=e._malloc(i);e.HEAPF32.set(n,u>>2),new Uint16Array(e.HEAPU8.buffer,l,t.indices.length).set(t.indices),e.renderer_submitTriangles(u,n.length/8,l,t.indices.length,t.textureId,t.blendMode,a),e._free(u),e._free(l)}a&&e._free(a)}export{s as SpineModuleController,a as SpinePlugin,i as SpineResource,r as loadSpineModule,o as submitSpineMeshesToCore,n as wrapSpineModule};
+let e=0;function t(t,n){const r=++e;return{_id:Symbol(`Resource_${r}_${n??""}`),_name:n??`Resource_${r}`,_default:t}}function n(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}async function r(e,t){let r;if(t)r=await t();else{const t=(await import(e)).default;r=await t()}return{raw:r,api:n(r)}}t({delta:0,elapsed:0,frameCount:0},"Time");class s{constructor(e,t){this.raw_=e,this.api_=t,this.listeners_=new Map}get raw(){return this.raw_}loadSkeleton(e,t,n){let r,s;if("string"==typeof e){const t=(new TextEncoder).encode(e);s=t.length,r=this.raw_._malloc(s+1),this.raw_.HEAPU8.set(t,r),this.raw_.HEAPU8[r+s]=0}else s=e.length,r=this.raw_._malloc(s),this.raw_.HEAPU8.set(e,r);const i=this.api_.loadSkeleton(r,s,t,t.length,n);return this.raw_._free(r),i}getLastError(){return this.api_.getLastError()}unloadSkeleton(e){this.api_.unloadSkeleton(e)}getAtlasPageCount(e){return this.api_.getAtlasPageCount(e)}getAtlasPageTextureName(e,t){return this.api_.getAtlasPageTextureName(e,t)}setAtlasPageTexture(e,t,n,r,s){this.api_.setAtlasPageTexture(e,t,n,r,s)}createInstance(e){return this.api_.createInstance(e)}destroyInstance(e){this.api_.destroyInstance(e),this.listeners_.delete(e)}play(e,t,n=!0,r=0){return!!this.api_.playAnimation(e,t,n,r)}addAnimation(e,t,n=!0,r=0,s=0){return!!this.api_.addAnimation(e,t,n,r,s)}setSkin(e,t){this.api_.setSkin(e,t)}update(e,t){this.api_.update(e,t)}getAnimations(e){const t=this.api_.getAnimations(e);try{return JSON.parse(t)}catch{return[]}}getSkins(e){const t=this.api_.getSkins(e);try{return JSON.parse(t)}catch{return[]}}getBonePosition(e,t){const n=this.raw_._malloc(4),r=this.raw_._malloc(4);if(!this.api_.getBonePosition(e,t,n,r))return this.raw_._free(n),this.raw_._free(r),null;const s=this.raw_.HEAPF32[n>>2],i=this.raw_.HEAPF32[r>>2];return this.raw_._free(n),this.raw_._free(r),{x:s,y:i}}getBoneRotation(e,t){return this.api_.getBoneRotation(e,t)}getBounds(e){const t=this.raw_._malloc(16);this.api_.getBounds(e,t,t+4,t+8,t+12);const n=this.raw_.HEAPF32,r=t>>2,s={x:n[r],y:n[r+1],width:n[r+2],height:n[r+3]};return this.raw_._free(t),s}extractMeshBatches(e){const t=this.api_.getMeshBatchCount(e),n=[],r=this.raw_._malloc(8),s=r,i=r+4;for(let r=0;r<t;r++){const t=this.api_.getMeshBatchVertexCount(e,r),a=this.api_.getMeshBatchIndexCount(e,r);if(t<=0||a<=0)continue;const o=8*t*4,u=2*a,l=this.raw_._malloc(o),_=this.raw_._malloc(u);this.api_.getMeshBatchData(e,r,l,_,s,i);const h=new Float32Array(this.raw_.HEAPF32.buffer,l,8*t),c=new Uint16Array(this.raw_.HEAPU8.buffer,_,a);n.push({vertices:new Float32Array(h),indices:new Uint16Array(c),textureId:this.raw_.HEAPU32[s>>2],blendMode:this.raw_.HEAPU32[i>>2]}),this.raw_._free(l),this.raw_._free(_)}return this.raw_._free(r),n}on(e,t,n){this.listeners_.has(e)||this.listeners_.set(e,new Map);const r=this.listeners_.get(e);r.has(t)||r.set(t,new Set),r.get(t).add(n)}off(e,t,n){const r=this.listeners_.get(e);if(!r)return;const s=r.get(t);s&&s.delete(n)}removeAllListeners(e){this.listeners_.delete(e)}}const i=t(null,"SpineController");class a{constructor(e,t){this.wasmUrl_=e,this.factory_=t}build(e){const t=e.wasmModule,n=r(this.wasmUrl_,this.factory_).then(({raw:n,api:r})=>{const a=new s(n,r);return e.insertResource(i,a),{controller:a,coreModule:t}});e.insertResource(i,null),e.__spineInitPromise=n}}function o(e,t,n,r,s){const i=t.extractMeshBatches(n);let a=0;r&&(a=e._malloc(64),e.HEAPF32.set(r,a>>2));const o=s&&(1!==s.r||1!==s.g||1!==s.b||1!==s.a);for(const t of i){let n=t.vertices;if(o){n=new Float32Array(n);for(let e=0;e<n.length;e+=8)n[e+4]*=s.r,n[e+5]*=s.g,n[e+6]*=s.b,n[e+7]*=s.a}const r=n.byteLength,i=t.indices.byteLength,u=e._malloc(r),l=e._malloc(i);e.HEAPF32.set(n,u>>2),new Uint16Array(e.HEAPU8.buffer,l,t.indices.length).set(t.indices),e.renderer_submitTriangles(u,n.length/8,l,t.indices.length,t.textureId,t.blendMode,a),e._free(u),e._free(l)}a&&e._free(a)}export{s as SpineModuleController,a as SpinePlugin,i as SpineResource,r as loadSpineModule,o as submitSpineMeshesToCore,n as wrapSpineModule};
//# sourceMappingURL=index.js.map
diff --git a/editor/src/asset/EditorAssetServer.ts b/editor/src/asset/EditorAssetServer.ts
index 45df07546..77d1e8812 100644
--- a/editor/src/asset/EditorAssetServer.ts
+++ b/editor/src/asset/EditorAssetServer.ts
@@ -370,7 +370,9 @@ export class EditorAssetServer {
}
if (typeof value === 'object' && value !== null) {
const obj = value as Record<string, number>;
- if ('w' in obj) {
+ if ('a' in obj) {
+ return { x: obj.r ?? 0, y: obj.g ?? 0, z: obj.b ?? 0, w: obj.a ?? 0 };
+ } else if ('w' in obj) {
return { x: obj.x ?? 0, y: obj.y ?? 0, z: obj.z ?? 0, w: obj.w ?? 0 };
} else if ('z' in obj) {
return { x: obj.x ?? 0, y: obj.y ?? 0, z: obj.z ?? 0 };
diff --git a/editor/src/bridge/EditorBridge.ts b/editor/src/bridge/EditorBridge.ts
index 05520a6d3..980ede023 100644
--- a/editor/src/bridge/EditorBridge.ts
+++ b/editor/src/bridge/EditorBridge.ts
@@ -120,7 +120,7 @@ export class EditorBridge {
case 'Sprite':
this.registry_.addSprite(entity, {
texture: comp.data.texture ?? 0,
- color: comp.data.color ?? { x: 1, y: 1, z: 1, w: 1 },
+ color: comp.data.color ?? { r: 1, g: 1, b: 1, a: 1 },
size: comp.data.size ?? { x: 100, y: 100 },
uvOffset: comp.data.uvOffset ?? { x: 0, y: 0 },
uvScale: comp.data.uvScale ?? { x: 1, y: 1 },
@@ -152,7 +152,7 @@ export class EditorBridge {
playing: comp.data.playing ?? true,
flipX: comp.data.flipX ?? false,
flipY: comp.data.flipY ?? false,
- color: comp.data.color ?? { x: 1, y: 1, z: 1, w: 1 },
+ color: comp.data.color ?? { r: 1, g: 1, b: 1, a: 1 },
layer: comp.data.layer ?? 0,
skeletonScale: comp.data.skeletonScale ?? 1,
});
diff --git a/editor/src/launcher/ProjectService.ts b/editor/src/launcher/ProjectService.ts
index 2c1c18737..3744acf7b 100644
--- a/editor/src/launcher/ProjectService.ts
+++ b/editor/src/launcher/ProjectService.ts
@@ -364,7 +364,7 @@ function createDefaultScene(
pixelsPerUnit,
scaleMode: 1,
matchWidthOrHeight: 0.5,
- backgroundColor: { x: 0, y: 0, z: 0, w: 1 },
+ backgroundColor: { r: 0, g: 0, b: 0, a: 1 },
},
},
],
diff --git a/editor/src/panels/InspectorPanel.ts b/editor/src/panels/InspectorPanel.ts
index a65538893..89ca3d773 100644
--- a/editor/src/panels/InspectorPanel.ts
+++ b/editor/src/panels/InspectorPanel.ts
@@ -775,7 +775,7 @@ export class InspectorPanel {
this.createVec4Editor(container, value as { x: number; y: number; z: number; w: number }, onChange);
break;
case ShaderPropertyType.Color:
- this.createColorEditor(container, value as { x: number; y: number; z: number; w: number }, onChange);
+ this.createColorEditor(container, value as { r: number; g: number; b: number; a: number }, onChange);
break;
default:
container.textContent = 'Unknown type';
@@ -1719,7 +1719,7 @@ export class InspectorPanel {
this.createVec4Editor(container, value as { x: number; y: number; z: number; w: number }, onChange);
break;
case ShaderPropertyType.Color:
- this.createColorEditor(container, value as { x: number; y: number; z: number; w: number }, onChange);
+ this.createColorEditor(container, value as { r: number; g: number; b: number; a: number }, onChange);
break;
case ShaderPropertyType.Texture:
this.createTextureEditor(container, value as string, onChange);
@@ -1982,18 +1982,18 @@ export class InspectorPanel {
private createColorEditor(
container: HTMLElement,
- value: { x: number; y: number; z: number; w: number },
- onChange: (v: { x: number; y: number; z: number; w: number }) => void
+ value: { r: number; g: number; b: number; a: number },
+ onChange: (v: { r: number; g: number; b: number; a: number }) => void
): void {
const wrapper = document.createElement('div');
wrapper.className = 'es-color-editor';
- const val = value ?? { x: 1, y: 1, z: 1, w: 1 };
+ const val = value ?? { r: 1, g: 1, b: 1, a: 1 };
const colorInput = document.createElement('input');
colorInput.type = 'color';
colorInput.className = 'es-input es-input-color';
- colorInput.value = this.vec4ToHex(val);
+ colorInput.value = this.colorToHex(val);
const alphaInput = document.createElement('input');
alphaInput.type = 'number';
@@ -2001,12 +2001,12 @@ export class InspectorPanel {
alphaInput.min = '0';
alphaInput.max = '1';
alphaInput.step = '0.01';
- alphaInput.value = String(val.w);
+ alphaInput.value = String(val.a);
const update = () => {
const hex = colorInput.value;
- const newColor = this.hexToVec4(hex);
- newColor.w = parseFloat(alphaInput.value) || 1;
+ const newColor = this.hexToColor(hex);
+ newColor.a = parseFloat(alphaInput.value) || 1;
onChange(newColor);
};
@@ -2019,18 +2019,18 @@ export class InspectorPanel {
container.appendChild(wrapper);
}
- private vec4ToHex(color: { x: number; y: number; z: number; w: number }): string {
- const r = Math.round(color.x * 255).toString(16).padStart(2, '0');
- const g = Math.round(color.y * 255).toString(16).padStart(2, '0');
- const b = Math.round(color.z * 255).toString(16).padStart(2, '0');
+ private colorToHex(color: { r: number; g: number; b: number; a: number }): string {
+ const r = Math.round(color.r * 255).toString(16).padStart(2, '0');
+ const g = Math.round(color.g * 255).toString(16).padStart(2, '0');
+ const b = Math.round(color.b * 255).toString(16).padStart(2, '0');
return `#${r}${g}${b}`;
}
- private hexToVec4(hex: string): { x: number; y: number; z: number; w: number } {
+ private hexToColor(hex: string): { r: number; g: number; b: number; a: number } {
const r = parseInt(hex.slice(1, 3), 16) / 255;
const g = parseInt(hex.slice(3, 5), 16) / 255;
const b = parseInt(hex.slice(5, 7), 16) / 255;
- return { x: r, y: g, z: b, w: 1 };
+ return { r, g, b, a: 1 };
}
private createTextureEditor(container: HTMLElement, value: string, onChange: (v: string) => void): void {
diff --git a/editor/src/panels/SceneViewPanel.ts b/editor/src/panels/SceneViewPanel.ts
index 33208fed9..4a79eca64 100644
--- a/editor/src/panels/SceneViewPanel.ts
+++ b/editor/src/panels/SceneViewPanel.ts
@@ -1136,7 +1136,7 @@ export class SceneViewPanel {
let w = 50;
let h = 50;
- let color: { x: number; y: number; z: number; w: number } | null = null;
+ let color: { r: number; g: number; b: number; a: number } | null = null;
const hasSprite = !!sprite;
let textureImg: HTMLImageElement | null = null;
let flipX = false;
@@ -1144,7 +1144,7 @@ export class SceneViewPanel {
if (sprite) {
const size = sprite.data.size as { x: number; y: number };
- const col = sprite.data.color as { x: number; y: number; z: number; w: number };
+ const col = sprite.data.color as { r: number; g: number; b: number; a: number };
const texturePath = sprite.data.texture;
if (size) {
@@ -1172,24 +1172,24 @@ export class SceneViewPanel {
if (hasSprite) {
if (textureImg) {
- ctx.globalAlpha = color?.w ?? 1;
+ ctx.globalAlpha = color?.a ?? 1;
ctx.drawImage(textureImg, -w / 2, -h / 2, w, h);
- if (color && (color.x !== 1 || color.y !== 1 || color.z !== 1)) {
+ if (color && (color.r !== 1 || color.g !== 1 || color.b !== 1)) {
ctx.globalCompositeOperation = 'multiply';
- const r = Math.round(color.x * 255);
- const g = Math.round(color.y * 255);
- const b = Math.round(color.z * 255);
+ const r = Math.round(color.r * 255);
+ const g = Math.round(color.g * 255);
+ const b = Math.round(color.b * 255);
ctx.fillStyle = `rgb(${r}, ${g}, ${b})`;
ctx.fillRect(-w / 2, -h / 2, w, h);
ctx.globalCompositeOperation = 'source-over';
}
ctx.globalAlpha = 1;
} else {
- const r = Math.round((color?.x ?? 0.4) * 255);
- const g = Math.round((color?.y ?? 0.4) * 255);
- const b = Math.round((color?.z ?? 0.8) * 255);
- const a = color?.w ?? 0.5;
+ const r = Math.round((color?.r ?? 0.4) * 255);
+ const g = Math.round((color?.g ?? 0.4) * 255);
+ const b = Math.round((color?.b ?? 0.8) * 255);
+ const a = color?.a ?? 0.5;
ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${a})`;
ctx.fillRect(-w / 2, -h / 2, w, h);
}
diff --git a/editor/src/property/editors.ts b/editor/src/property/editors.ts
index 377258cdb..2fdc948ff 100644
--- a/editor/src/property/editors.ts
+++ b/editor/src/property/editors.ts
@@ -416,7 +416,7 @@ function createColorEditor(
ctx: PropertyEditorContext
): PropertyEditorInstance {
const { value, onChange } = ctx;
- const color = (value as Vec4) ?? { x: 1, y: 1, z: 1, w: 1 };
+ const color = (value as { r: number; g: number; b: number; a: number }) ?? { r: 1, g: 1, b: 1, a: 1 };
const wrapper = document.createElement('div');
wrapper.className = 'es-color-editor';
@@ -424,7 +424,7 @@ function createColorEditor(
const colorInput = document.createElement('input');
colorInput.type = 'color';
colorInput.className = 'es-input es-input-color';
- colorInput.value = vec4ToHex(color);
+ colorInput.value = colorToHex(color);
const alphaInput = document.createElement('input');
alphaInput.type = 'number';
@@ -432,12 +432,12 @@ function createColorEditor(
alphaInput.min = '0';
alphaInput.max = '1';
alphaInput.step = '0.01';
- alphaInput.value = String(color.w);
+ alphaInput.value = String(color.a);
const updateColor = () => {
const hex = colorInput.value;
- const newColor = hexToVec4(hex);
- newColor.w = parseFloat(alphaInput.value) || 1;
+ const newColor = hexToColor(hex);
+ newColor.a = parseFloat(alphaInput.value) || 1;
onChange(newColor);
};
@@ -450,9 +450,9 @@ function createColorEditor(
return {
update(v: unknown) {
- const newColor = (v as Vec4) ?? { x: 1, y: 1, z: 1, w: 1 };
- colorInput.value = vec4ToHex(newColor);
- alphaInput.value = String(newColor.w);
+ const newColor = (v as { r: number; g: number; b: number; a: number }) ?? { r: 1, g: 1, b: 1, a: 1 };
+ colorInput.value = colorToHex(newColor);
+ alphaInput.value = String(newColor.a);
},
dispose() {
wrapper.remove();
@@ -460,18 +460,18 @@ function createColorEditor(
};
}
-function vec4ToHex(color: Vec4): string {
- const r = Math.round(color.x * 255).toString(16).padStart(2, '0');
- const g = Math.round(color.y * 255).toString(16).padStart(2, '0');
- const b = Math.round(color.z * 255).toString(16).padStart(2, '0');
+function colorToHex(color: { r: number; g: number; b: number; a: number }): string {
+ const r = Math.round(color.r * 255).toString(16).padStart(2, '0');
+ const g = Math.round(color.g * 255).toString(16).padStart(2, '0');
+ const b = Math.round(color.b * 255).toString(16).padStart(2, '0');
return `#${r}${g}${b}`;
}
-function hexToVec4(hex: string): Vec4 {
+function hexToColor(hex: string): { r: number; g: number; b: number; a: number } {
const r = parseInt(hex.slice(1, 3), 16) / 255;
const g = parseInt(hex.slice(3, 5), 16) / 255;
const b = parseInt(hex.slice(5, 7), 16) / 255;
- return { x: r, y: g, z: b, w: 1 };
+ return { r, g, b, a: 1 };
}
// =============================================================================
diff --git a/editor/src/renderer/EditorSceneRenderer.ts b/editor/src/renderer/EditorSceneRenderer.ts
index 62c5f2859..292047581 100644
--- a/editor/src/renderer/EditorSceneRenderer.ts
+++ b/editor/src/renderer/EditorSceneRenderer.ts
@@ -171,7 +171,7 @@ export class EditorSceneRenderer {
if (width <= 0 || height <= 0) return;
const bg = this.findCanvasBackgroundColor();
- Renderer.setClearColor(bg.x, bg.y, bg.z, bg.w);
+ Renderer.setClearColor(bg.r, bg.g, bg.b, bg.a);
const matrix = this.camera_.getViewProjection(width, height);
const elapsed = (performance.now() - this.startTime_) / 1000;
@@ -183,17 +183,17 @@ export class EditorSceneRenderer {
});
}
- private findCanvasBackgroundColor(): { x: number; y: number; z: number; w: number } {
+ private findCanvasBackgroundColor(): { r: number; g: number; b: number; a: number } {
if (this.store_) {
for (const entity of this.store_.scene.entities) {
for (const comp of entity.components) {
if (comp.type === 'Canvas' && comp.data?.backgroundColor) {
- return comp.data.backgroundColor as { x: number; y: number; z: number; w: number };
+ return comp.data.backgroundColor as { r: number; g: number; b: number; a: number };
}
}
}
}
- return { x: 0.1, y: 0.1, z: 0.1, w: 1.0 };
+ return { r: 0.1, g: 0.1, b: 0.1, a: 1.0 };
}
// =========================================================================
diff --git a/editor/src/scene/EditorSceneManager.ts b/editor/src/scene/EditorSceneManager.ts
index 150657c19..254d8ba2c 100644
--- a/editor/src/scene/EditorSceneManager.ts
+++ b/editor/src/scene/EditorSceneManager.ts
@@ -297,7 +297,7 @@ export class EditorSceneManager {
const flipY = (spineData?.flipY as boolean) ?? false;
const playing = spineData?.playing !== false;
const timeScale = (spineData?.timeScale as number) ?? 1;
- const color = spineData?.color as { x: number; y: number; z: number; w: number } | undefined;
+ const color = spineData?.color as { r: number; g: number; b: number; a: number } | undefined;
if (playing) {
this.spineController_.update(instanceId, dt * timeScale);
@@ -525,7 +525,7 @@ export class EditorSceneManager {
this.world_.insert(entity, Sprite, {
texture: textureHandle,
- color: data.color ?? { x: 1, y: 1, z: 1, w: 1 },
+ color: data.color ?? { r: 1, g: 1, b: 1, a: 1 },
size: data.size ?? { x: 100, y: 100 },
uvOffset: data.uvOffset ?? { x: 0, y: 0 },
uvScale: data.uvScale ?? { x: 1, y: 1 },
@@ -544,7 +544,7 @@ export class EditorSceneManager {
content: data.content ?? '',
fontFamily: data.fontFamily ?? 'Arial',
fontSize: data.fontSize ?? 24,
- color: data.color ?? { x: 1, y: 1, z: 1, w: 1 },
+ color: data.color ?? { r: 1, g: 1, b: 1, a: 1 },
align: data.align ?? TextAlign.Left,
verticalAlign: data.verticalAlign ?? TextVerticalAlign.Top,
wordWrap: data.wordWrap ?? true,
@@ -563,7 +563,7 @@ export class EditorSceneManager {
this.world_.insert(entity, Sprite, {
texture: result.textureHandle,
- color: { x: 1, y: 1, z: 1, w: 1 },
+ color: { r: 1, g: 1, b: 1, a: 1 },
size: { x: result.width, y: result.height },
uvOffset: { x: 0, y: 0 },
uvScale: { x: 1, y: 1 },
@@ -685,7 +685,7 @@ export class EditorSceneManager {
playing: data.playing ?? true,
flipX: data.flipX ?? false,
flipY: data.flipY ?? false,
- color: data.color ?? { x: 1, y: 1, z: 1, w: 1 },
+ color: data.color ?? { r: 1, g: 1, b: 1, a: 1 },
layer: data.layer ?? 0,
skeletonScale: data.skeletonScale ?? 1,
material: materialHandle,
diff --git a/editor/src/schemas/ComponentSchemas.ts b/editor/src/schemas/ComponentSchemas.ts
index 60d94a124..874b3f8c0 100644
--- a/editor/src/schemas/ComponentSchemas.ts
+++ b/editor/src/schemas/ComponentSchemas.ts
@@ -34,8 +34,9 @@ function isVec3(v: unknown): boolean {
}
function isVec4OrColor(v: unknown): boolean {
- return typeof v === 'object' && v !== null &&
- 'x' in v && 'y' in v && 'z' in v && 'w' in v;
+ if (typeof v !== 'object' || v === null) return false;
+ if ('r' in v && 'g' in v && 'b' in v && 'a' in v) return true;
+ return 'x' in v && 'y' in v && 'z' in v && 'w' in v;
}
function inferPropertyType(value: unknown): string {
@@ -388,7 +389,7 @@ const editorOnlyDefaults: Record<string, Record<string, unknown>> = {
content: 'Text',
fontFamily: 'Arial',
fontSize: 24,
- color: { x: 1, y: 1, z: 1, w: 1 },
+ color: { r: 1, g: 1, b: 1, a: 1 },
align: 0,
verticalAlign: 0,
wordWrap: true,
diff --git a/editor/src/shader/ShaderPropertyParser.ts b/editor/src/shader/ShaderPropertyParser.ts
index fc7448707..dbd39dcee 100644
--- a/editor/src/shader/ShaderPropertyParser.ts
+++ b/editor/src/shader/ShaderPropertyParser.ts
@@ -239,8 +239,9 @@ export function getDefaultPropertyValue(type: ShaderPropertyType): unknown {
case ShaderPropertyType.Vec3:
return { x: 0, y: 0, z: 0 };
case ShaderPropertyType.Vec4:
+ return { x: 0, y: 0, z: 0, w: 1 };
case ShaderPropertyType.Color:
- return { x: 1, y: 1, z: 1, w: 1 };
+ return { r: 1, g: 1, b: 1, a: 1 };
case ShaderPropertyType.Texture:
return '';
default:
diff --git a/editor/src/types/SceneTypes.ts b/editor/src/types/SceneTypes.ts
index c58906d33..6235bb0c9 100644
--- a/editor/src/types/SceneTypes.ts
+++ b/editor/src/types/SceneTypes.ts
@@ -114,7 +114,7 @@ export function createEmptyScene(
pixelsPerUnit,
scaleMode: 1,
matchWidthOrHeight: 0.5,
- backgroundColor: { x: 0, y: 0, z: 0, w: 1 },
+ backgroundColor: { r: 0, g: 0, b: 0, a: 1 },
},
},
],
diff --git a/sdk/src/app.ts b/sdk/src/app.ts
index 6cedb7699..e91feb8e4 100644
--- a/sdk/src/app.ts
+++ b/sdk/src/app.ts
@@ -277,7 +277,7 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): A
const canvas = findCanvasData(cppRegistry, scanLimit);
if (canvas) {
const bg = canvas.backgroundColor;
- Renderer.setClearColor(bg.x, bg.y, bg.z, bg.w);
+ Renderer.setClearColor(bg.r, bg.g, bg.b, bg.a);
}
const vp = computeViewProjection(cppRegistry, width, height);
const elapsed = (platformNow() - startTime) / 1000;
@@ -324,7 +324,7 @@ function findCanvasData(registry: CppRegistry, scanLimit: number): {
designResolution: { x: number; y: number };
scaleMode: number;
matchWidthOrHeight: number;
- backgroundColor: { x: number; y: number; z: number; w: number };
+ backgroundColor: { r: number; g: number; b: number; a: number };
} | null {
for (let e = 0; e < scanLimit; e++) {
if (!registry.valid(e) || !registry.hasCanvas(e)) continue;
@@ -332,7 +332,7 @@ function findCanvasData(registry: CppRegistry, scanLimit: number): {
designResolution: { x: number; y: number };
scaleMode: number;
matchWidthOrHeight: number;
- backgroundColor: { x: number; y: number; z: number; w: number };
+ backgroundColor: { r: number; g: number; b: number; a: number };
};
return canvas;
}
diff --git a/sdk/src/component.ts b/sdk/src/component.ts
index c31631ad0..734a12977 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, Vec4, Quat, INVALID_TEXTURE } from './types';
+import { Entity, Vec2, Vec3, Color, Quat, INVALID_TEXTURE } from './types';
import {
RigidBody, BoxCollider, CircleCollider, CapsuleCollider,
type RigidBodyData, type BoxColliderData, type CircleColliderData, type CapsuleColliderData,
@@ -137,7 +137,7 @@ export interface WorldTransformData {
export interface SpriteData {
texture: number;
- color: Vec4;
+ color: Color;
size: Vec2;
uvOffset: Vec2;
uvScale: Vec2;
@@ -164,7 +164,7 @@ export interface CanvasData {
pixelsPerUnit: number;
scaleMode: number;
matchWidthOrHeight: number;
- backgroundColor: Vec4;
+ backgroundColor: Color;
}
export interface VelocityData {
@@ -190,7 +190,7 @@ export interface SpineAnimationData {
playing: boolean;
flipX: boolean;
flipY: boolean;
- color: Vec4;
+ color: Color;
layer: number;
skeletonScale: number;
material: number;
@@ -214,7 +214,7 @@ export const WorldTransform = defineBuiltin<WorldTransformData>('WorldTransform'
export const Sprite = defineBuiltin<SpriteData>('Sprite', {
texture: INVALID_TEXTURE,
- color: { x: 1, y: 1, z: 1, w: 1 },
+ color: { r: 1, g: 1, b: 1, a: 1 },
size: { x: 32, y: 32 },
uvOffset: { x: 0, y: 0 },
uvScale: { x: 1, y: 1 },
@@ -241,7 +241,7 @@ export const Canvas = defineBuiltin<CanvasData>('Canvas', {
pixelsPerUnit: 100,
scaleMode: 1,
matchWidthOrHeight: 0.5,
- backgroundColor: { x: 0, y: 0, z: 0, w: 1 }
+ backgroundColor: { r: 0, g: 0, b: 0, a: 1 }
});
export const Velocity = defineBuiltin<VelocityData>('Velocity', {
@@ -267,7 +267,7 @@ export const SpineAnimation = defineBuiltin<SpineAnimationData>('SpineAnimation'
playing: true,
flipX: false,
flipY: false,
- color: { x: 1, y: 1, z: 1, w: 1 },
+ color: { r: 1, g: 1, b: 1, a: 1 },
layer: 0,
skeletonScale: 1.0,
material: 0
diff --git a/sdk/src/draw.ts b/sdk/src/draw.ts
index b4b2ff023..9c8b78054 100644
--- a/sdk/src/draw.ts
+++ b/sdk/src/draw.ts
@@ -200,7 +200,7 @@ function getModule(): ESEngineModule {
return module;
}
-const WHITE: Color = { x: 1, y: 1, z: 1, w: 1 };
+const WHITE: Color = { r: 1, g: 1, b: 1, a: 1 };
export const Draw: DrawAPI = {
begin(viewProjection: Float32Array): void {
@@ -217,7 +217,7 @@ export const Draw: DrawAPI = {
getModule().draw_line(
from.x, from.y,
to.x, to.y,
- color.x, color.y, color.z, color.w,
+ color.r, color.g, color.b, color.a,
thickness
);
},
@@ -226,7 +226,7 @@ export const Draw: DrawAPI = {
getModule().draw_rect(
position.x, position.y,
size.x, size.y,
- color.x, color.y, color.z, color.w,
+ color.r, color.g, color.b, color.a,
filled
);
},
@@ -235,7 +235,7 @@ export const Draw: DrawAPI = {
getModule().draw_rectOutline(
position.x, position.y,
size.x, size.y,
- color.x, color.y, color.z, color.w,
+ color.r, color.g, color.b, color.a,
thickness
);
},
@@ -244,7 +244,7 @@ export const Draw: DrawAPI = {
getModule().draw_circle(
center.x, center.y,
radius,
- color.x, color.y, color.z, color.w,
+ color.r, color.g, color.b, color.a,
filled,
segments
);
@@ -254,7 +254,7 @@ export const Draw: DrawAPI = {
getModule().draw_circleOutline(
center.x, center.y,
radius,
- color.x, color.y, color.z, color.w,
+ color.r, color.g, color.b, color.a,
thickness,
segments
);
@@ -265,7 +265,7 @@ export const Draw: DrawAPI = {
position.x, position.y,
size.x, size.y,
textureHandle,
- tint.x, tint.y, tint.z, tint.w
+ tint.r, tint.g, tint.b, tint.a
);
},
@@ -275,7 +275,7 @@ export const Draw: DrawAPI = {
size.x, size.y,
rotation,
textureHandle,
- tint.x, tint.y, tint.z, tint.w
+ tint.r, tint.g, tint.b, tint.a
);
},
diff --git a/sdk/src/material.ts b/sdk/src/material.ts
index e40f41091..63973d603 100644
--- a/sdk/src/material.ts
+++ b/sdk/src/material.ts
@@ -247,7 +247,9 @@ export const Material = {
uniforms[key] = value;
} else if (typeof value === 'object' && value !== null) {
const obj = value as Record<string, number>;
- if ('w' in obj) {
+ if ('a' in obj) {
+ uniforms[key] = { x: obj.r ?? 0, y: obj.g ?? 0, z: obj.b ?? 0, w: obj.a ?? 0 };
+ } else if ('w' in obj) {
uniforms[key] = { x: obj.x ?? 0, y: obj.y ?? 0, z: obj.z ?? 0, w: obj.w ?? 0 };
} else if ('z' in obj) {
uniforms[key] = { x: obj.x ?? 0, y: obj.y ?? 0, z: obj.z ?? 0 };
diff --git a/sdk/src/spine/SpinePlugin.ts b/sdk/src/spine/SpinePlugin.ts
index 3998a543a..4bbdce112 100644
--- a/sdk/src/spine/SpinePlugin.ts
+++ b/sdk/src/spine/SpinePlugin.ts
@@ -43,7 +43,7 @@ export function submitSpineMeshesToCore(
controller: SpineModuleController,
instanceId: number,
transform?: Float32Array,
- color?: { x: number; y: number; z: number; w: number },
+ color?: { r: number; g: number; b: number; a: number },
): void {
const batches = controller.extractMeshBatches(instanceId);
@@ -53,17 +53,17 @@ export function submitSpineMeshesToCore(
coreModule.HEAPF32.set(transform, transformPtr >> 2);
}
- const needsTint = color && (color.x !== 1 || color.y !== 1 || color.z !== 1 || color.w !== 1);
+ const needsTint = color && (color.r !== 1 || color.g !== 1 || color.b !== 1 || color.a !== 1);
for (const batch of batches) {
let vertices = batch.vertices;
if (needsTint) {
vertices = new Float32Array(vertices);
for (let i = 0; i < vertices.length; i += 8) {
- vertices[i + 4] *= color.x;
- vertices[i + 5] *= color.y;
- vertices[i + 6] *= color.z;
- vertices[i + 7] *= color.w;
+ vertices[i + 4] *= color.r;
+ vertices[i + 5] *= color.g;
+ vertices[i + 6] *= color.b;
+ vertices[i + 7] *= color.a;
}
}
diff --git a/sdk/src/types.ts b/sdk/src/types.ts
index 19f7074de..e83c34774 100644
--- a/sdk/src/types.ts
+++ b/sdk/src/types.ts
@@ -42,7 +42,12 @@ export interface Quat {
z: number;
}
-export type Color = Vec4;
+export interface Color {
+ r: number;
+ g: number;
+ b: number;
+ a: number;
+}
// =============================================================================
// Factory Functions
@@ -51,5 +56,5 @@ export type Color = Vec4;
export const vec2 = (x = 0, y = 0): Vec2 => ({ x, y });
export const vec3 = (x = 0, y = 0, z = 0): Vec3 => ({ x, y, z });
export const vec4 = (x = 0, y = 0, z = 0, w = 1): Vec4 => ({ x, y, z, w });
-export const color = (r = 1, g = 1, b = 1, a = 1): Color => ({ x: r, y: g, z: b, w: a });
+export const color = (r = 1, g = 1, b = 1, a = 1): Color => ({ r, g, b, a });
export const quat = (w = 1, x = 0, y = 0, z = 0): Quat => ({ w, x, y, z });
diff --git a/sdk/src/ui/TextPlugin.ts b/sdk/src/ui/TextPlugin.ts
index 0e96d1939..e1afd6cfb 100644
--- a/sdk/src/ui/TextPlugin.ts
+++ b/sdk/src/ui/TextPlugin.ts
@@ -39,7 +39,7 @@ export class TextPlugin implements Plugin {
world.insert(entity, Sprite, {
texture: INVALID_TEXTURE,
size: { x: 0, y: 0 },
- color: { x: 1, y: 1, z: 1, w: 1 },
+ color: { r: 1, g: 1, b: 1, a: 1 },
anchor: { x: 0.5, y: 0.5 },
flip: { x: false, y: false }
});
diff --git a/sdk/src/ui/TextRenderer.ts b/sdk/src/ui/TextRenderer.ts
index 39a46e0f4..8c4ec3538 100644
--- a/sdk/src/ui/TextRenderer.ts
+++ b/sdk/src/ui/TextRenderer.ts
@@ -76,10 +76,10 @@ export class TextRenderer {
canvas.height = newHeight;
}
- const r = Math.round(text.color.x * 255);
- const g = Math.round(text.color.y * 255);
- const b = Math.round(text.color.z * 255);
- const a = text.color.w;
+ const r = Math.round(text.color.r * 255);
+ const g = Math.round(text.color.g * 255);
+ const b = Math.round(text.color.b * 255);
+ const a = text.color.a;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.font = `${text.fontSize}px ${text.fontFamily}`;
diff --git a/sdk/src/ui/text.ts b/sdk/src/ui/text.ts
index fd7c31bf5..7cbc1cb5f 100644
--- a/sdk/src/ui/text.ts
+++ b/sdk/src/ui/text.ts
@@ -4,7 +4,7 @@
*/
import { defineComponent } from '../component';
-import type { Vec4 } from '../types';
+import type { Color } from '../types';
// =============================================================================
// Text Alignment Enums
@@ -36,7 +36,7 @@ export interface TextData {
content: string;
fontFamily: string;
fontSize: number;
- color: Vec4;
+ color: Color;
align: TextAlign;
verticalAlign: TextVerticalAlign;
wordWrap: boolean;
@@ -53,7 +53,7 @@ export const Text = defineComponent<TextData>('Text', {
content: '',
fontFamily: 'Arial',
fontSize: 24,
- color: { x: 1, y: 1, z: 1, w: 1 },
+ color: { r: 1, g: 1, b: 1, a: 1 },
align: TextAlign.Left,
verticalAlign: TextVerticalAlign.Top,
wordWrap: true,
diff --git a/sdk/src/wasm.generated.ts b/sdk/src/wasm.generated.ts
index bf866a15f..4c076020c 100644
--- a/sdk/src/wasm.generated.ts
+++ b/sdk/src/wasm.generated.ts
@@ -4,7 +4,7 @@
* @details Generated by EHT - DO NOT EDIT
*/
-import type { Entity, Vec2, Vec3, Vec4, Quat } from './types';
+import type { Entity, Vec2, Vec3, Vec4, Color, Quat } from './types';
// Additional Math Types
export interface UVec2 { x: number; y: number; }
@@ -88,7 +88,7 @@ export interface SpineAnimation {
playing: boolean;
flipX: boolean;
flipY: boolean;
- color: Vec4;
+ color: Color;
layer: number;
skeletonScale: number;
material: number;
@@ -106,7 +106,7 @@ export interface RigidBody {
export interface Sprite {
texture: number;
- color: Vec4;
+ color: Color;
size: Vec2;
uvOffset: Vec2;
uvScale: Vec2;
@@ -128,7 +128,7 @@ export interface Canvas {
pixelsPerUnit: number;
scaleMode: number;
matchWidthOrHeight: number;
- backgroundColor: Vec4;
+ backgroundColor: Color;
}
export interface Camera {
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index 9fa89a5b0..4cbd5d4a1 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -118,9 +118,16 @@ RigidBodyJS rigidbodyToJS(const esengine::ecs::RigidBody& c) {
return js;
}
+struct ColorJS {
+ f32 r, g, b, a;
+};
+
+ColorJS colorToJS(const glm::vec4& c) { return {c.x, c.y, c.z, c.w}; }
+glm::vec4 colorFromJS(const ColorJS& c) { return {c.r, c.g, c.b, c.a}; }
+
struct SpriteJS {
u32 texture;
- glm::vec4 color;
+ ColorJS color;
glm::vec2 size;
glm::vec2 uvOffset;
glm::vec2 uvScale;
@@ -133,7 +140,7 @@ struct SpriteJS {
esengine::ecs::Sprite spriteFromJS(const SpriteJS& js) {
esengine::ecs::Sprite c;
c.texture = resource::TextureHandle(js.texture);
- c.color = js.color;
+ c.color = colorFromJS(js.color);
c.size = js.size;
c.uvOffset = js.uvOffset;
c.uvScale = js.uvScale;
@@ -147,7 +154,7 @@ esengine::ecs::Sprite spriteFromJS(const SpriteJS& js) {
SpriteJS spriteToJS(const esengine::ecs::Sprite& c) {
SpriteJS js;
js.texture = c.texture.id();
- js.color = c.color;
+ js.color = colorToJS(c.color);
js.size = c.size;
js.uvOffset = c.uvOffset;
js.uvScale = c.uvScale;
@@ -163,7 +170,7 @@ struct CanvasJS {
f32 pixelsPerUnit;
i32 scaleMode;
f32 matchWidthOrHeight;
- glm::vec4 backgroundColor;
+ ColorJS backgroundColor;
};
esengine::ecs::Canvas canvasFromJS(const CanvasJS& js) {
@@ -172,7 +179,7 @@ esengine::ecs::Canvas canvasFromJS(const CanvasJS& js) {
c.pixelsPerUnit = js.pixelsPerUnit;
c.scaleMode = static_cast<CanvasScaleMode>(js.scaleMode);
c.matchWidthOrHeight = js.matchWidthOrHeight;
- c.backgroundColor = js.backgroundColor;
+ c.backgroundColor = colorFromJS(js.backgroundColor);
return c;
}
@@ -182,7 +189,59 @@ CanvasJS canvasToJS(const esengine::ecs::Canvas& c) {
js.pixelsPerUnit = c.pixelsPerUnit;
js.scaleMode = static_cast<i32>(c.scaleMode);
js.matchWidthOrHeight = c.matchWidthOrHeight;
- js.backgroundColor = c.backgroundColor;
+ js.backgroundColor = colorToJS(c.backgroundColor);
+ return js;
+}
+
+struct SpineAnimationJS {
+ std::string skeletonPath;
+ std::string atlasPath;
+ std::string skin;
+ std::string animation;
+ f32 timeScale;
+ bool loop;
+ bool playing;
+ bool flipX;
+ bool flipY;
+ ColorJS color;
+ i32 layer;
+ f32 skeletonScale;
+ u32 material;
+};
+
+esengine::ecs::SpineAnimation spineAnimationFromJS(const SpineAnimationJS& js) {
+ esengine::ecs::SpineAnimation c;
+ c.skeletonPath = js.skeletonPath;
+ c.atlasPath = js.atlasPath;
+ c.skin = js.skin;
+ c.animation = js.animation;
+ c.timeScale = js.timeScale;
+ c.loop = js.loop;
+ c.playing = js.playing;
+ c.flipX = js.flipX;
+ c.flipY = js.flipY;
+ c.color = colorFromJS(js.color);
+ c.layer = js.layer;
+ c.skeletonScale = js.skeletonScale;
+ c.material = js.material;
+ return c;
+}
+
+SpineAnimationJS spineAnimationToJS(const esengine::ecs::SpineAnimation& c) {
+ SpineAnimationJS js;
+ js.skeletonPath = c.skeletonPath;
+ js.atlasPath = c.atlasPath;
+ js.skin = c.skin;
+ js.animation = c.animation;
+ js.timeScale = c.timeScale;
+ js.loop = c.loop;
+ js.playing = c.playing;
+ js.flipX = c.flipX;
+ js.flipY = c.flipY;
+ js.color = colorToJS(c.color);
+ js.layer = c.layer;
+ js.skeletonScale = c.skeletonScale;
+ js.material = c.material;
return js;
}
@@ -224,6 +283,12 @@ CameraJS cameraToJS(const esengine::ecs::Camera& c) {
}
EMSCRIPTEN_BINDINGS(esengine_components) {
+ value_object<ColorJS>("Color")
+ .field("r", &ColorJS::r)
+ .field("g", &ColorJS::g)
+ .field("b", &ColorJS::b)
+ .field("a", &ColorJS::a);
+
value_object<esengine::ecs::BoxCollider>("BoxCollider")
.field("halfExtents", &esengine::ecs::BoxCollider::halfExtents)
.field("offset", &esengine::ecs::BoxCollider::offset)
@@ -263,20 +328,20 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("linear", &esengine::ecs::Velocity::linear)
.field("angular", &esengine::ecs::Velocity::angular);
- value_object<esengine::ecs::SpineAnimation>("SpineAnimation")
- .field("skeletonPath", &esengine::ecs::SpineAnimation::skeletonPath)
- .field("atlasPath", &esengine::ecs::SpineAnimation::atlasPath)
- .field("skin", &esengine::ecs::SpineAnimation::skin)
- .field("animation", &esengine::ecs::SpineAnimation::animation)
- .field("timeScale", &esengine::ecs::SpineAnimation::timeScale)
- .field("loop", &esengine::ecs::SpineAnimation::loop)
- .field("playing", &esengine::ecs::SpineAnimation::playing)
- .field("flipX", &esengine::ecs::SpineAnimation::flipX)
- .field("flipY", &esengine::ecs::SpineAnimation::flipY)
- .field("color", &esengine::ecs::SpineAnimation::color)
- .field("layer", &esengine::ecs::SpineAnimation::layer)
- .field("skeletonScale", &esengine::ecs::SpineAnimation::skeletonScale)
- .field("material", &esengine::ecs::SpineAnimation::material);
+ value_object<SpineAnimationJS>("SpineAnimation")
+ .field("skeletonPath", &SpineAnimationJS::skeletonPath)
+ .field("atlasPath", &SpineAnimationJS::atlasPath)
+ .field("skin", &SpineAnimationJS::skin)
+ .field("animation", &SpineAnimationJS::animation)
+ .field("timeScale", &SpineAnimationJS::timeScale)
+ .field("loop", &SpineAnimationJS::loop)
+ .field("playing", &SpineAnimationJS::playing)
+ .field("flipX", &SpineAnimationJS::flipX)
+ .field("flipY", &SpineAnimationJS::flipY)
+ .field("color", &SpineAnimationJS::color)
+ .field("layer", &SpineAnimationJS::layer)
+ .field("skeletonScale", &SpineAnimationJS::skeletonScale)
+ .field("material", &SpineAnimationJS::material);
value_object<RigidBodyJS>("RigidBody")
.field("bodyType", &RigidBodyJS::bodyType)
@@ -428,11 +493,11 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
.function("hasSpineAnimation", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::SpineAnimation>(static_cast<Entity>(e));
}))
- .function("getSpineAnimation", optional_override([](Registry& r, u32 e) -> esengine::ecs::SpineAnimation& {
- return r.get<esengine::ecs::SpineAnimation>(static_cast<Entity>(e));
- }), allow_raw_pointers())
- .function("addSpineAnimation", optional_override([](Registry& r, u32 e, const esengine::ecs::SpineAnimation& c) {
- r.emplaceOrReplace<esengine::ecs::SpineAnimation>(static_cast<Entity>(e), c);
+ .function("getSpineAnimation", optional_override([](Registry& r, u32 e) {
+ return spineAnimationToJS(r.get<esengine::ecs::SpineAnimation>(static_cast<Entity>(e)));
+ }))
+ .function("addSpineAnimation", optional_override([](Registry& r, u32 e, const SpineAnimationJS& js) {
+ r.emplaceOrReplace<esengine::ecs::SpineAnimation>(static_cast<Entity>(e), spineAnimationFromJS(js));
}))
.function("removeSpineAnimation", optional_override([](Registry& r, u32 e) {
r.remove<esengine::ecs::SpineAnimation>(static_cast<Entity>(e));
diff --git a/templates/src/main.ts b/templates/src/main.ts
index 19058f0b9..e39466df4 100644
--- a/templates/src/main.ts
+++ b/templates/src/main.ts
@@ -61,7 +61,7 @@ export async function main(Module: ESEngineModule): Promise<void> {
const sprite = cmds.spawn()
.insert(Sprite, {
texture: 0,
- color: { x: 1, y: 0.5, z: 0.2, w: 1 },
+ color: { r: 1, g: 0.5, b: 0.2, a: 1 },
size: { x: 100, y: 100 },
uvOffset: { x: 0, y: 0 },
uvScale: { x: 1, y: 1 },