A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix: resolve spine rendering and asset loading in preview
esenginee0d9e87b06d1
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.jsindex 2b05a741e..2ef00b61b 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().readTextFile(e)}async function s(e){return t().fileExists(e)}function o(e,r){return t().createCanvas(e,r)}function i(){return t().now()}function a(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 l=null;function u(){return l||(l=wx.getFileSystemManager()),l}function h(e){return new Promise((t,r)=>{u().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function d(e,t="utf-8"){return new Promise((r,n)=>{u().readFile({filePath:e,encoding:t,success:e=>{r(e.data)},fail:t=>{n(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function p(e){return new Promise(t=>{u().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}let f=null,x=null;function _(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 m(e,t=!0){const{width:r,height:n}=e,{ctx:s}=function(e,t){return f||(f=wx.createCanvas(),f.width=e,f.height=t,x=f.getContext("2d")),(f.width<e||f.height<t)&&(f.width=Math.max(f.width,e),f.height=Math.max(f.height,t)),{canvas:f,ctx:x}}(r,n);s.clearRect(0,0,r,n),s.save(),t&&(s.translate(0,n),s.scale(1,-1)),s.drawImage(e,0,0),s.restore();const o=s.getImageData(0,0,r,n);return{width:r,height:n,pixels:new Uint8Array(o.data.buffer)}}let g=!1;const y=new class{constructor(){this.name="wechat"}async fetch(e,t){return a(e,t)}async readFile(e){return h(e)}async readTextFile(e){return d(e)}async fileExists(e){return p(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)}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)})}},w=4294967295;let v=0;function S(e,t){const r=++v;return{_id:Symbol(`Component_${r}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function T(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function P(e,t){const r=T(),n=r.get(e);if(n)return n;const s=S(e,t);return r.set(e,s),b(e,t,!1),s}function C(e){return T().get(e)}function b(e,t,r){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,r)}function A(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function M(e){return!0===e._builtin}const R=A("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),E=A("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),F=A("Sprite",{texture:w,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}),U=A("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0}),I=A("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),z=A("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),B=A("Parent",{entity:0}),W=A("Children",{entities:[]}),$=A("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}),k={LocalTransform:R,WorldTransform:E,Sprite:F,Camera:U,Canvas:I,Velocity:z,Parent:B,Children:W,SpineAnimation:$};let D=0;function L(e,t){const r=++D;return{_id:Symbol(`Resource_${r}_${t??""}`),_name:t??`Resource_${r}`,_default:e}}class O{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 H{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 O(this.get(e),t=>this.set(e,t))}}const N=L({delta:0,elapsed:0,frameCount:0},"Time");function G(e){return"object"==typeof e&&null!==e&&"mut"===e._type}class V{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return G(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,c=[];try{for(const e of i){if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data);c=[];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)c.push({component:s[e],data:o[e]});a=e,yield[e,...o]}}finally{if(null!==a)for(const e of c)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 j{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=M(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 X{constructor(e,t){this.pending_=[],this.world_=e,this.resources_=t}spawn(){return new j(this,null)}entity(e){return new j(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.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 q;exports.Schedule=void 0,(q=exports.Schedule||(exports.Schedule={}))[q.Startup=0]="Startup",q[q.First=1]="First",q[q.PreUpdate=2]="PreUpdate",q[q.Update=3]="Update",q[q.PostUpdate=4]="PostUpdate",q[q.Last=5]="Last",q[q.FixedPreUpdate=10]="FixedPreUpdate",q[q.FixedUpdate=11]="FixedUpdate",q[q.FixedPostUpdate=12]="FixedPostUpdate";let Y=0;function K(e,t,r){const n=++Y;return{_id:Symbol(`System_${n}_${r?.name??""}`),_params:e,_fn:t,_name:r?.name??`System_${n}`}}function J(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class Q{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 X&&e.flush()}resolveParam(e){switch(e._type){case"query":return new V(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new X(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Z{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 ee=L(new Z,"Input");class te{constructor(e){this.target_=e??null}build(e){const r=new Z;e.insertResource(ee,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,K([],()=>{r.keysPressed.clear(),r.keysReleased.clear(),r.mouseButtonsPressed.clear(),r.mouseButtonsReleased.clear(),r.scrollDeltaX=0,r.scrollDeltaY=0},{name:"InputClearSystem"}))}}const re=new te;class ne{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 M(t)?this.insertBuiltin(e,t,r):this.insertScript(e,t,r)}get(e,t){return M(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return M(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){M(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 se,oe,ie;exports.TextAlign=void 0,(se=exports.TextAlign||(exports.TextAlign={}))[se.Left=0]="Left",se[se.Center=1]="Center",se[se.Right=2]="Right",exports.TextVerticalAlign=void 0,(oe=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[oe.Top=0]="Top",oe[oe.Middle=1]="Middle",oe[oe.Bottom=2]="Bottom",exports.TextOverflow=void 0,(ie=exports.TextOverflow||(exports.TextOverflow={}))[ie.Visible=0]="Visible",ie[ie.Clip=1]="Clip",ie[ie.Ellipsis=2]="Ellipsis";const ae=P("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 ce{constructor(e){this.cache=new Map,this.module=e,this.canvas=o(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 c=this.wrapText(e.content,a?o: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),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/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[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 x=Math.round(255*e.color.x),_=Math.round(255*e.color.y),m=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(${x}, ${_}, ${m}, ${g})`,s&&e.overflow===exports.TextOverflow.Clip&&(r.save(),r.beginPath(),r.rect(0,0,p,f),r.clip());const y=c.length*l;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 c){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+=l}s&&e.overflow===exports.TextOverflow.Clip&&r.restore();const S=r.getImageData(0,0,p,f),T=new Uint8Array(S.data.buffer),P=this.flipVertically(T,p,f),C=this.module.getResourceManager(),b=this.module._malloc(P.length);this.module.HEAPU8.set(P,b);const A=C.createTexture(p,f,b,P.length,1);return this.module._free(b),{textureHandle:A,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}flipVertically(e,t,r){const n=4*t,s=new Uint8Array(e.length);for(let t=0;t<r;t++){const o=t*n,i=(r-1-t)*n;s.set(e.subarray(o,o+n),i)}return s}}const le=P("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class ue{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const r=new ce(t),n=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,K([],()=>{const e=n.getEntitiesWithComponents([ae]);for(const t of e){const e=n.get(t,ae);if(!e.dirty)continue;n.has(t,F)||n.insert(t,F,{texture:w,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,le)?n.get(t,le):null,o=r.renderForEntity(t,e,s),i=n.get(t,F);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,F,i),e.dirty=!1}}))}}const he=new ue;var de;function pe(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(de=exports.BlendMode||(exports.BlendMode={}))[de.Normal=0]="Normal",de[de.Additive=1]="Additive",de[de.Multiply=2]="Multiply",de[de.Screen=3]="Screen",de[de.PremultipliedAlpha=4]="PremultipliedAlpha";let fe=null,xe=null,_e=1;const me=new Map;function ge(e){fe=e,xe=e.getResourceManager(),be()}function ye(){0!==Te&&fe&&(fe._free(Te),Te=0),me.clear(),_e=1,Se=!1,xe=null,fe=null}function we(){if(!xe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return xe}const ve={createShader:(e,t)=>we().createShader(e,t),releaseShader(e){e>0&&we().releaseShader(e)},create(e){const t=_e++,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 me.set(t,r),t},get:e=>me.get(e),setUniform(e,t,r){const n=me.get(e);n&&n.uniforms.set(t,r)},getUniform(e,t){const r=me.get(e);return r?.uniforms.get(t)},setBlendMode(e,t){const r=me.get(e);r&&(r.blendMode=t)},getBlendMode(e){const t=me.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const r=me.get(e);r&&(r.depthTest=t)},getShader(e){const t=me.get(e);return t?.shader??0},release(e){me.delete(e)},isValid:e=>me.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=me.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const r=_e++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return me.set(r,n),r},toAssetData(e,t){const r=me.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=me.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Se=!1,Te=0;const Pe=4096;function Ce(e){const t=(0===Te&&fe&&(Te=fe._malloc(Pe)),Te);if(0===t||!fe)return{ptr:0,count:0};let r=0,n=0;const s=fe.HEAPU8,o=fe.HEAPU32,i=fe.HEAPF32;for(const[a,c]of e){if(r+128>Pe)break;const e=(new TextEncoder).encode(a),l=e.length,u=4*Math.ceil(l/4);o[t+r>>2]=l,r+=4,s.set(e,t+r),r+=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]);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 be(){if(!fe||Se)return;fe.materialDataProvider=(e,t,r,n,s)=>{const o=me.get(e);if(!o)return fe.HEAPU32[t>>2]=0,fe.HEAPU32[r>>2]=0,fe.HEAPU32[n>>2]=0,void(fe.HEAPU32[s>>2]=0);fe.HEAPU32[t>>2]=o.shader,fe.HEAPU32[r>>2]=o.blendMode;const{ptr:i,count:a}=Ce(o.uniforms);fe.HEAPU32[n>>2]=i,fe.HEAPU32[s>>2]=a},Se=!0}const Ae={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"};let Me=null,Re=0,Ee=0,Fe=0;const Ue=new Float32Array(256);function Ie(e){Me=e,Re=Me._malloc(64),Ee=Me._malloc(64),Fe=Me._malloc(1024)}function ze(){Me&&(Re&&(Me._free(Re),Re=0),Ee&&(Me._free(Ee),Ee=0),Fe&&(Me._free(Fe),Fe=0)),Me=null}function Be(){if(!Me)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Me}const We={x:1,y:1,z:1,w:1},$e={begin(e){const t=Be();t.HEAPF32.set(e,Re/4),t.draw_begin(Re)},end(){Be().draw_end()},line(e,t,r,n=1){Be().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){Be().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){Be().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){Be().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){Be().draw_circleOutline(e.x,e.y,t,r.x,r.y,r.z,r.w,n,s)},texture(e,t,r,n=We){Be().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=We){Be().draw_textureRotated(e.x,e.y,t.x,t.y,r,n,s.x,s.y,s.z,s.w)},setLayer(e){Be().draw_setLayer(e)},setDepth(e){Be().draw_setDepth(e)},getDrawCallCount:()=>Me?Me.draw_getDrawCallCount():0,getPrimitiveCount:()=>Me?Me.draw_getPrimitiveCount():0,setBlendMode(e){Be().draw_setBlendMode(e)},setDepthTest(e){Be().draw_setDepthTest(e)},drawMesh(e,t,r){const n=Be();n.HEAPF32.set(r,Ee/4),n.draw_mesh(e,t,Ee)},drawMeshWithMaterial(e,t,r){const n=Be(),s=ve.get(t);if(!s)return;if($e.setBlendMode(s.blendMode),$e.setDepthTest(s.depthTest),0===s.uniforms.size)return void $e.drawMesh(e,s.shader,r);n.HEAPF32.set(r,Ee/4);let o=0,i=0;for(const[e,t]of s.uniforms){const r=De(e);if(!(r<0)){if(pe(t))Ue[o++]=10,Ue[o++]=r,Ue[o++]=t.slot??i++,Ue[o++]=t.textureId;else if("number"==typeof t)Ue[o++]=1,Ue[o++]=r,Ue[o++]=t;else if(Array.isArray(t)){Ue[o++]=t.length,Ue[o++]=r;for(let e=0;e<t.length;e++)Ue[o++]=t[e]}else"w"in t?(Ue[o++]=4,Ue[o++]=r,Ue[o++]=t.x,Ue[o++]=t.y,Ue[o++]=t.z,Ue[o++]=t.w):"z"in t?(Ue[o++]=3,Ue[o++]=r,Ue[o++]=t.x,Ue[o++]=t.y,Ue[o++]=t.z):(Ue[o++]=2,Ue[o++]=r,Ue[o++]=t.x,Ue[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(n.HEAPF32.set(Ue.subarray(0,o),Fe/4),n.draw_meshWithUniforms(e,s.shader,Ee,Fe,o)):n.draw_mesh(e,s.shader,Ee)}},ke={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 De(e){return ke[e]??-1}var Le;exports.DataType=void 0,(Le=exports.DataType||(exports.DataType={}))[Le.Float=1]="Float",Le[Le.Float2=2]="Float2",Le[Le.Float3=3]="Float3",Le[Le.Float4=4]="Float4",Le[Le.Int=5]="Int",Le[Le.Int2=6]="Int2",Le[Le.Int3=7]="Int3",Le[Le.Int4=8]="Int4";let Oe=null,He=0,Ne=0,Ge=0;function Ve(e){Oe=e,He=Oe._malloc(262144),Ne=Oe._malloc(65536),Ge=Oe._malloc(256)}function je(){Oe&&(He&&Oe._free(He),Ne&&Oe._free(Ne),Ge&&Oe._free(Ge),He=0,Ne=0,Ge=0),Oe=null}function Xe(){if(!Oe)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Oe}const qe={create(e){const t=Xe(),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,He/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,Ge,s).set(o),t.geometry_init(r,He,n,Ge,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,Ne,n).set(e.indices),t.geometry_setIndices16(r,Ne,n)}else{new Uint32Array(t.HEAPU8.buffer,Ne,n).set(e.indices),t.geometry_setIndices32(r,Ne,n)}}return r},updateVertices(e,t,r=0){const n=Xe(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);n.HEAPF32.set(t,He/4),n.geometry_updateVertices(e,He,s,r)},release(e){e>0&&Xe().geometry_release(e)},isValid:e=>!(!Oe||e<=0)&&Oe.geometry_isValid(e),createQuad(e=1,t=1){const r=e/2,n=t/2;return qe.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,c=(Math.sin(s)+1)/2;r.push(o,i,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return qe.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 qe.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 Ye=null;function Ke(e){Ye=e}function Je(){Ye&&Ze.isInitialized()&&Ze.shutdown(),Ye=null}function Qe(){if(!Ye)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ye}const Ze={init:(e,t)=>Qe().postprocess_init(e,t),shutdown(){Qe().postprocess_shutdown()},resize(e,t){Qe().postprocess_resize(e,t)},addPass:(e,t)=>Qe().postprocess_addPass(e,t),removePass(e){Qe().postprocess_removePass(e)},setEnabled(e,t){Qe().postprocess_setPassEnabled(e,t)},isEnabled:e=>Qe().postprocess_isPassEnabled(e),setUniform(e,t,r){Qe().postprocess_setUniformFloat(e,t,r)},setUniformVec4(e,t,r){Qe().postprocess_setUniformVec4(e,t,r.x,r.y,r.z,r.w)},begin(){Qe().postprocess_begin()},end(){Qe().postprocess_end()},getPassCount:()=>Qe().postprocess_getPassCount(),isInitialized:()=>!!Ye&&Ye.postprocess_isInitialized(),setBypass(e){Qe().postprocess_setBypass(e)},isBypassed:()=>!Ye||Ye.postprocess_isBypassed(),createBlur:()=>ve.createShader(et,"#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:()=>ve.createShader(et,"#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:()=>ve.createShader(et,"#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:()=>ve.createShader(et,"#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")},et="#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 tt;exports.RenderStage=void 0,(tt=exports.RenderStage||(exports.RenderStage={}))[tt.Background=0]="Background",tt[tt.Opaque=1]="Opaque",tt[tt.Transparent=2]="Transparent",tt[tt.Overlay=3]="Overlay";let rt=null,nt=0;function st(e){rt=e,nt=rt._malloc(64)}function ot(){rt&&nt&&(rt._free(nt),nt=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&&nt&&(rt.HEAPF32.set(e,nt/4),rt.renderer_begin(nt,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,r=1)=>rt?.renderer_createTarget(e,t,r)??0,releaseRenderTarget(e){rt?.renderer_releaseTarget(e)},getTargetTexture:e=>rt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>rt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,r,n){rt?.renderer_setClearColor?.(e,t,r,n)},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 at=null;function ct(e){at=e}function lt(){at=null}const ut={enable(){at?.gl_enableErrorCheck(!0)},disable(){at?.gl_enableErrorCheck(!1)},check:e=>at?.gl_checkErrors(e)??0,diagnose(){at?.renderer_diagnose()}},ht=new Map;function dt(e){ht.delete(e)}class pt{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:r,width:n,height:s,elapsed:o}=e;it.resize(n,s),Ze.isInitialized()&&Ze.getPassCount()>0&&!Ze.isBypassed()&&Ze.resize(n,s),it.begin(r),it.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,o):it.submitSpine(t),it.flush();const i=ht;if(i.size>0){$e.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)}$e.end();for(const t of e)dt(t)}it.end()}}class ft{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=i(),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 ne,this.resources_=new H;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new ft}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 Q(this.world_,this.resources_),this.resources_.insert(N,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=i(),this.mainLoop())}quit(){this.running_=!1,lt(),ot(),Je(),je(),ye(),ze()}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(N),r={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(N,r)}}const xt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function _t(e,t){for(let r=0;r<t;r++){if(!e.valid(r)||!e.hasCanvas(r))continue;return e.getCanvas(r)}return null}function mt(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 gt(e,t,r,n,s,o){const i=new Float32Array(16),a=t-e,c=n-r,l=o-s;return i[0]=2/a,i[5]=2/c,i[10]=-2/l,i[12]=-(t+e)/a,i[13]=-(n+r)/c,i[14]=-(o+s)/l,i[15]=1,i}function yt(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 vt(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}class St{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&&(ve.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())ve.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await s(t))throw new Error(`Material file not found: ${t}`);const r=await n(t);if(!r)throw new Error(`Failed to read material file: ${t}`);const o=JSON.parse(r);if("material"!==o.type)throw new Error(`Invalid material file type: ${o.type}`);const i=this.resolveShaderPath(e,o.shader),a=await this.shaderLoader_.load(i);return{handle:ve.createFromAsset(o,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 Tt(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)Ct(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 Pt(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}}Ct(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 Ct(e,t,r){const n=r.data;switch(r.type){case"LocalTransform":e.insert(t,R,n);break;case"Sprite":e.insert(t,F,n);break;case"Camera":e.insert(t,U,n);break;case"Canvas":e.insert(t,I,n);break;case"Text":e.insert(t,ae,n);break;case"SpineAnimation":e.insert(t,$,n);break;case"UIRect":e.insert(t,le,n);break;default:{const s=C(r.type);s?e.insert(t,s,n):console.warn(`Unknown component type: ${r.type}`);break}}}class bt{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 At{constructor(e){this.textureCache_=new bt,this.shaderCache_=new bt,this.jsonCache_=new bt,this.textCache_=new bt,this.binaryCache_=new bt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.module_=e,this.canvas_=o(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 St(t)}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 fetch(s);if(!o.ok)return{success:!1,error:`Failed to fetch atlas: ${s}`};const i=await o.text();if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const a=t.substring(0,t.lastIndexOf("/")),c=this.parseAtlasTextures(i);for(const e of c){const t=a?`${a}/${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),u=await fetch(l);if(!u.ok)return{success:!1,error:`Failed to fetch skeleton: ${l}`};const h=e.endsWith(".skel")?new Uint8Array(await u.arrayBuffer()):await u.text();return this.writeToVirtualFS(e,h)?(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 Pt(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},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){return new Promise((t,r)=>{const n=new Image;n.crossOrigin="anonymous",n.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(n,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void t(e)}catch{}t(n)},n.onerror=()=>r(new Error(`Failed to load image: ${e}`)),n.src=e})}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_.save(),n&&(this.ctx_.translate(0,r),this.ctx_.scale(1,-1)),this.ctx_.drawImage(e,0,0),this.ctx_.restore();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 c=i.createTexture(t,r,a,o.length,1);return this.module_._free(a),{handle:c,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){if(!await s(e))throw new Error(`Shader file not found: ${e}`);const t=await n(e);if(!t)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:o}=this.parseEsShader(t);if(!r||!o)throw new Error(`Invalid shader format: ${e}`);return ve.createShader(r,o)}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}}async fetchJson(e){const t=await r(e);if(!t.ok)throw new Error(`Failed to fetch JSON: ${e} (${t.status})`);return t.json()}async fetchText(e){const t=await r(e);if(!t.ok)throw new Error(`Failed to fetch text: ${e} (${t.status})`);return t.text()}async fetchBinary(e){const t=await r(e);if(!t.ok)throw new Error(`Failed to fetch binary: ${e} (${t.status})`);return t.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 Mt=L(null,"Assets");class Rt{build(e){const t=e.wasmModule;t?e.insertResource(Mt,new At(t)):console.warn("AssetPlugin: No WASM module available")}}const Et=new Rt;function Ft(e,t){const r=e.getResourceManager(),n=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,n);const s=r.createTexture(t.width,t.height,n,t.pixels.length,1);return e._free(n),s}function Ut(e,t){const r=t.substring(0,t.lastIndexOf("/"));r&&e.FS.mkdirTree(r)}function It(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}const zt={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),r=it.createRenderTarget(e.width,e.height,t);return{_handle:r,textureId:it.getTargetTexture(r),width:e.width,height:e.height}},release(e){it.releaseRenderTarget(e._handle)},resize:(e,t,r)=>(it.releaseRenderTarget(e._handle),zt.create({width:t,height:r,depth:!0})),begin(e,t){it.begin(t,e._handle)},end(){it.end()},getDepthTexture:e=>it.getTargetDepthTexture(e._handle)};let Bt=!1;var Wt;g||(g=!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 a(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=Wt=y,console.log(`[ESEngine] Platform: ${Wt.name}`),exports.App=ft,exports.AssetPlugin=Rt,exports.AssetServer=At,exports.Assets=Mt,exports.AsyncCache=bt,exports.Camera=U,exports.Canvas=I,exports.Children=W,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=X,exports.Draw=$e,exports.EntityCommands=j,exports.GLDebug=ut,exports.Geometry=qe,exports.INVALID_ENTITY=0,exports.INVALID_TEXTURE=w,exports.Input=ee,exports.InputPlugin=te,exports.InputState=Z,exports.LocalTransform=R,exports.Material=ve,exports.MaterialLoader=St,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Parent=B,exports.PostProcess=Ze,exports.PreviewPlugin=class{constructor(e){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e}build(e){this.app_=e,e.hasResource(Mt)||e.addPlugin(Et),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=this.app_.getResource(Mt);await n.loadScene(this.app_.world,t),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([U]);for(const n of r){if(e.get(n,U).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([I]);for(const s of n){const n=e.get(s,I);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,R,o);const i={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:r,priority:0,showFrustum:!0};e.insert(s,U,i)}}},exports.Query=function(...e){return function(e,t=[],r=[]){const n=[];return e.forEach((e,t)=>{G(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:r}}(e)},exports.QueryInstance=V,exports.RenderPipeline=pt,exports.RenderTexture=zt,exports.Renderer=it,exports.Res=function(e){return{_type:"res",_resource:e}},exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.ShaderSources=Ae,exports.SpineAnimation=$,exports.Sprite=F,exports.SystemRunner=Q,exports.Text=ae,exports.TextPlugin=ue,exports.TextRenderer=ce,exports.Time=N,exports.UIRect=le,exports.Velocity=z,exports.World=ne,exports.WorldTransform=E,exports.addStartupSystem=function(e){J().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){J().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){J().push({schedule:e,system:t})},exports.assetPlugin=Et,exports.clearDrawCallbacks=function(){ht.clear()},exports.clearUserComponents=function(){T().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=ft.new(),n=new e.Registry;r.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ie(e),ge(e),Ve(e),Ke(e),st(e),ct(e);const s=new pt;r.pipeline_=s;let o=i();const a=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:e,height:t}=a(),r=function(e,t,r){const n=e.entityCount()+1e3;for(let s=0;s<n;s++){if(!e.valid(s)||!e.hasCamera(s)||!e.hasLocalTransform(s))continue;const o=e.getCamera(s);if(!o.isActive)continue;const i=e.getLocalTransform(s),a=t/r;let c;if(1===o.projectionType){let t=o.orthoSize;const r=_t(e,n);if(r){t=mt(r.designResolution.y/2,r.designResolution.x/r.designResolution.y,a,r.scaleMode,r.matchWidthOrHeight)}const s=t*a;c=gt(-s,s,-t,t,-o.farPlane,o.farPlane)}else c=yt(o.fov*Math.PI/180,a,o.nearPlane,o.farPlane);return vt(c,wt(i.position.x,i.position.y,i.position.z))}return xt}(n,e,t),c=(i()-o)/1e3;s.render({registry:{_cpp:n},viewProjection:r,width:e,height:t,elapsed:c})}};return r.addSystemToSchedule(exports.Schedule.Last,c),r.addPlugin(re),r.addPlugin(he),r},exports.defineComponent=P,exports.defineResource=L,exports.defineSystem=K,exports.defineTag=function(e){const t=T(),r=t.get(e);if(r)return r;const n=S(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=k[e];if(t)return{...t._default};const r=C(e);return r?{...r._default}:null},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=C,exports.initDrawAPI=Ie,exports.initGLDebugAPI=ct,exports.initGeometryAPI=Ve,exports.initMaterialAPI=ge,exports.initPostProcessAPI=Ke,exports.initRendererAPI=st,exports.inputPlugin=re,exports.isBuiltinComponent=M,exports.isEditor=function(){return Bt},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!Bt},exports.isTextureRef=pe,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=Ct,exports.loadRuntimeScene=async function(e,t,r,n,s){const o=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]=Ft(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,o);let i={};s&&(i=await async function(e,t,r,n){const s={};for(const o of r.entities)for(const r of o.components){if("SpineAnimation"!==r.type||!r.data)continue;const o=r.data.skeletonPath,i=r.data.atlasPath;if(!o||!i)continue;const a=n.resolvePath(o),c=n.resolvePath(i);try{const r=n.readText(i),l=a.endsWith(".skel");Ut(t,a),l?t.FS.writeFile(a,n.readBinary(o)):t.FS.writeFile(a,n.readText(o));const u=t.spine_loadSkeleton(a,r,r.length,l);if(u<0)continue;s[o]=u;const h=It(r),d=c.substring(0,c.lastIndexOf("/"));for(let r=0;r<h.length;r++){const s=d+"/"+h[r];try{const o=n.loadPixelsRaw??n.loadPixels,i=await o(s),a=Ft(e,i),c=e.getResourceManager().getTextureGLId(a);t.spine_setAtlasPageTexture(u,r,c,i.width,i.height)}catch{}}}catch{}}return s}(t,s,r,n));const a=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=ve.createShader(e.vertexSource,e.fragmentSource),n[o]=i),r[s]=ve.createFromAsset(e,i)}catch{r[s]=0}}return r}(r,n),c=Tt(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,F);s&&(s.texture=r[n.data.texture]||0,e.insert(t,F,s))}}}(e.world,r,o,c),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,F);r&&(r.material=s,e.insert(t,F,r))}else if("SpineAnimation"===n.type){const r=e.get(t,$);r&&(r.material=s,e.insert(t,$,r))}}}}(e.world,r,a,c),s){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.spine_createInstance(i);if(a<0)continue;const c=n.get(o.id);void 0!==c&&(s[c]=a),t.data.animation&&e.spine_playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.spine_setSkin(a,t.data.skin)}return s}(s,r,i,c);!function(e,t,r,n){if(0===Object.keys(n).length)return;let s=0;e.setSpineRenderer((e,o)=>{let i=o-s;s=o,(i<=0||i>.5)&&(i=1/60);for(const e in n){const s=n[e];r.spine_update(s,i);const o=r.spine_getMeshBatchCount(s);for(let e=0;e<o;e++){const n=r.spine_getMeshBatchVertexCount(s,e),o=r.spine_getMeshBatchIndexCount(s,e);if(!n||!o)continue;const i=8*n*4,a=2*o,c=r._malloc(i),l=r._malloc(a),u=r._malloc(4),h=r._malloc(4);r.spine_getMeshBatchData(s,e,c,l,u,h);const d=r.HEAPU32[u>>2],p=r.HEAPU32[h>>2],f=new Float32Array(r.HEAPF32.buffer,c,8*n),x=new Uint16Array(r.HEAPU8.buffer,l,o),_=t._malloc(i),m=t._malloc(a);t.HEAPF32.set(f,_>>2),new Uint16Array(t.HEAPU8.buffer,m,o).set(x),t.renderer_submitTriangles(_,n,m,o,d,p,0),t._free(_),t._free(m),r._free(c),r._free(l),r._free(u),r._free(h)}}})}(e,t,s,n)}},exports.loadSceneData=Tt,exports.loadSceneWithAssets=Pt,exports.platformFetch=r,exports.platformFileExists=s,exports.platformInstantiateWasm=async function(e,r){return t().instantiateWasm(e,r)},exports.platformReadFile=async function(e){return t().readFile(e)},exports.platformReadTextFile=n,exports.quat=(e=1,t=0,r=0,n=0)=>({w:e,x:t,y:r,z:n}),exports.registerDrawCallback=function(e,t){ht.set(e,t)},exports.registerMaterialCallback=be,exports.setEditorMode=function(e){Bt=e},exports.shutdownDrawAPI=ze,exports.shutdownGLDebugAPI=lt,exports.shutdownGeometryAPI=je,exports.shutdownMaterialAPI=ye,exports.shutdownPostProcessAPI=Je,exports.shutdownRendererAPI=ot,exports.textPlugin=he,exports.unregisterDrawCallback=dt,exports.updateCameraAspectRatio=function(e,t){const r=e.getEntitiesWithComponents([U]);for(const n of r){const r=e.get(n,U);r&&(r.aspectRatio=t,e.insert(n,U,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=p,exports.wxFileExistsSync=function(e){const t=u();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=m,exports.wxLoadImage=_,exports.wxLoadImagePixels=async function(e,t=!0){return m(await _(e),t)},exports.wxReadFile=h,exports.wxReadTextFile=d,exports.wxWriteFile=function(e,t){return new Promise((r,n)=>{u().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 s(e){return t().readTextFile(e)}async function n(e){return t().fileExists(e)}function o(e,r){return t().createCanvas(e,r)}function i(){return t().now()}function a(e,t){return new Promise((r,s)=>{const n=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===n?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];r({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,r="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(r).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function c(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const r=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(r,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${r}": ${t}`)}}let l=null;function u(){return l||(l=wx.getFileSystemManager()),l}function h(e){return new Promise((t,r)=>{u().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function d(e,t="utf-8"){return new Promise((r,s)=>{u().readFile({filePath:e,encoding:t,success:e=>{r(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function p(e){return new Promise(t=>{u().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}let f=null,x=null;function _(e){return new Promise((t,r)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>r(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function m(e,t=!0){const{width:r,height:s}=e,{ctx:n}=function(e,t){return f||(f=wx.createCanvas(),f.width=e,f.height=t,x=f.getContext("2d")),(f.width<e||f.height<t)&&(f.width=Math.max(f.width,e),f.height=Math.max(f.height,t)),{canvas:f,ctx:x}}(r,s);n.clearRect(0,0,r,s),n.save(),t&&(n.translate(0,s),n.scale(1,-1)),n.drawImage(e,0,0),n.restore();const o=n.getImageData(0,0,r,s);return{width:r,height:s,pixels:new Uint8Array(o.data.buffer)}}let g=!1;const y=new class{constructor(){this.name="wechat"}async fetch(e,t){return a(e,t)}async readFile(e){return h(e)}async readTextFile(e){return d(e)}async fileExists(e){return p(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)}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)})}},w=4294967295;let v=0;function S(e,t){const r=++v;return{_id:Symbol(`Component_${r}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function P(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function T(e,t){const r=P(),s=r.get(e);if(s)return s;const n=S(e,t);return r.set(e,n),b(e,t,!1),n}function C(e){return P().get(e)}function b(e,t,r){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,r)}function A(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function M(e){return!0===e._builtin}const R=A("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),E=A("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),F=A("Sprite",{texture:w,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}),U=A("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0}),I=A("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),W=A("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),B=A("Parent",{entity:0}),z=A("Children",{entities:[]}),$=A("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}),k={LocalTransform:R,WorldTransform:E,Sprite:F,Camera:U,Canvas:I,Velocity:W,Parent:B,Children:z,SpineAnimation:$};let D=0;function L(e,t){const r=++D;return{_id:Symbol(`Resource_${r}_${t??""}`),_name:t??`Resource_${r}`,_default:e}}class O{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 H{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 O(this.get(e),t=>this.set(e,t))}}const N=L({delta:0,elapsed:0,frameCount:0},"Time");function G(e){return"object"==typeof e&&null!==e&&"mut"===e._type}class V{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return G(e)?e._component:e}commitPending(){for(const e of this.pendingMutations_)this.world_.insert(e.entity,e.component,e.data);this.pendingMutations_=[]}*[Symbol.iterator](){const{_components:e,_mutIndices:t,_with:r,_without:s}=this.descriptor_,n=e.map(e=>this.getActualComponent(e)),o=[...n,...r],i=this.world_.getEntitiesWithComponents(o);let a=null,c=[];try{for(const e of i){if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data);c=[];let r=!1;for(const t of s)if(this.world_.has(e,t)){r=!0;break}if(r)continue;const o=n.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:n[e],data:o[e]});a=e,yield[e,...o]}}finally{if(null!==a)for(const e of c)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 j{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=M(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 X{constructor(e,t){this.pending_=[],this.world_=e,this.resources_=t}spawn(){return new j(this,null)}entity(e){return new j(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.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 q;exports.Schedule=void 0,(q=exports.Schedule||(exports.Schedule={}))[q.Startup=0]="Startup",q[q.First=1]="First",q[q.PreUpdate=2]="PreUpdate",q[q.Update=3]="Update",q[q.PostUpdate=4]="PostUpdate",q[q.Last=5]="Last",q[q.FixedPreUpdate=10]="FixedPreUpdate",q[q.FixedUpdate=11]="FixedUpdate",q[q.FixedPostUpdate=12]="FixedPostUpdate";let Y=0;function K(e,t,r){const s=++Y;return{_id:Symbol(`System_${s}_${r?.name??""}`),_params:e,_fn:t,_name:r?.name??`System_${s}`}}function J(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class Q{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 X&&e.flush()}resolveParam(e){switch(e._type){case"query":return new V(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new X(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Z{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 ee=L(new Z,"Input");class te{constructor(e){this.target_=e??null}build(e){const r=new Z;e.insertResource(ee,r),t().bindInputEvents({onKeyDown(e){r.keysDown.has(e)||r.keysPressed.add(e),r.keysDown.add(e)},onKeyUp(e){r.keysDown.delete(e),r.keysReleased.add(e)},onPointerMove(e,t){r.mouseX=e,r.mouseY=t},onPointerDown(e,t,s){r.mouseX=t,r.mouseY=s,r.mouseButtons.add(e),r.mouseButtonsPressed.add(e)},onPointerUp(e){r.mouseButtons.delete(e),r.mouseButtonsReleased.add(e)},onWheel(e,t){r.scrollDeltaX+=e,r.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.First,K([],()=>{r.keysPressed.clear(),r.keysReleased.clear(),r.mouseButtonsPressed.clear(),r.mouseButtonsReleased.clear(),r.scrollDeltaX=0,r.scrollDeltaY=0},{name:"InputClearSystem"}))}}const re=new te;class se{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 M(t)?this.insertBuiltin(e,t,r):this.insertScript(e,t,r)}get(e,t){return M(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return M(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){M(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,r){const s={...t._default,...r};if(this.cppRegistry_){const r=`add${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e,s)}return s}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const r=`get${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const r=`has${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const r=`remove${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e)}insertScript(e,t,r){const s=t.create(r);return this.getStorage(t).set(e,s),s}getScript(e,t){const r=this.tsStorage_.get(t._id);if(!r)throw new Error(`Component not found: ${t._name}`);return r.get(e)}hasScript(e,t){const r=this.tsStorage_.get(t._id);return r?.has(e)??!1}removeScript(e,t){const r=this.tsStorage_.get(t._id);r?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=[];for(const r of this.entities_){let s=!0;for(const t of e)if(!this.has(r,t)){s=!1;break}s&&t.push(r)}return t}}var ne,oe,ie;exports.TextAlign=void 0,(ne=exports.TextAlign||(exports.TextAlign={}))[ne.Left=0]="Left",ne[ne.Center=1]="Center",ne[ne.Right=2]="Right",exports.TextVerticalAlign=void 0,(oe=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[oe.Top=0]="Top",oe[oe.Middle=1]="Middle",oe[oe.Bottom=2]="Bottom",exports.TextOverflow=void 0,(ie=exports.TextOverflow||(exports.TextOverflow={}))[ie.Visible=0]="Visible",ie[ie.Clip=1]="Clip",ie[ie.Ellipsis=2]="Ellipsis";const ae=T("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 ce{constructor(e){this.cache=new Map,this.module=e,this.canvas=o(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const r=this.ctx,s=this.canvas;r.font=`${e.fontSize}px ${e.fontFamily}`;const n=t&&t.size.x>0&&t.size.y>0,o=n?t.size.x:0,i=n?t.size.y:0,a=e.wordWrap&&n;let c=this.wrapText(e.content,a?o: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),p=n?Math.ceil(o):h+2*u,f=n?Math.ceil(i):d+2*u;if(n&&e.overflow===exports.TextOverflow.Ellipsis&&d>i){const e=Math.floor(i/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<p||s.height<f){const e=Math.max(s.width,this.nextPowerOf2(p)),t=Math.max(s.height,this.nextPowerOf2(f));s.width=e,s.height=t}const x=Math.round(255*e.color.x),_=Math.round(255*e.color.y),m=Math.round(255*e.color.z),g=e.color.w;r.clearRect(0,0,s.width,s.height),r.font=`${e.fontSize}px ${e.fontFamily}`,r.textAlign=this.mapAlign(e.align),r.textBaseline="top",r.fillStyle=`rgba(${x}, ${_}, ${m}, ${g})`,n&&e.overflow===exports.TextOverflow.Clip&&(r.save(),r.beginPath(),r.rect(0,0,p,f),r.clip());const y=c.length*l;let w;if(n)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-y)/2;break;case exports.TextVerticalAlign.Bottom:w=f-y-u;break;default:w=u}else w=u;let v=w;for(const t of c){let s;switch(e.align){case exports.TextAlign.Left:s=u;break;case exports.TextAlign.Center:s=p/2;break;case exports.TextAlign.Right:s=p-u;break;default:s=u}r.fillText(t,s,v),v+=l}n&&e.overflow===exports.TextOverflow.Clip&&r.restore();const S=r.getImageData(0,0,p,f),P=new Uint8Array(S.data.buffer),T=this.flipVertically(P,p,f),C=this.module.getResourceManager(),b=this.module._malloc(T.length);this.module.HEAPU8.set(T,b);const A=C.createTexture(p,f,b,T.length,1);return this.module._free(b),{textureHandle:A,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let r=e;for(;r.length>0&&this.ctx.measureText(r+"...").width>t;)r=r.slice(0,-1);return r+"..."}renderForEntity(e,t,r){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const n=this.renderText(t,r);return this.cache.set(e,n),n}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const r=e.split("\n"),s=[];for(const e of r){if(!e){s.push("");continue}let r="";for(const n of e){const e=r+n;this.ctx.measureText(e).width>t&&r?(s.push(r),r=n):r=e}r&&s.push(r)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const r of e){const e=this.ctx.measureText(r),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}flipVertically(e,t,r){const s=4*t,n=new Uint8Array(e.length);for(let t=0;t<r;t++){const o=t*s,i=(r-1-t)*s;n.set(e.subarray(o,o+s),i)}return n}}const le=T("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class ue{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const r=new ce(t),s=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,K([],()=>{const e=s.getEntitiesWithComponents([ae]);for(const t of e){const e=s.get(t,ae);if(!e.dirty)continue;s.has(t,F)||s.insert(t,F,{texture:w,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 n=s.has(t,le)?s.get(t,le):null,o=r.renderForEntity(t,e,n),i=s.get(t,F);i.texture=o.textureHandle,i.size={x:o.width,y:o.height},i.uvOffset={x:0,y:0},i.uvScale={x:1,y:1},s.insert(t,F,i),e.dirty=!1}}))}}const he=new ue;var de;function pe(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(de=exports.BlendMode||(exports.BlendMode={}))[de.Normal=0]="Normal",de[de.Additive=1]="Additive",de[de.Multiply=2]="Multiply",de[de.Screen=3]="Screen",de[de.PremultipliedAlpha=4]="PremultipliedAlpha";let fe=null,xe=null,_e=1;const me=new Map;function ge(e){fe=e,xe=e.getResourceManager(),be()}function ye(){0!==Pe&&fe&&(fe._free(Pe),Pe=0),me.clear(),_e=1,Se=!1,xe=null,fe=null}function we(){if(!xe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return xe}const ve={createShader:(e,t)=>we().createShader(e,t),releaseShader(e){e>0&&we().releaseShader(e)},create(e){const t=_e++,r={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))r.uniforms.set(t,s);return me.set(t,r),t},get:e=>me.get(e),setUniform(e,t,r){const s=me.get(e);s&&s.uniforms.set(t,r)},getUniform(e,t){const r=me.get(e);return r?.uniforms.get(t)},setBlendMode(e,t){const r=me.get(e);r&&(r.blendMode=t)},getBlendMode(e){const t=me.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const r=me.get(e);r&&(r.depthTest=t)},getShader(e){const t=me.get(e);return t?.shader??0},release(e){me.delete(e)},isValid:e=>me.has(e),createFromAsset(e,t){const r={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)r[t]=s;else if("object"==typeof s&&null!==s){const e=s;"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=me.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const r=_e++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return me.set(r,s),r},toAssetData(e,t){const r=me.get(e);if(!r)return null;const s={};for(const[e,t]of r.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:r.blendMode,depthTest:r.depthTest,properties:s}},getUniforms(e){const t=me.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Se=!1,Pe=0;const Te=4096;function Ce(e){const t=(0===Pe&&fe&&(Pe=fe._malloc(Te)),Pe);if(0===t||!fe)return{ptr:0,count:0};let r=0,s=0;const n=fe.HEAPU8,o=fe.HEAPU32,i=fe.HEAPF32;for(const[a,c]of e){if(r+128>Te)break;const e=(new TextEncoder).encode(a),l=e.length,u=4*Math.ceil(l/4);o[t+r>>2]=l,r+=4,n.set(e,t+r),r+=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]);o[t+r>>2]=h,r+=4;for(let e=0;e<4;e++)i[t+r>>2]=d[e],r+=4;s++}return{ptr:t,count:s}}function be(){if(!fe||Se)return;fe.materialDataProvider=(e,t,r,s,n)=>{const o=me.get(e);if(!o)return fe.HEAPU32[t>>2]=0,fe.HEAPU32[r>>2]=0,fe.HEAPU32[s>>2]=0,void(fe.HEAPU32[n>>2]=0);fe.HEAPU32[t>>2]=o.shader,fe.HEAPU32[r>>2]=o.blendMode;const{ptr:i,count:a}=Ce(o.uniforms);fe.HEAPU32[s>>2]=i,fe.HEAPU32[n>>2]=a},Se=!0}const Ae={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 Me{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const r=this.pending_.get(e);if(r)return r;const s=this.loadInternal(e);this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(ve.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())ve.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await n(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 o=JSON.parse(r);if("material"!==o.type)throw new Error(`Invalid material file type: ${o.type}`);const i=this.resolveShaderPath(e,o.shader),a=await this.shaderLoader_.load(i);return{handle:ve.createFromAsset(o,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 Re(e,t){const r=new Map;for(const s of t.entities){const t=e.spawn();r.set(s.id,t);for(const r of s.components)Fe(e,t,r)}for(const s of t.entities)if(null!==s.parent){const t=r.get(s.id),n=r.get(s.parent);void 0!==t&&void 0!==n&&e.setParent(t,n)}return r}async function Ee(e,t,r){const s=new Map,n=r?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();s.set(i.id,t);for(const s of i.components){if("Sprite"===s.type&&n){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:r?.assetBaseUrl?`${r.assetBaseUrl}/${t}`:`/${t}`;try{const r=await n.loadTexture(s);e.texture=r.handle,o.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("SpineAnimation"===s.type&&n){const e=s.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await n.loadSpine(t,o,r?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Fe(e,t,s)}}for(const r of t.entities)if(null!==r.parent){const t=s.get(r.id),n=s.get(r.parent);void 0!==t&&void 0!==n&&e.setParent(t,n)}if(n&&t.textureMetadata)for(const[e,r]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&r.sliceBorder&&n.setTextureMetadataByPath(t,r.sliceBorder)}return s}function Fe(e,t,r){const s=r.data;switch(r.type){case"LocalTransform":e.insert(t,R,s);break;case"Sprite":e.insert(t,F,s);break;case"Camera":e.insert(t,U,s);break;case"Canvas":e.insert(t,I,s);break;case"Text":e.insert(t,ae,s);break;case"SpineAnimation":e.insert(t,$,s);break;case"UIRect":e.insert(t,le,s);break;default:{const n=C(r.type);n?e.insert(t,n,s):console.warn(`Unknown component type: ${r.type}`);break}}}class Ue{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const r=this.cache_.get(e);if(void 0!==r)return r;const s=this.pending_.get(e);if(s)return s;const n=t();this.pending_.set(e,n);try{const t=await n;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class Ie{constructor(e){this.textureCache_=new Ue,this.shaderCache_=new Ue,this.jsonCache_=new Ue,this.textCache_=new Ue,this.binaryCache_=new Ue,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.module_=e,this.canvas_=o(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 Me(t)}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const r of[!0,!1]){const s=this.textureCacheKey(e,r),n=this.textureCache_.get(s);n&&(t.releaseTexture(n.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);this.textureCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear()}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const r=this.textureCache_.get(this.textureCacheKey(e,!0));return!!r&&(this.setTextureMetadata(r.handle,t),!0)}async loadSpine(e,t,r){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const n=this.resolveUrl(t,r),o=await fetch(n);if(!o.ok)return{success:!1,error:`Failed to fetch atlas: ${n}`};const i=await o.text();if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const a=t.substring(0,t.lastIndexOf("/")),c=this.parseAtlasTextures(i);for(const e of c){const t=a?`${a}/${e}`:e,s=this.resolveUrl(t,r);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,r),u=await fetch(l);if(!u.ok)return{success:!1,error:`Failed to fetch skeleton: ${l}`};const h=e.endsWith(".skel")?new Uint8Array(await u.arrayBuffer()):await u.text();return this.writeToVirtualFS(e,h)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(r):this.jsonCache_.getOrLoad(r,()=>this.fetchJson(r))}async loadText(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(r):this.textCache_.getOrLoad(r,()=>this.fetchText(r))}async loadBinary(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(r):this.binaryCache_.getOrLoad(r,()=>this.fetchBinary(r))}async loadScene(e,t){return Ee(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},r=[];if(e.textures)for(const s of e.textures)r.push(this.loadTexture(s).then(e=>{t.textures.set(s,e)}));if(e.materials)for(const s of e.materials)r.push(this.loadMaterial(s).then(e=>{t.materials.set(s,e)}));if(e.spine)for(const s of e.spine){const e=`${s.skeleton}:${s.atlas}`;r.push(this.loadSpine(s.skeleton,s.atlas,s.baseUrl).then(r=>{t.spine.set(e,r)}))}if(e.json)for(const s of e.json)r.push(this.loadJson(s).then(e=>{t.json.set(s,e)}));if(e.text)for(const s of e.text)r.push(this.loadText(s).then(e=>{t.text.set(s,e)}));if(e.binary)for(const s of e.binary)r.push(this.loadBinary(s).then(e=>{t.binary.set(s,e)}));return await Promise.all(r),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const r=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(r,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const r=await this.loadImage(e);return this.createTextureFromImage(r,t)}async loadImage(e){return new Promise((t,r)=>{const s=new Image;s.crossOrigin="anonymous",s.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(s,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void t(e)}catch{}t(s)},s.onerror=()=>r(new Error(`Failed to load image: ${e}`)),s.src=e})}createTextureFromImage(e,t){const{width:r,height:s}=e,n=this.getWebGL2Context();return n?this.createTextureWebGL2(n,e,r,s,t):this.createTextureFallback(e,r,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,r,s,n){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,n?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,r,s),width:r,height:s}}createTextureFallback(e,t,r,s){(this.canvas_.width<t||this.canvas_.height<r)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(r))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.save(),s&&(this.ctx_.translate(0,r),this.ctx_.scale(1,-1)),this.ctx_.drawImage(e,0,0),this.ctx_.restore();const n=this.ctx_.getImageData(0,0,t,r),o=new Uint8Array(n.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const c=i.createTexture(t,r,a,o.length,1);return this.module_._free(a),{handle:c,width:t,height:r}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const r=e[t+3];if(r>0&&r<255){const s=255/r;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){if(!await n(e))throw new Error(`Shader file not found: ${e}`);const t=await s(e);if(!t)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:o}=this.parseEsShader(t);if(!r||!o)throw new Error(`Invalid shader format: ${e}`);return ve.createShader(r,o)}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}}async fetchJson(e){const t=await r(e);if(!t.ok)throw new Error(`Failed to fetch JSON: ${e} (${t.status})`);return t.json()}async fetchText(e){const t=await r(e);if(!t.ok)throw new Error(`Failed to fetch text: ${e} (${t.status})`);return t.text()}async fetchBinary(e){const t=await r(e);if(!t.ok)throw new Error(`Failed to fetch binary: ${e} (${t.status})`);return t.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const r=this.module_.FS;if(!r)return!1;try{return this.ensureVirtualDir(e),r.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const r=e.substring(0,e.lastIndexOf("/"));if(!r)return;const s=r.split("/").filter(e=>e);let n="";for(const e of s){n=n?`${n}/${e}`:e;try{t.analyzePath(n).exists||t.mkdir(n)}catch{try{t.mkdir(n)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const r=t??this.baseUrl;return r?`${r}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const We=L(null,"Assets");class Be{build(e){const t=e.wasmModule;t?e.insertResource(We,new Ie(t)):console.warn("AssetPlugin: No WASM module available")}}const ze=new Be;let $e=null,ke=0,De=0,Le=0;const Oe=new Float32Array(256);function He(e){$e=e,ke=$e._malloc(64),De=$e._malloc(64),Le=$e._malloc(1024)}function Ne(){$e&&(ke&&($e._free(ke),ke=0),De&&($e._free(De),De=0),Le&&($e._free(Le),Le=0)),$e=null}function Ge(){if(!$e)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return $e}const Ve={x:1,y:1,z:1,w:1},je={begin(e){const t=Ge();t.HEAPF32.set(e,ke/4),t.draw_begin(ke)},end(){Ge().draw_end()},line(e,t,r,s=1){Ge().draw_line(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,s)},rect(e,t,r,s=!0){Ge().draw_rect(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,s)},rectOutline(e,t,r,s=1){Ge().draw_rectOutline(e.x,e.y,t.x,t.y,r.x,r.y,r.z,r.w,s)},circle(e,t,r,s=!0,n=32){Ge().draw_circle(e.x,e.y,t,r.x,r.y,r.z,r.w,s,n)},circleOutline(e,t,r,s=1,n=32){Ge().draw_circleOutline(e.x,e.y,t,r.x,r.y,r.z,r.w,s,n)},texture(e,t,r,s=Ve){Ge().draw_texture(e.x,e.y,t.x,t.y,r,s.x,s.y,s.z,s.w)},textureRotated(e,t,r,s,n=Ve){Ge().draw_textureRotated(e.x,e.y,t.x,t.y,r,s,n.x,n.y,n.z,n.w)},setLayer(e){Ge().draw_setLayer(e)},setDepth(e){Ge().draw_setDepth(e)},getDrawCallCount:()=>$e?$e.draw_getDrawCallCount():0,getPrimitiveCount:()=>$e?$e.draw_getPrimitiveCount():0,setBlendMode(e){Ge().draw_setBlendMode(e)},setDepthTest(e){Ge().draw_setDepthTest(e)},drawMesh(e,t,r){const s=Ge();s.HEAPF32.set(r,De/4),s.draw_mesh(e,t,De)},drawMeshWithMaterial(e,t,r){const s=Ge(),n=ve.get(t);if(!n)return;if(je.setBlendMode(n.blendMode),je.setDepthTest(n.depthTest),0===n.uniforms.size)return void je.drawMesh(e,n.shader,r);s.HEAPF32.set(r,De/4);let o=0,i=0;for(const[e,t]of n.uniforms){const r=qe(e);if(!(r<0)){if(pe(t))Oe[o++]=10,Oe[o++]=r,Oe[o++]=t.slot??i++,Oe[o++]=t.textureId;else if("number"==typeof t)Oe[o++]=1,Oe[o++]=r,Oe[o++]=t;else if(Array.isArray(t)){Oe[o++]=t.length,Oe[o++]=r;for(let e=0;e<t.length;e++)Oe[o++]=t[e]}else"w"in t?(Oe[o++]=4,Oe[o++]=r,Oe[o++]=t.x,Oe[o++]=t.y,Oe[o++]=t.z,Oe[o++]=t.w):"z"in t?(Oe[o++]=3,Oe[o++]=r,Oe[o++]=t.x,Oe[o++]=t.y,Oe[o++]=t.z):(Oe[o++]=2,Oe[o++]=r,Oe[o++]=t.x,Oe[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(Oe.subarray(0,o),Le/4),s.draw_meshWithUniforms(e,n.shader,De,Le,o)):s.draw_mesh(e,n.shader,De)}},Xe={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 qe(e){return Xe[e]??-1}var Ye;exports.DataType=void 0,(Ye=exports.DataType||(exports.DataType={}))[Ye.Float=1]="Float",Ye[Ye.Float2=2]="Float2",Ye[Ye.Float3=3]="Float3",Ye[Ye.Float4=4]="Float4",Ye[Ye.Int=5]="Int",Ye[Ye.Int2=6]="Int2",Ye[Ye.Int3=7]="Int3",Ye[Ye.Int4=8]="Int4";let Ke=null,Je=0,Qe=0,Ze=0;function et(e){Ke=e,Je=Ke._malloc(262144),Qe=Ke._malloc(65536),Ze=Ke._malloc(256)}function tt(){Ke&&(Je&&Ke._free(Je),Qe&&Ke._free(Qe),Ze&&Ke._free(Ze),Je=0,Qe=0,Ze=0),Ke=null}function rt(){if(!Ke)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Ke}const st={create(e){const t=rt(),r=t.geometry_create();if(0===r)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,Je/4);const n=e.layout.length,o=new Int32Array(n);for(let t=0;t<n;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Ze,n).set(o),t.geometry_init(r,Je,s,Ze,n,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Qe,s).set(e.indices),t.geometry_setIndices16(r,Qe,s)}else{new Uint32Array(t.HEAPU8.buffer,Qe,s).set(e.indices),t.geometry_setIndices32(r,Qe,s)}}return r},updateVertices(e,t,r=0){const s=rt(),n=t.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);s.HEAPF32.set(t,Je/4),s.geometry_updateVertices(e,Je,n,r)},release(e){e>0&&rt().geometry_release(e)},isValid:e=>!(!Ke||e<=0)&&Ke.geometry_isValid(e),createQuad(e=1,t=1){const r=e/2,s=t/2;return st.create({vertices:new Float32Array([-r,-s,0,0,r,-s,1,0,r,s,1,1,-r,s,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const r=[],s=[];r.push(0,0,.5,.5);for(let s=0;s<=t;s++){const n=s/t*Math.PI*2,o=Math.cos(n)*e,i=Math.sin(n)*e,a=(Math.cos(n)+1)/2,c=(Math.sin(n)+1)/2;r.push(o,i,a,c)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return st.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,r=1/0,s=-1/0,n=-1/0;for(const o of e)t=Math.min(t,o.x),r=Math.min(r,o.y),s=Math.max(s,o.x),n=Math.max(n,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-r)/(n-r);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return st.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 nt=null;function ot(e){nt=e}function it(){nt&&ct.isInitialized()&&ct.shutdown(),nt=null}function at(){if(!nt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return nt}const ct={init:(e,t)=>at().postprocess_init(e,t),shutdown(){at().postprocess_shutdown()},resize(e,t){at().postprocess_resize(e,t)},addPass:(e,t)=>at().postprocess_addPass(e,t),removePass(e){at().postprocess_removePass(e)},setEnabled(e,t){at().postprocess_setPassEnabled(e,t)},isEnabled:e=>at().postprocess_isPassEnabled(e),setUniform(e,t,r){at().postprocess_setUniformFloat(e,t,r)},setUniformVec4(e,t,r){at().postprocess_setUniformVec4(e,t,r.x,r.y,r.z,r.w)},begin(){at().postprocess_begin()},end(){at().postprocess_end()},getPassCount:()=>at().postprocess_getPassCount(),isInitialized:()=>!!nt&&nt.postprocess_isInitialized(),setBypass(e){at().postprocess_setBypass(e)},isBypassed:()=>!nt||nt.postprocess_isBypassed(),createBlur:()=>ve.createShader(lt,"#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:()=>ve.createShader(lt,"#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:()=>ve.createShader(lt,"#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:()=>ve.createShader(lt,"#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")},lt="#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 ut;exports.RenderStage=void 0,(ut=exports.RenderStage||(exports.RenderStage={}))[ut.Background=0]="Background",ut[ut.Opaque=1]="Opaque",ut[ut.Transparent=2]="Transparent",ut[ut.Overlay=3]="Overlay";let ht=null,dt=0;function pt(e){ht=e,dt=ht._malloc(64)}function ft(){ht&&dt&&(ht._free(dt),dt=0),ht=null}const xt={init(e,t){ht?.renderer_init(e,t)},resize(e,t){ht?.renderer_resize(e,t)},begin(e,t){ht&&dt&&(ht.HEAPF32.set(e,dt/4),ht.renderer_begin(dt,t??0))},flush(){ht?.renderer_flush()},end(){ht?.renderer_end()},submitSprites(e){ht&&ht.renderer_submitSprites(e._cpp)},submitSpine(e){ht&&ht.renderer_submitSpine?.(e._cpp)},setStage(e){ht?.renderer_setStage(e)},createRenderTarget:(e,t,r=1)=>ht?.renderer_createTarget(e,t,r)??0,releaseRenderTarget(e){ht?.renderer_releaseTarget(e)},getTargetTexture:e=>ht?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>ht?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,r,s){ht?.renderer_setClearColor?.(e,t,r,s)},getStats:()=>ht?{drawCalls:ht.renderer_getDrawCalls(),triangles:ht.renderer_getTriangles(),sprites:ht.renderer_getSprites(),spine:ht.renderer_getSpine?.()??0,meshes:ht.renderer_getMeshes(),culled:ht.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let _t=null;function mt(e){_t=e}function gt(){_t=null}const yt={enable(){_t?.gl_enableErrorCheck(!0)},disable(){_t?.gl_enableErrorCheck(!1)},check:e=>_t?.gl_checkErrors(e)??0,diagnose(){_t?.renderer_diagnose()}},wt=new Map;function vt(e){wt.delete(e)}class St{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:r,width:s,height:n,elapsed:o}=e;xt.resize(s,n),ct.isInitialized()&&ct.getPassCount()>0&&!ct.isBypassed()&&ct.resize(s,n),xt.begin(r),xt.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,o):xt.submitSpine(t),xt.flush();const i=wt;if(i.size>0){je.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)}je.end();for(const t of e)vt(t)}xt.end()}}class Pt{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=i(),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 se,this.resources_=new H;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Pt}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 Q(this.world_,this.resources_),this.resources_.insert(N,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=i(),this.mainLoop())}quit(){this.running_=!1,gt(),ft(),it(),tt(),ye(),Ne()}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(N),r={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(N,r)}}const Tt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ct(e,t){for(let r=0;r<t;r++){if(!e.valid(r)||!e.hasCanvas(r))continue;return e.getCanvas(r)}return null}function bt(e,t,r,s,n){const o=e*t/r,i=e;switch(s){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=n;return Math.pow(o,1-e)*Math.pow(i,e)}}}function At(e,t,r,s,n,o){const i=new Float32Array(16),a=t-e,c=s-r,l=o-n;return i[0]=2/a,i[5]=2/c,i[10]=-2/l,i[12]=-(t+e)/a,i[13]=-(s+r)/c,i[14]=-(o+n)/l,i[15]=1,i}function Mt(e,t,r,s){const n=new Float32Array(16),o=1/Math.tan(e/2),i=r-s;return n[0]=o/t,n[5]=o,n[10]=(s+r)/i,n[11]=-1,n[14]=2*s*r/i,n}function Rt(e,t,r){const s=new Float32Array(16);return s[0]=1,s[5]=1,s[10]=1,s[15]=1,s[12]=-e,s[13]=-t,s[14]=-r,s}function Et(e,t){const r=new Float32Array(16);for(let s=0;s<4;s++)for(let n=0;n<4;n++)r[4*n+s]=e[0+s]*t[4*n+0]+e[4+s]*t[4*n+1]+e[8+s]*t[4*n+2]+e[12+s]*t[4*n+3];return r}function Ft(e,t){const r=e.getResourceManager(),s=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,s);const n=r.createTexture(t.width,t.height,s,t.pixels.length,1);return e._free(s),n}function Ut(e,t){const r=t.substring(0,t.lastIndexOf("/"));r&&e.FS.mkdirTree(r)}function It(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}async function Wt(e,t,r,s,n){const o=await async function(e,t,r){const s={};for(const n of t.entities)for(const t of n.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const n=t.data.texture;if(void 0!==s[n])continue;try{s[n]=Ft(e,await r.loadPixels(n))}catch{s[n]=0}}return s}(t,r,s);!function(e,t,r){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const n=r[e];if(n&&n>0){const r=t.textureMetadata[e];if(r?.sliceBorder){const e=r.sliceBorder;s.setTextureMetadata(n,e.left,e.right,e.top,e.bottom)}}}}(t,r,o);let i={};n&&(i=await async function(e,t,r,s){const n={};for(const o of r.entities)for(const r of o.components){if("SpineAnimation"!==r.type||!r.data)continue;const o=r.data.skeletonPath,i=r.data.atlasPath;if(!o||!i)continue;const a=s.resolvePath(o),c=s.resolvePath(i);try{const r=s.readText(i),l=a.endsWith(".skel");Ut(t,a),l?t.FS.writeFile(a,s.readBinary(o)):t.FS.writeFile(a,s.readText(o));const u=t.spine_loadSkeleton(a,r,r.length,l);if(u<0)continue;n[o]=u;const h=It(r),d=c.substring(0,c.lastIndexOf("/"));for(let r=0;r<h.length;r++){const n=d+"/"+h[r];try{const o=s.loadPixelsRaw?await s.loadPixelsRaw(n):await s.loadPixels(n),i=Ft(e,o),a=e.getResourceManager().getTextureGLId(i);t.spine_setAtlasPageTexture(u,r,a,o.width,o.height)}catch{}}}catch{}}return n}(t,n,r,s));const a=function(e,t){const r={},s={};for(const n of e.entities)for(const e of n.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const n=e.data.material;if(void 0===r[n])try{const e=JSON.parse(t.readText(n));if(!e.vertexSource||!e.fragmentSource){r[n]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=ve.createShader(e.vertexSource,e.fragmentSource),s[o]=i),r[n]=ve.createFromAsset(e,i)}catch{r[n]=0}}return r}(r,s),c=Re(e.world,r);if(function(e,t,r,s){for(const n of t.entities){const t=s.get(n.id);if(void 0!==t)for(const s of n.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const n=e.get(t,F);n&&(n.texture=r[s.data.texture]||0,e.insert(t,F,n))}}}(e.world,r,o,c),function(e,t,r,s){for(const n of t.entities){const t=s.get(n.id);if(void 0!==t)for(const s of n.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const n=r[s.data.material]||0;if(n)if("Sprite"===s.type){const r=e.get(t,F);r&&(r.material=n,e.insert(t,F,r))}else if("SpineAnimation"===s.type){const r=e.get(t,$);r&&(r.material=n,e.insert(t,$,r))}}}}(e.world,r,a,c),n){const s=function(e,t,r,s){const n={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=r[t.data.skeletonPath];if(void 0===i)continue;const a=e.spine_createInstance(i);if(a<0)continue;const c=s.get(o.id);void 0!==c&&(n[c]=a),t.data.animation&&e.spine_playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.spine_setSkin(a,t.data.skin)}return n}(n,r,i,c);!function(e,t,r,s){let n=0;e.setSpineRenderer((e,o)=>{let i=o-n;n=o,(i<=0||i>.5)&&(i=1/60);for(const e in s){const n=s[e];r.spine_update(n,i);const o=r.spine_getMeshBatchCount(n);for(let e=0;e<o;e++){const s=r.spine_getMeshBatchVertexCount(n,e),o=r.spine_getMeshBatchIndexCount(n,e);if(!s||!o)continue;const i=8*s*4,a=2*o,c=r._malloc(i),l=r._malloc(a),u=r._malloc(4),h=r._malloc(4);r.spine_getMeshBatchData(n,e,c,l,u,h);const d=r.HEAPU32[u>>2],p=r.HEAPU32[h>>2],f=new Float32Array(r.HEAPF32.buffer,c,8*s),x=new Uint16Array(r.HEAPU8.buffer,l,o),_=t._malloc(i),m=t._malloc(a);t.HEAPF32.set(f,_>>2),new Uint16Array(t.HEAPU8.buffer,m,o).set(x),t.renderer_submitTriangles(_,s,m,o,d,p,0),t._free(_),t._free(m),r._free(c),r._free(l),r._free(u),r._free(h)}}})}(e,t,n,s)}}class Bt{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,r=new Set;for(const s of e.entities)for(const e of s.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,n=e.data.atlasPath;s&&(s.endsWith(".skel")?r.add(s):t.add(s)),n&&t.add(n)}"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const s=[];for(const e of t)s.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of r)s.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(s)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),r=await fetch(t),s=await r.blob(),n=await createImageBitmap(s),o=new OffscreenCanvas(n.width,n.height).getContext("2d");o.drawImage(n,0,0);const i=o.getImageData(0,0,n.width,n.height);return n.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const zt={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),r=xt.createRenderTarget(e.width,e.height,t);return{_handle:r,textureId:xt.getTargetTexture(r),width:e.width,height:e.height}},release(e){xt.releaseRenderTarget(e._handle)},resize:(e,t,r)=>(xt.releaseRenderTarget(e._handle),zt.create({width:t,height:r,depth:!0})),begin(e,t){xt.begin(t,e._handle)},end(){xt.end()},getDepthTexture:e=>xt.getTargetDepthTexture(e._handle)};let $t=!1;var kt;g||(g=!0,void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const r="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},n=await a(r,s);return{ok:n.ok,status:n.status,statusText:n.statusText,headers:new Headers(n.headers),json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:r}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return c(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),r=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);n<128?r[s++]=n:n<2048?(r[s++]=192|n>>6,r[s++]=128|63&n):n>=55296&&n<=56319?(n=e.charCodeAt(++t)-56320+(n-55296<<10)+65536,r[s++]=240|n>>18,r[s++]=128|n>>12&63,r[s++]=128|n>>6&63,r[s++]=128|63&n):(r[s++]=224|n>>12,r[s++]=128|n>>6&63,r[s++]=128|63&n)}return r.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let r="";for(let e=0;e<t.length;){const s=t[e];if(s<128)r+=String.fromCharCode(s),e++;else if(192==(224&s))r+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))r+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const n=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;r+=String.fromCharCode(55296+(n>>10),56320+(1023&n)),e+=4}}return r}})}(),console.log("[ESEngine] WeChat platform initialized")),e=kt=y,console.log(`[ESEngine] Platform: ${kt.name}`),exports.App=Pt,exports.AssetPlugin=Be,exports.AssetServer=Ie,exports.Assets=We,exports.AsyncCache=Ue,exports.Camera=U,exports.Canvas=I,exports.Children=z,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=X,exports.Draw=je,exports.EntityCommands=j,exports.GLDebug=yt,exports.Geometry=st,exports.INVALID_ENTITY=0,exports.INVALID_TEXTURE=w,exports.Input=ee,exports.InputPlugin=te,exports.InputState=Z,exports.LocalTransform=R,exports.Material=ve,exports.MaterialLoader=Me,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Parent=B,exports.PostProcess=ct,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await r(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new Bt(this.baseUrl_);await s.prefetch(t);let n=null;const o=this.app_.__spineInitPromise;if(o){n=(await o).controller.module}await Wt(this.app_,this.app_.wasmModule,t,s,n),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const r=e.getEntitiesWithComponents([U]);for(const s of r){if(e.get(s,U).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,r=1920/1080;const s=e.getEntitiesWithComponents([I]);for(const n of s){const s=e.get(n,I);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,r=s.designResolution.x/s.designResolution.y;break}}const n=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(n,R,o);const i={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:r,priority:0,showFrustum:!0};e.insert(n,U,i)}}},exports.Query=function(...e){return function(e,t=[],r=[]){const s=[];return e.forEach((e,t)=>{G(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:r}}(e)},exports.QueryInstance=V,exports.RenderPipeline=St,exports.RenderTexture=zt,exports.Renderer=xt,exports.Res=function(e){return{_type:"res",_resource:e}},exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.ShaderSources=Ae,exports.SpineAnimation=$,exports.Sprite=F,exports.SystemRunner=Q,exports.Text=ae,exports.TextPlugin=ue,exports.TextRenderer=ce,exports.Time=N,exports.UIRect=le,exports.Velocity=W,exports.WebAssetProvider=Bt,exports.World=se,exports.WorldTransform=E,exports.addStartupSystem=function(e){J().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){J().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){J().push({schedule:e,system:t})},exports.assetPlugin=ze,exports.clearDrawCallbacks=function(){wt.clear()},exports.clearUserComponents=function(){P().clear()},exports.color=(e=1,t=1,r=1,s=1)=>({x:e,y:t,z:r,w:s}),exports.createWebApp=function(e,t){const r=Pt.new(),s=new e.Registry;r.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),He(e),ge(e),et(e),ot(e),pt(e),mt(e);const n=new St;r.pipeline_=n;let o=i();const a=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:e,height:t}=a(),r=function(e,t,r){const s=e.entityCount()+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 c;if(1===o.projectionType){let t=o.orthoSize;const r=Ct(e,s);if(r){t=bt(r.designResolution.y/2,r.designResolution.x/r.designResolution.y,a,r.scaleMode,r.matchWidthOrHeight)}const n=t*a;c=At(-n,n,-t,t,-o.farPlane,o.farPlane)}else c=Mt(o.fov*Math.PI/180,a,o.nearPlane,o.farPlane);return Et(c,Rt(i.position.x,i.position.y,i.position.z))}return Tt}(s,e,t),c=(i()-o)/1e3;n.render({registry:{_cpp:s},viewProjection:r,width:e,height:t,elapsed:c})}};return r.addSystemToSchedule(exports.Schedule.Last,c),r.addPlugin(ze),r.addPlugin(re),r.addPlugin(he),r},exports.defineComponent=T,exports.defineResource=L,exports.defineSystem=K,exports.defineTag=function(e){const t=P(),r=t.get(e);if(r)return r;const s=S(e,{});return t.set(e,s),b(e,{},!0),s},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=k[e];if(t)return{...t._default};const r=C(e);return r?{...r._default}:null},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=C,exports.initDrawAPI=He,exports.initGLDebugAPI=mt,exports.initGeometryAPI=et,exports.initMaterialAPI=ge,exports.initPostProcessAPI=ot,exports.initRendererAPI=pt,exports.inputPlugin=re,exports.isBuiltinComponent=M,exports.isEditor=function(){return $t},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!$t},exports.isTextureRef=pe,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=Fe,exports.loadRuntimeScene=Wt,exports.loadSceneData=Re,exports.loadSceneWithAssets=Ee,exports.platformFetch=r,exports.platformFileExists=n,exports.platformInstantiateWasm=async function(e,r){return t().instantiateWasm(e,r)},exports.platformReadFile=async function(e){return t().readFile(e)},exports.platformReadTextFile=s,exports.quat=(e=1,t=0,r=0,s=0)=>({w:e,x:t,y:r,z:s}),exports.registerDrawCallback=function(e,t){wt.set(e,t)},exports.registerMaterialCallback=be,exports.setEditorMode=function(e){$t=e},exports.shutdownDrawAPI=Ne,exports.shutdownGLDebugAPI=gt,exports.shutdownGeometryAPI=tt,exports.shutdownMaterialAPI=ye,exports.shutdownPostProcessAPI=it,exports.shutdownRendererAPI=ft,exports.textPlugin=he,exports.unregisterDrawCallback=vt,exports.updateCameraAspectRatio=function(e,t){const r=e.getEntitiesWithComponents([U]);for(const s of r){const r=e.get(s,U);r&&(r.aspectRatio=t,e.insert(s,U,r))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,r=0)=>({x:e,y:t,z:r}),exports.vec4=(e=0,t=0,r=0,s=1)=>({x:e,y:t,z:r,w:s}),exports.wxFileExists=p,exports.wxFileExistsSync=function(e){const t=u();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=m,exports.wxLoadImage=_,exports.wxLoadImagePixels=async function(e,t=!0){return m(await _(e),t)},exports.wxReadFile=h,exports.wxReadTextFile=d,exports.wxWriteFile=function(e,t){return new Promise((r,s)=>{u().writeFile({filePath:e,data:t,success:()=>r(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};//# sourceMappingURL=index.wechat.cjs.js.mapdiff --git a/desktop/public/sdk/cjs/index.wechat.js b/desktop/public/sdk/cjs/index.wechat.jsindex 8b3592e04..fc8fecd17 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 r(){return null!==e}function n(){return e?.name??null}function s(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,r){return t().fetch(e,r)}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,r){return t().instantiateWasm(e,r)}function h(e,r){return t().createCanvas(e,r)}function d(){return t().now()}function f(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 p(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 _=null;function m(){return _||(_=wx.getFileSystemManager()),_}function g(e){return new Promise((t,r)=>{m().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function y(e,t="utf-8"){return new Promise((r,n)=>{m().readFile({filePath:e,encoding:t,success:e=>{r(e.data)},fail:t=>{n(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((r,n)=>{m().writeFile({filePath:e,data:t,success:()=>r(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}let S=null,P=null;function C(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 b(e,t=!0){const{width:r,height:n}=e,{ctx:s}=function(e,t){return S||(S=wx.createCanvas(),S.width=e,S.height=t,P=S.getContext("2d")),(S.width<e||S.height<t)&&(S.width=Math.max(S.width,e),S.height=Math.max(S.height,t)),{canvas:S,ctx:P}}(r,n);s.clearRect(0,0,r,n),s.save(),t&&(s.translate(0,n),s.scale(1,-1)),s.drawImage(e,0,0),s.restore();const o=s.getImageData(0,0,r,n);return{width:r,height:n,pixels:new Uint8Array(o.data.buffer)}}async function T(e,t=!0){return b(await C(e),t)}let E=!1;const M=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)}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)})}},A=0,R=4294967295,F=(e=0,t=0)=>({x:e,y:t}),U=(e=0,t=0,r=0)=>({x:e,y:t,z:r}),z=(e=0,t=0,r=0,n=1)=>({x:e,y:t,z:r,w:n}),I=(e=1,t=1,r=1,n=1)=>({x:e,y:t,z:r,w:n}),$=(e=1,t=0,r=0,n=0)=>({w:e,x:t,y:r,z:n});let B=0;function W(e,t){const r=++B;return{_id:Symbol(`Component_${r}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function k(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function D(e,t){const r=k(),n=r.get(e);if(n)return n;const s=W(e,t);return r.set(e,s),N(e,t,!1),s}function L(e){const t=k(),r=t.get(e);if(r)return r;const n=W(e,{});return t.set(e,n),N(e,{},!0),n}function O(e){return k().get(e)}function H(){k().clear()}function N(e,t,r){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,r)}function j(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function X(e){return!0===e._builtin}const G=j("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),V=j("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),q=j("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}),Y=j("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0}),K=j("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),J=j("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Q=j("Parent",{entity:0}),Z=j("Children",{entities:[]}),ee=j("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}),te={LocalTransform:G,WorldTransform:V,Sprite:q,Camera:Y,Canvas:K,Velocity:J,Parent:Q,Children:Z,SpineAnimation:ee};function re(e){const t=te[e];if(t)return{...t._default};const r=O(e);return r?{...r._default}:null}let ne=0;function se(e,t){const r=++ne;return{_id:Symbol(`Resource_${r}_${t??""}`),_name:t??`Resource_${r}`,_default:e}}function oe(e){return{_type:"res",_resource:e}}function ie(e){return{_type:"res_mut",_resource:e}}class ae{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 ce{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 ae(this.get(e),t=>this.set(e,t))}}const le=se({delta:0,elapsed:0,frameCount:0},"Time");function ue(e){return{_type:"mut",_component:e}}function he(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function de(...e){return function(e,t=[],r=[]){const n=[];return e.forEach((e,t)=>{he(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:r}}(e)}class fe{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return he(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,c=[];try{for(const e of i){if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data);c=[];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)c.push({component:s[e],data:o[e]});a=e,yield[e,...o]}}finally{if(null!==a)for(const e of c)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]}}function pe(){return{_type:"commands"}}class _e{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=X(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 me{constructor(e,t){this.pending_=[],this.world_=e,this.resources_=t}spawn(){return new _e(this,null)}entity(e){return new _e(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.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 ge;!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"}(ge||(ge={}));let ye=0;function we(e,t,r){const n=++ye;return{_id:Symbol(`System_${n}_${r?.name??""}`),_params:e,_fn:t,_name:r?.name??`System_${n}`}}function xe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function ve(e){xe().push({schedule:ge.Update,system:e})}function Se(e){xe().push({schedule:ge.Startup,system:e})}function Pe(e,t){xe().push({schedule:e,system:t})}class Ce{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 me&&e.flush()}resolveParam(e){switch(e._type){case"query":return new fe(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new me(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class be{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const Te=se(new be,"Input");class Ee{constructor(e){this.target_=e??null}build(e){const r=new be;e.insertResource(Te,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(ge.First,we([],()=>{r.keysPressed.clear(),r.keysReleased.clear(),r.mouseButtonsPressed.clear(),r.mouseButtonsReleased.clear(),r.scrollDeltaX=0,r.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Me=new Ee;class Ae{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 X(t)?this.insertBuiltin(e,t,r):this.insertScript(e,t,r)}get(e,t){return X(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return X(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){X(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 Re,Fe,Ue;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Re||(Re={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Fe||(Fe={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Ue||(Ue={}));const ze=D("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:Re.Left,verticalAlign:Fe.Top,wordWrap:!0,overflow:Ue.Visible,lineHeight:1.2,dirty:!0});class Ie{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 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 c=this.wrapText(e.content,a?o: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(o):h+2*u,p=s?Math.ceil(i):d+2*u;if(s&&e.overflow===Ue.Ellipsis&&d>i){const e=Math.floor(i/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,o)}}if(n.width<f||n.height<p){const e=Math.max(n.width,this.nextPowerOf2(f)),t=Math.max(n.height,this.nextPowerOf2(p));n.width=e,n.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;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}, ${y})`,s&&e.overflow===Ue.Clip&&(r.save(),r.beginPath(),r.rect(0,0,f,p),r.clip());const w=c.length*l;let x;if(s)switch(e.verticalAlign){case Fe.Top:x=u;break;case Fe.Middle:x=(p-w)/2;break;case Fe.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let n;switch(e.align){case Re.Left:n=u;break;case Re.Center:n=f/2;break;case Re.Right:n=f-u;break;default:n=u}r.fillText(t,n,v),v+=l}s&&e.overflow===Ue.Clip&&r.restore();const S=r.getImageData(0,0,f,p),P=new Uint8Array(S.data.buffer),C=this.flipVertically(P,f,p),b=this.module.getResourceManager(),T=this.module._malloc(C.length);this.module.HEAPU8.set(C,T);const E=b.createTexture(f,p,T,C.length,1);return this.module._free(T),{textureHandle:E,width:f,height:p}}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 Re.Left:return"left";case Re.Center:return"center";case Re.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}flipVertically(e,t,r){const n=4*t,s=new Uint8Array(e.length);for(let t=0;t<r;t++){const o=t*n,i=(r-1-t)*n;s.set(e.subarray(o,o+n),i)}return s}}const $e=D("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class Be{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const r=new Ie(t),n=e.world;e.addSystemToSchedule(ge.PreUpdate,we([],()=>{const e=n.getEntitiesWithComponents([ze]);for(const t of e){const e=n.get(t,ze);if(!e.dirty)continue;n.has(t,q)||n.insert(t,q,{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=n.has(t,$e)?n.get(t,$e):null,o=r.renderForEntity(t,e,s),i=n.get(t,q);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,q,i),e.dirty=!1}}))}}const We=new Be;var ke;function De(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"}(ke||(ke={}));let Le=null,Oe=null,He=1;const Ne=new Map;function je(e){Le=e,Oe=e.getResourceManager(),Qe()}function Xe(){0!==Ye&&Le&&(Le._free(Ye),Ye=0),Ne.clear(),He=1,qe=!1,Oe=null,Le=null}function Ge(){if(!Oe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Oe}const Ve={createShader:(e,t)=>Ge().createShader(e,t),releaseShader(e){e>0&&Ge().releaseShader(e)},create(e){const t=He++,r={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??ke.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))r.uniforms.set(t,n);return Ne.set(t,r),t},get:e=>Ne.get(e),setUniform(e,t,r){const n=Ne.get(e);n&&n.uniforms.set(t,r)},getUniform(e,t){const r=Ne.get(e);return r?.uniforms.get(t)},setBlendMode(e,t){const r=Ne.get(e);r&&(r.blendMode=t)},getBlendMode(e){const t=Ne.get(e);return t?.blendMode??ke.Normal},setDepthTest(e,t){const r=Ne.get(e);r&&(r.depthTest=t)},getShader(e){const t=Ne.get(e);return t?.shader??0},release(e){Ne.delete(e)},isValid:e=>Ne.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??ke.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ne.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const r=He++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Ne.set(r,n),r},toAssetData(e,t){const r=Ne.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=Ne.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let qe=!1,Ye=0;const Ke=4096;function Je(e){const t=(0===Ye&&Le&&(Ye=Le._malloc(Ke)),Ye);if(0===t||!Le)return{ptr:0,count:0};let r=0,n=0;const s=Le.HEAPU8,o=Le.HEAPU32,i=Le.HEAPF32;for(const[a,c]of e){if(r+128>Ke)break;const e=(new TextEncoder).encode(a),l=e.length,u=4*Math.ceil(l/4);o[t+r>>2]=l,r+=4,s.set(e,t+r),r+=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]);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 Qe(){if(!Le||qe)return;Le.materialDataProvider=(e,t,r,n,s)=>{const o=Ne.get(e);if(!o)return Le.HEAPU32[t>>2]=0,Le.HEAPU32[r>>2]=0,Le.HEAPU32[n>>2]=0,void(Le.HEAPU32[s>>2]=0);Le.HEAPU32[t>>2]=o.shader,Le.HEAPU32[r>>2]=o.blendMode;const{ptr:i,count:a}=Je(o.uniforms);Le.HEAPU32[n>>2]=i,Le.HEAPU32[s>>2]=a},qe=!0}const Ze={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"};let et=null,tt=0,rt=0,nt=0;const st=new Float32Array(256);function ot(e){et=e,tt=et._malloc(64),rt=et._malloc(64),nt=et._malloc(1024)}function it(){et&&(tt&&(et._free(tt),tt=0),rt&&(et._free(rt),rt=0),nt&&(et._free(nt),nt=0)),et=null}function at(){if(!et)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return et}const ct={x:1,y:1,z:1,w:1},lt={begin(e){const t=at();t.HEAPF32.set(e,tt/4),t.draw_begin(tt)},end(){at().draw_end()},line(e,t,r,n=1){at().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){at().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){at().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){at().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){at().draw_circleOutline(e.x,e.y,t,r.x,r.y,r.z,r.w,n,s)},texture(e,t,r,n=ct){at().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=ct){at().draw_textureRotated(e.x,e.y,t.x,t.y,r,n,s.x,s.y,s.z,s.w)},setLayer(e){at().draw_setLayer(e)},setDepth(e){at().draw_setDepth(e)},getDrawCallCount:()=>et?et.draw_getDrawCallCount():0,getPrimitiveCount:()=>et?et.draw_getPrimitiveCount():0,setBlendMode(e){at().draw_setBlendMode(e)},setDepthTest(e){at().draw_setDepthTest(e)},drawMesh(e,t,r){const n=at();n.HEAPF32.set(r,rt/4),n.draw_mesh(e,t,rt)},drawMeshWithMaterial(e,t,r){const n=at(),s=Ve.get(t);if(!s)return;if(lt.setBlendMode(s.blendMode),lt.setDepthTest(s.depthTest),0===s.uniforms.size)return void lt.drawMesh(e,s.shader,r);n.HEAPF32.set(r,rt/4);let o=0,i=0;for(const[e,t]of s.uniforms){const r=ht(e);if(!(r<0)){if(De(t))st[o++]=10,st[o++]=r,st[o++]=t.slot??i++,st[o++]=t.textureId;else if("number"==typeof t)st[o++]=1,st[o++]=r,st[o++]=t;else if(Array.isArray(t)){st[o++]=t.length,st[o++]=r;for(let e=0;e<t.length;e++)st[o++]=t[e]}else"w"in t?(st[o++]=4,st[o++]=r,st[o++]=t.x,st[o++]=t.y,st[o++]=t.z,st[o++]=t.w):"z"in t?(st[o++]=3,st[o++]=r,st[o++]=t.x,st[o++]=t.y,st[o++]=t.z):(st[o++]=2,st[o++]=r,st[o++]=t.x,st[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(n.HEAPF32.set(st.subarray(0,o),nt/4),n.draw_meshWithUniforms(e,s.shader,rt,nt,o)):n.draw_mesh(e,s.shader,rt)}},ut={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 ht(e){return ut[e]??-1}var dt;!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"}(dt||(dt={}));let ft=null,pt=0,_t=0,mt=0;function gt(e){ft=e,pt=ft._malloc(262144),_t=ft._malloc(65536),mt=ft._malloc(256)}function yt(){ft&&(pt&&ft._free(pt),_t&&ft._free(_t),mt&&ft._free(mt),pt=0,_t=0,mt=0),ft=null}function wt(){if(!ft)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ft}const xt={create(e){const t=wt(),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,pt/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,mt,s).set(o),t.geometry_init(r,pt,n,mt,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,_t,n).set(e.indices),t.geometry_setIndices16(r,_t,n)}else{new Uint32Array(t.HEAPU8.buffer,_t,n).set(e.indices),t.geometry_setIndices32(r,_t,n)}}return r},updateVertices(e,t,r=0){const n=wt(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);n.HEAPF32.set(t,pt/4),n.geometry_updateVertices(e,pt,s,r)},release(e){e>0&&wt().geometry_release(e)},isValid:e=>!(!ft||e<=0)&&ft.geometry_isValid(e),createQuad(e=1,t=1){const r=e/2,n=t/2;return xt.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:dt.Float2},{name:"a_texCoord",type:dt.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,c=(Math.sin(s)+1)/2;r.push(o,i,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return xt.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:dt.Float2},{name:"a_texCoord",type:dt.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 xt.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:dt.Float2},{name:"a_texCoord",type:dt.Float2}],indices:new Uint16Array(i)})}};let vt=null;function St(e){vt=e}function Pt(){vt&&bt.isInitialized()&&bt.shutdown(),vt=null}function Ct(){if(!vt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return vt}const bt={init:(e,t)=>Ct().postprocess_init(e,t),shutdown(){Ct().postprocess_shutdown()},resize(e,t){Ct().postprocess_resize(e,t)},addPass:(e,t)=>Ct().postprocess_addPass(e,t),removePass(e){Ct().postprocess_removePass(e)},setEnabled(e,t){Ct().postprocess_setPassEnabled(e,t)},isEnabled:e=>Ct().postprocess_isPassEnabled(e),setUniform(e,t,r){Ct().postprocess_setUniformFloat(e,t,r)},setUniformVec4(e,t,r){Ct().postprocess_setUniformVec4(e,t,r.x,r.y,r.z,r.w)},begin(){Ct().postprocess_begin()},end(){Ct().postprocess_end()},getPassCount:()=>Ct().postprocess_getPassCount(),isInitialized:()=>!!vt&&vt.postprocess_isInitialized(),setBypass(e){Ct().postprocess_setBypass(e)},isBypassed:()=>!vt||vt.postprocess_isBypassed(),createBlur:()=>Ve.createShader(Tt,"#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:()=>Ve.createShader(Tt,"#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:()=>Ve.createShader(Tt,"#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:()=>Ve.createShader(Tt,"#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")},Tt="#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 Et;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Et||(Et={}));let Mt=null,At=0;function Rt(e){Mt=e,At=Mt._malloc(64)}function Ft(){Mt&&At&&(Mt._free(At),At=0),Mt=null}const Ut={init(e,t){Mt?.renderer_init(e,t)},resize(e,t){Mt?.renderer_resize(e,t)},begin(e,t){Mt&&At&&(Mt.HEAPF32.set(e,At/4),Mt.renderer_begin(At,t??0))},flush(){Mt?.renderer_flush()},end(){Mt?.renderer_end()},submitSprites(e){Mt&&Mt.renderer_submitSprites(e._cpp)},submitSpine(e){Mt&&Mt.renderer_submitSpine?.(e._cpp)},setStage(e){Mt?.renderer_setStage(e)},createRenderTarget:(e,t,r=1)=>Mt?.renderer_createTarget(e,t,r)??0,releaseRenderTarget(e){Mt?.renderer_releaseTarget(e)},getTargetTexture:e=>Mt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Mt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,r,n){Mt?.renderer_setClearColor?.(e,t,r,n)},getStats:()=>Mt?{drawCalls:Mt.renderer_getDrawCalls(),triangles:Mt.renderer_getTriangles(),sprites:Mt.renderer_getSprites(),spine:Mt.renderer_getSpine?.()??0,meshes:Mt.renderer_getMeshes(),culled:Mt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let zt=null;function It(e){zt=e}function $t(){zt=null}const Bt={enable(){zt?.gl_enableErrorCheck(!0)},disable(){zt?.gl_enableErrorCheck(!1)},check:e=>zt?.gl_checkErrors(e)??0,diagnose(){zt?.renderer_diagnose()}},Wt=new Map;function kt(e,t){Wt.set(e,t)}function Dt(e){Wt.delete(e)}function Lt(){Wt.clear()}class Ot{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:r,width:n,height:s,elapsed:o}=e;Ut.resize(n,s),bt.isInitialized()&&bt.getPassCount()>0&&!bt.isBypassed()&&bt.resize(n,s),Ut.begin(r),Ut.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,o):Ut.submitSpine(t),Ut.flush();const i=Wt;if(i.size>0){lt.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)}lt.end();for(const t of e)Dt(t)}Ut.end()}}class Ht{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 r=t/1e3;for(this.updateTime(r),this.runSchedule(ge.First),this.fixedAccumulator_+=r;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ge.FixedPreUpdate),this.runSchedule(ge.FixedUpdate),this.runSchedule(ge.FixedPostUpdate);this.runSchedule(ge.PreUpdate),this.runSchedule(ge.Update),this.runSchedule(ge.PostUpdate),this.runSchedule(ge.Last),requestAnimationFrame(this.mainLoop)},this.world_=new Ae,this.resources_=new ce;for(const e of Object.values(ge))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Ht}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(ge.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(ge.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 Ce(this.world_,this.resources_),this.resources_.insert(le,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(ge.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,$t(),Ft(),Pt(),yt(),Xe(),it()}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(le),r={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(le,r)}}function Nt(e,t){const r=Ht.new(),n=new e.Registry;r.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),ot(e),je(e),gt(e),St(e),Rt(e),It(e);const s=new Ot;r.pipeline_=s;let o=d();const i=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}=i(),r=function(e,t,r){const n=e.entityCount()+1e3;for(let s=0;s<n;s++){if(!e.valid(s)||!e.hasCamera(s)||!e.hasLocalTransform(s))continue;const o=e.getCamera(s);if(!o.isActive)continue;const i=e.getLocalTransform(s),a=t/r;let c;if(1===o.projectionType){let t=o.orthoSize;const r=Gt(e,n);if(r){t=Vt(r.designResolution.y/2,r.designResolution.x/r.designResolution.y,a,r.scaleMode,r.matchWidthOrHeight)}const s=t*a;c=qt(-s,s,-t,t,-o.farPlane,o.farPlane)}else c=Yt(o.fov*Math.PI/180,a,o.nearPlane,o.farPlane);return Jt(c,Kt(i.position.x,i.position.y,i.position.z))}return Xt}(n,e,t),a=(d()-o)/1e3;s.render({registry:{_cpp:n},viewProjection:r,width:e,height:t,elapsed:a})}};return r.addSystemToSchedule(ge.Last,a),r.addPlugin(Me),r.addPlugin(We),r}function jt(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}}const Xt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Gt(e,t){for(let r=0;r<t;r++){if(!e.valid(r)||!e.hasCanvas(r))continue;return e.getCanvas(r)}return null}function Vt(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 qt(e,t,r,n,s,o){const i=new Float32Array(16),a=t-e,c=n-r,l=o-s;return i[0]=2/a,i[5]=2/c,i[10]=-2/l,i[12]=-(t+e)/a,i[13]=-(n+r)/c,i[14]=-(o+s)/l,i[15]=1,i}function Yt(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 Jt(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}class Qt{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&&(Ve.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ve.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 r=await c(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 s=this.resolveShaderPath(e,n.shader),o=await this.shaderLoader_.load(s);return{handle:Ve.createFromAsset(n,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const r=e.substring(0,e.lastIndexOf("/"));return r?`${r}/${t}`:t}}function Zt(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)tr(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 er(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}}tr(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 tr(e,t,r){const n=r.data;switch(r.type){case"LocalTransform":e.insert(t,G,n);break;case"Sprite":e.insert(t,q,n);break;case"Camera":e.insert(t,Y,n);break;case"Canvas":e.insert(t,K,n);break;case"Text":e.insert(t,ze,n);break;case"SpineAnimation":e.insert(t,ee,n);break;case"UIRect":e.insert(t,$e,n);break;default:{const s=O(r.type);s?e.insert(t,s,n):console.warn(`Unknown component type: ${r.type}`);break}}}function rr(e,t){const r=e.getEntitiesWithComponents([Y]);for(const n of r){const r=e.get(n,Y);r&&(r.aspectRatio=t,e.insert(n,Y,r))}}class nr{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 sr{constructor(e){this.textureCache_=new nr,this.shaderCache_=new nr,this.jsonCache_=new nr,this.textCache_=new nr,this.binaryCache_=new nr,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,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 Qt(t)}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 fetch(s);if(!o.ok)return{success:!1,error:`Failed to fetch atlas: ${s}`};const i=await o.text();if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const a=t.substring(0,t.lastIndexOf("/")),c=this.parseAtlasTextures(i);for(const e of c){const t=a?`${a}/${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),u=await fetch(l);if(!u.ok)return{success:!1,error:`Failed to fetch skeleton: ${l}`};const h=e.endsWith(".skel")?new Uint8Array(await u.arrayBuffer()):await u.text();return this.writeToVirtualFS(e,h)?(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 er(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){return new Promise((t,r)=>{const n=new Image;n.crossOrigin="anonymous",n.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(n,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void t(e)}catch{}t(n)},n.onerror=()=>r(new Error(`Failed to load image: ${e}`)),n.src=e})}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_.save(),n&&(this.ctx_.translate(0,r),this.ctx_.scale(1,-1)),this.ctx_.drawImage(e,0,0),this.ctx_.restore();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 c=i.createTexture(t,r,a,o.length,1);return this.module_._free(a),{handle:c,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){if(!await l(e))throw new Error(`Shader file not found: ${e}`);const t=await c(e);if(!t)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:n}=this.parseEsShader(t);if(!r||!n)throw new Error(`Invalid shader format: ${e}`);return Ve.createShader(r,n)}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}}async fetchJson(e){const t=await i(e);if(!t.ok)throw new Error(`Failed to fetch JSON: ${e} (${t.status})`);return t.json()}async fetchText(e){const t=await i(e);if(!t.ok)throw new Error(`Failed to fetch text: ${e} (${t.status})`);return t.text()}async fetchBinary(e){const t=await i(e);if(!t.ok)throw new Error(`Failed to fetch binary: ${e} (${t.status})`);return t.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 or=se(null,"Assets");class ir{build(e){const t=e.wasmModule;t?e.insertResource(or,new sr(t)):console.warn("AssetPlugin: No WASM module available")}}const ar=new ir;function cr(e,t){const r=e.getResourceManager(),n=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,n);const s=r.createTexture(t.width,t.height,n,t.pixels.length,1);return e._free(n),s}function lr(e,t){const r=t.substring(0,t.lastIndexOf("/"));r&&e.FS.mkdirTree(r)}function ur(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}async function hr(e,t,r,n,s){const o=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]=cr(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,o);let i={};s&&(i=await async function(e,t,r,n){const s={};for(const o of r.entities)for(const r of o.components){if("SpineAnimation"!==r.type||!r.data)continue;const o=r.data.skeletonPath,i=r.data.atlasPath;if(!o||!i)continue;const a=n.resolvePath(o),c=n.resolvePath(i);try{const r=n.readText(i),l=a.endsWith(".skel");lr(t,a),l?t.FS.writeFile(a,n.readBinary(o)):t.FS.writeFile(a,n.readText(o));const u=t.spine_loadSkeleton(a,r,r.length,l);if(u<0)continue;s[o]=u;const h=ur(r),d=c.substring(0,c.lastIndexOf("/"));for(let r=0;r<h.length;r++){const s=d+"/"+h[r];try{const o=n.loadPixelsRaw??n.loadPixels,i=await o(s),a=cr(e,i),c=e.getResourceManager().getTextureGLId(a);t.spine_setAtlasPageTexture(u,r,c,i.width,i.height)}catch{}}}catch{}}return s}(t,s,r,n));const a=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=Ve.createShader(e.vertexSource,e.fragmentSource),n[o]=i),r[s]=Ve.createFromAsset(e,i)}catch{r[s]=0}}return r}(r,n),c=Zt(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,q);s&&(s.texture=r[n.data.texture]||0,e.insert(t,q,s))}}}(e.world,r,o,c),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,q);r&&(r.material=s,e.insert(t,q,r))}else if("SpineAnimation"===n.type){const r=e.get(t,ee);r&&(r.material=s,e.insert(t,ee,r))}}}}(e.world,r,a,c),s){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.spine_createInstance(i);if(a<0)continue;const c=n.get(o.id);void 0!==c&&(s[c]=a),t.data.animation&&e.spine_playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.spine_setSkin(a,t.data.skin)}return s}(s,r,i,c);!function(e,t,r,n){if(0===Object.keys(n).length)return;let s=0;e.setSpineRenderer((e,o)=>{let i=o-s;s=o,(i<=0||i>.5)&&(i=1/60);for(const e in n){const s=n[e];r.spine_update(s,i);const o=r.spine_getMeshBatchCount(s);for(let e=0;e<o;e++){const n=r.spine_getMeshBatchVertexCount(s,e),o=r.spine_getMeshBatchIndexCount(s,e);if(!n||!o)continue;const i=8*n*4,a=2*o,c=r._malloc(i),l=r._malloc(a),u=r._malloc(4),h=r._malloc(4);r.spine_getMeshBatchData(s,e,c,l,u,h);const d=r.HEAPU32[u>>2],f=r.HEAPU32[h>>2],p=new Float32Array(r.HEAPF32.buffer,c,8*n),_=new Uint16Array(r.HEAPU8.buffer,l,o),m=t._malloc(i),g=t._malloc(a);t.HEAPF32.set(p,m>>2),new Uint16Array(t.HEAPU8.buffer,g,o).set(_),t.renderer_submitTriangles(m,n,g,o,d,f,0),t._free(m),t._free(g),r._free(c),r._free(l),r._free(u),r._free(h)}}})}(e,t,s,n)}}class dr{constructor(e){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e}build(e){this.app_=e,e.hasResource(or)||e.addPlugin(ar),this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),r=this.app_.getResource(or);await r.loadScene(this.app_.world,t),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([Y]);for(const n of r){if(e.get(n,Y).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([K]);for(const s of n){const n=e.get(s,K);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,G,o);const i={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:r,priority:0,showFrustum:!0};e.insert(s,Y,i)}}}const fr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),r=Ut.createRenderTarget(e.width,e.height,t);return{_handle:r,textureId:Ut.getTargetTexture(r),width:e.width,height:e.height}},release(e){Ut.releaseRenderTarget(e._handle)},resize:(e,t,r)=>(Ut.releaseRenderTarget(e._handle),fr.create({width:t,height:r,depth:!0})),begin(e,t){Ut.begin(t,e._handle)},end(){Ut.end()},getDepthTexture:e=>Ut.getTargetDepthTexture(e._handle)};let pr=!1;function _r(e){pr=e}function mr(){return pr}function gr(){return!pr}var yr;E||(E=!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 f(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 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),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=yr=M,console.log(`[ESEngine] Platform: ${yr.name}`);export{Ht as App,ir as AssetPlugin,sr as AssetServer,or as Assets,nr as AsyncCache,ke as BlendMode,Y as Camera,K as Canvas,Z as Children,pe as Commands,me as CommandsInstance,dt as DataType,lt as Draw,_e as EntityCommands,Bt as GLDebug,xt as Geometry,A as INVALID_ENTITY,R as INVALID_TEXTURE,Te as Input,Ee as InputPlugin,be as InputState,G as LocalTransform,Ve as Material,Qt as MaterialLoader,ue as Mut,Q as Parent,bt as PostProcess,dr as PreviewPlugin,de as Query,fe as QueryInstance,Ot as RenderPipeline,Et as RenderStage,fr as RenderTexture,Ut as Renderer,oe as Res,ie as ResMut,ge as Schedule,Ze as ShaderSources,ee as SpineAnimation,q as Sprite,Ce as SystemRunner,ze as Text,Re as TextAlign,Ue as TextOverflow,Be as TextPlugin,Ie as TextRenderer,Fe as TextVerticalAlign,le as Time,$e as UIRect,J as Velocity,Ae as World,V as WorldTransform,Se as addStartupSystem,ve as addSystem,Pe as addSystemToSchedule,ar as assetPlugin,Lt as clearDrawCallbacks,H as clearUserComponents,I as color,Nt as createWebApp,D as defineComponent,se as defineResource,we as defineSystem,L as defineTag,jt as flushPendingSystems,re as getComponentDefaults,t as getPlatform,n as getPlatformType,O as getUserComponent,ot as initDrawAPI,It as initGLDebugAPI,gt as initGeometryAPI,je as initMaterialAPI,St as initPostProcessAPI,Rt as initRendererAPI,Me as inputPlugin,X as isBuiltinComponent,mr as isEditor,r as isPlatformInitialized,gr as isRuntime,De as isTextureRef,s as isWeChat,o as isWeb,tr as loadComponent,hr as loadRuntimeScene,Zt as loadSceneData,er as loadSceneWithAssets,i as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,$ as quat,kt as registerDrawCallback,Qe as registerMaterialCallback,_r as setEditorMode,it as shutdownDrawAPI,$t as shutdownGLDebugAPI,yt as shutdownGeometryAPI,Xe as shutdownMaterialAPI,Pt as shutdownPostProcessAPI,Ft as shutdownRendererAPI,We as textPlugin,Dt as unregisterDrawCallback,rr as updateCameraAspectRatio,F as vec2,U as vec3,z as vec4,w as wxFileExists,x as wxFileExistsSync,b as wxGetImagePixels,C as wxLoadImage,T 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 r(){return null!==e}function n(){return e?.name??null}function s(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,r){return t().fetch(e,r)}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,r){return t().instantiateWasm(e,r)}function h(e,r){return t().createCanvas(e,r)}function d(){return t().now()}function f(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 p(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 _=null;function m(){return _||(_=wx.getFileSystemManager()),_}function g(e){return new Promise((t,r)=>{m().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function y(e,t="utf-8"){return new Promise((r,n)=>{m().readFile({filePath:e,encoding:t,success:e=>{r(e.data)},fail:t=>{n(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((r,n)=>{m().writeFile({filePath:e,data:t,success:()=>r(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}let S=null,P=null;function b(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 C(e,t=!0){const{width:r,height:n}=e,{ctx:s}=function(e,t){return S||(S=wx.createCanvas(),S.width=e,S.height=t,P=S.getContext("2d")),(S.width<e||S.height<t)&&(S.width=Math.max(S.width,e),S.height=Math.max(S.height,t)),{canvas:S,ctx:P}}(r,n);s.clearRect(0,0,r,n),s.save(),t&&(s.translate(0,n),s.scale(1,-1)),s.drawImage(e,0,0),s.restore();const o=s.getImageData(0,0,r,n);return{width:r,height:n,pixels:new Uint8Array(o.data.buffer)}}async function T(e,t=!0){return C(await b(e),t)}let M=!1;const E=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)}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)})}},A=0,R=4294967295,U=(e=0,t=0)=>({x:e,y:t}),F=(e=0,t=0,r=0)=>({x:e,y:t,z:r}),z=(e=0,t=0,r=0,n=1)=>({x:e,y:t,z:r,w:n}),I=(e=1,t=1,r=1,n=1)=>({x:e,y:t,z:r,w:n}),W=(e=1,t=0,r=0,n=0)=>({w:e,x:t,y:r,z:n});let B=0;function $(e,t){const r=++B;return{_id:Symbol(`Component_${r}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function k(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function D(e,t){const r=k(),n=r.get(e);if(n)return n;const s=$(e,t);return r.set(e,s),N(e,t,!1),s}function L(e){const t=k(),r=t.get(e);if(r)return r;const n=$(e,{});return t.set(e,n),N(e,{},!0),n}function O(e){return k().get(e)}function H(){k().clear()}function N(e,t,r){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,r)}function j(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function X(e){return!0===e._builtin}const G=j("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),V=j("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),q=j("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}),Y=j("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0}),K=j("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),J=j("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Q=j("Parent",{entity:0}),Z=j("Children",{entities:[]}),ee=j("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}),te={LocalTransform:G,WorldTransform:V,Sprite:q,Camera:Y,Canvas:K,Velocity:J,Parent:Q,Children:Z,SpineAnimation:ee};function re(e){const t=te[e];if(t)return{...t._default};const r=O(e);return r?{...r._default}:null}let ne=0;function se(e,t){const r=++ne;return{_id:Symbol(`Resource_${r}_${t??""}`),_name:t??`Resource_${r}`,_default:e}}function oe(e){return{_type:"res",_resource:e}}function ie(e){return{_type:"res_mut",_resource:e}}class ae{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 ce{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 ae(this.get(e),t=>this.set(e,t))}}const le=se({delta:0,elapsed:0,frameCount:0},"Time");function ue(e){return{_type:"mut",_component:e}}function he(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function de(...e){return function(e,t=[],r=[]){const n=[];return e.forEach((e,t)=>{he(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:r}}(e)}class fe{constructor(e,t){this.pendingMutations_=[],this.world_=e,this.descriptor_=t}getActualComponent(e){return he(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,c=[];try{for(const e of i){if(null!==a)for(const e of c)this.world_.insert(a,e.component,e.data);c=[];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)c.push({component:s[e],data:o[e]});a=e,yield[e,...o]}}finally{if(null!==a)for(const e of c)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]}}function pe(){return{_type:"commands"}}class _e{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=X(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 me{constructor(e,t){this.pending_=[],this.world_=e,this.resources_=t}spawn(){return new _e(this,null)}entity(e){return new _e(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.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 ge;!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"}(ge||(ge={}));let ye=0;function we(e,t,r){const n=++ye;return{_id:Symbol(`System_${n}_${r?.name??""}`),_params:e,_fn:t,_name:r?.name??`System_${n}`}}function xe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function ve(e){xe().push({schedule:ge.Update,system:e})}function Se(e){xe().push({schedule:ge.Startup,system:e})}function Pe(e,t){xe().push({schedule:e,system:t})}class be{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 me&&e.flush()}resolveParam(e){switch(e._type){case"query":return new fe(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new me(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ce{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const Te=se(new Ce,"Input");class Me{constructor(e){this.target_=e??null}build(e){const r=new Ce;e.insertResource(Te,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(ge.First,we([],()=>{r.keysPressed.clear(),r.keysReleased.clear(),r.mouseButtonsPressed.clear(),r.mouseButtonsReleased.clear(),r.scrollDeltaX=0,r.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Ee=new Me;class Ae{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 X(t)?this.insertBuiltin(e,t,r):this.insertScript(e,t,r)}get(e,t){return X(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return X(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){X(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 Re,Ue,Fe;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Re||(Re={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Ue||(Ue={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Fe||(Fe={}));const ze=D("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:Re.Left,verticalAlign:Ue.Top,wordWrap:!0,overflow:Fe.Visible,lineHeight:1.2,dirty:!0});class Ie{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 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 c=this.wrapText(e.content,a?o: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(o):h+2*u,p=s?Math.ceil(i):d+2*u;if(s&&e.overflow===Fe.Ellipsis&&d>i){const e=Math.floor(i/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,o)}}if(n.width<f||n.height<p){const e=Math.max(n.width,this.nextPowerOf2(f)),t=Math.max(n.height,this.nextPowerOf2(p));n.width=e,n.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;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}, ${y})`,s&&e.overflow===Fe.Clip&&(r.save(),r.beginPath(),r.rect(0,0,f,p),r.clip());const w=c.length*l;let x;if(s)switch(e.verticalAlign){case Ue.Top:x=u;break;case Ue.Middle:x=(p-w)/2;break;case Ue.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let n;switch(e.align){case Re.Left:n=u;break;case Re.Center:n=f/2;break;case Re.Right:n=f-u;break;default:n=u}r.fillText(t,n,v),v+=l}s&&e.overflow===Fe.Clip&&r.restore();const S=r.getImageData(0,0,f,p),P=new Uint8Array(S.data.buffer),b=this.flipVertically(P,f,p),C=this.module.getResourceManager(),T=this.module._malloc(b.length);this.module.HEAPU8.set(b,T);const M=C.createTexture(f,p,T,b.length,1);return this.module._free(T),{textureHandle:M,width:f,height:p}}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 Re.Left:return"left";case Re.Center:return"center";case Re.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}flipVertically(e,t,r){const n=4*t,s=new Uint8Array(e.length);for(let t=0;t<r;t++){const o=t*n,i=(r-1-t)*n;s.set(e.subarray(o,o+n),i)}return s}}const We=D("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class Be{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const r=new Ie(t),n=e.world;e.addSystemToSchedule(ge.PreUpdate,we([],()=>{const e=n.getEntitiesWithComponents([ze]);for(const t of e){const e=n.get(t,ze);if(!e.dirty)continue;n.has(t,q)||n.insert(t,q,{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=n.has(t,We)?n.get(t,We):null,o=r.renderForEntity(t,e,s),i=n.get(t,q);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,q,i),e.dirty=!1}}))}}const $e=new Be;var ke;function De(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"}(ke||(ke={}));let Le=null,Oe=null,He=1;const Ne=new Map;function je(e){Le=e,Oe=e.getResourceManager(),Qe()}function Xe(){0!==Ye&&Le&&(Le._free(Ye),Ye=0),Ne.clear(),He=1,qe=!1,Oe=null,Le=null}function Ge(){if(!Oe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Oe}const Ve={createShader:(e,t)=>Ge().createShader(e,t),releaseShader(e){e>0&&Ge().releaseShader(e)},create(e){const t=He++,r={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??ke.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))r.uniforms.set(t,n);return Ne.set(t,r),t},get:e=>Ne.get(e),setUniform(e,t,r){const n=Ne.get(e);n&&n.uniforms.set(t,r)},getUniform(e,t){const r=Ne.get(e);return r?.uniforms.get(t)},setBlendMode(e,t){const r=Ne.get(e);r&&(r.blendMode=t)},getBlendMode(e){const t=Ne.get(e);return t?.blendMode??ke.Normal},setDepthTest(e,t){const r=Ne.get(e);r&&(r.depthTest=t)},getShader(e){const t=Ne.get(e);return t?.shader??0},release(e){Ne.delete(e)},isValid:e=>Ne.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??ke.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ne.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const r=He++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Ne.set(r,n),r},toAssetData(e,t){const r=Ne.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=Ne.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let qe=!1,Ye=0;const Ke=4096;function Je(e){const t=(0===Ye&&Le&&(Ye=Le._malloc(Ke)),Ye);if(0===t||!Le)return{ptr:0,count:0};let r=0,n=0;const s=Le.HEAPU8,o=Le.HEAPU32,i=Le.HEAPF32;for(const[a,c]of e){if(r+128>Ke)break;const e=(new TextEncoder).encode(a),l=e.length,u=4*Math.ceil(l/4);o[t+r>>2]=l,r+=4,s.set(e,t+r),r+=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]);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 Qe(){if(!Le||qe)return;Le.materialDataProvider=(e,t,r,n,s)=>{const o=Ne.get(e);if(!o)return Le.HEAPU32[t>>2]=0,Le.HEAPU32[r>>2]=0,Le.HEAPU32[n>>2]=0,void(Le.HEAPU32[s>>2]=0);Le.HEAPU32[t>>2]=o.shader,Le.HEAPU32[r>>2]=o.blendMode;const{ptr:i,count:a}=Je(o.uniforms);Le.HEAPU32[n>>2]=i,Le.HEAPU32[s>>2]=a},qe=!0}const Ze={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class et{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const 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&&(Ve.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ve.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 r=await c(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 s=this.resolveShaderPath(e,n.shader),o=await this.shaderLoader_.load(s);return{handle:Ve.createFromAsset(n,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const r=e.substring(0,e.lastIndexOf("/"));return r?`${r}/${t}`:t}}function tt(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)nt(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 rt(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}}nt(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 nt(e,t,r){const n=r.data;switch(r.type){case"LocalTransform":e.insert(t,G,n);break;case"Sprite":e.insert(t,q,n);break;case"Camera":e.insert(t,Y,n);break;case"Canvas":e.insert(t,K,n);break;case"Text":e.insert(t,ze,n);break;case"SpineAnimation":e.insert(t,ee,n);break;case"UIRect":e.insert(t,We,n);break;default:{const s=O(r.type);s?e.insert(t,s,n):console.warn(`Unknown component type: ${r.type}`);break}}}function st(e,t){const r=e.getEntitiesWithComponents([Y]);for(const n of r){const r=e.get(n,Y);r&&(r.aspectRatio=t,e.insert(n,Y,r))}}class ot{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 it{constructor(e){this.textureCache_=new ot,this.shaderCache_=new ot,this.jsonCache_=new ot,this.textCache_=new ot,this.binaryCache_=new ot,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.module_=e,this.canvas_=h(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new et(t)}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 fetch(s);if(!o.ok)return{success:!1,error:`Failed to fetch atlas: ${s}`};const i=await o.text();if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const a=t.substring(0,t.lastIndexOf("/")),c=this.parseAtlasTextures(i);for(const e of c){const t=a?`${a}/${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),u=await fetch(l);if(!u.ok)return{success:!1,error:`Failed to fetch skeleton: ${l}`};const h=e.endsWith(".skel")?new Uint8Array(await u.arrayBuffer()):await u.text();return this.writeToVirtualFS(e,h)?(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 rt(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){return new Promise((t,r)=>{const n=new Image;n.crossOrigin="anonymous",n.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(n,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void t(e)}catch{}t(n)},n.onerror=()=>r(new Error(`Failed to load image: ${e}`)),n.src=e})}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_.save(),n&&(this.ctx_.translate(0,r),this.ctx_.scale(1,-1)),this.ctx_.drawImage(e,0,0),this.ctx_.restore();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 c=i.createTexture(t,r,a,o.length,1);return this.module_._free(a),{handle:c,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){if(!await l(e))throw new Error(`Shader file not found: ${e}`);const t=await c(e);if(!t)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:n}=this.parseEsShader(t);if(!r||!n)throw new Error(`Invalid shader format: ${e}`);return Ve.createShader(r,n)}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}}async fetchJson(e){const t=await i(e);if(!t.ok)throw new Error(`Failed to fetch JSON: ${e} (${t.status})`);return t.json()}async fetchText(e){const t=await i(e);if(!t.ok)throw new Error(`Failed to fetch text: ${e} (${t.status})`);return t.text()}async fetchBinary(e){const t=await i(e);if(!t.ok)throw new Error(`Failed to fetch binary: ${e} (${t.status})`);return t.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 at=se(null,"Assets");class ct{build(e){const t=e.wasmModule;t?e.insertResource(at,new it(t)):console.warn("AssetPlugin: No WASM module available")}}const lt=new ct;let ut=null,ht=0,dt=0,ft=0;const pt=new Float32Array(256);function _t(e){ut=e,ht=ut._malloc(64),dt=ut._malloc(64),ft=ut._malloc(1024)}function mt(){ut&&(ht&&(ut._free(ht),ht=0),dt&&(ut._free(dt),dt=0),ft&&(ut._free(ft),ft=0)),ut=null}function gt(){if(!ut)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return ut}const yt={x:1,y:1,z:1,w:1},wt={begin(e){const t=gt();t.HEAPF32.set(e,ht/4),t.draw_begin(ht)},end(){gt().draw_end()},line(e,t,r,n=1){gt().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){gt().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){gt().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){gt().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){gt().draw_circleOutline(e.x,e.y,t,r.x,r.y,r.z,r.w,n,s)},texture(e,t,r,n=yt){gt().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=yt){gt().draw_textureRotated(e.x,e.y,t.x,t.y,r,n,s.x,s.y,s.z,s.w)},setLayer(e){gt().draw_setLayer(e)},setDepth(e){gt().draw_setDepth(e)},getDrawCallCount:()=>ut?ut.draw_getDrawCallCount():0,getPrimitiveCount:()=>ut?ut.draw_getPrimitiveCount():0,setBlendMode(e){gt().draw_setBlendMode(e)},setDepthTest(e){gt().draw_setDepthTest(e)},drawMesh(e,t,r){const n=gt();n.HEAPF32.set(r,dt/4),n.draw_mesh(e,t,dt)},drawMeshWithMaterial(e,t,r){const n=gt(),s=Ve.get(t);if(!s)return;if(wt.setBlendMode(s.blendMode),wt.setDepthTest(s.depthTest),0===s.uniforms.size)return void wt.drawMesh(e,s.shader,r);n.HEAPF32.set(r,dt/4);let o=0,i=0;for(const[e,t]of s.uniforms){const r=vt(e);if(!(r<0)){if(De(t))pt[o++]=10,pt[o++]=r,pt[o++]=t.slot??i++,pt[o++]=t.textureId;else if("number"==typeof t)pt[o++]=1,pt[o++]=r,pt[o++]=t;else if(Array.isArray(t)){pt[o++]=t.length,pt[o++]=r;for(let e=0;e<t.length;e++)pt[o++]=t[e]}else"w"in t?(pt[o++]=4,pt[o++]=r,pt[o++]=t.x,pt[o++]=t.y,pt[o++]=t.z,pt[o++]=t.w):"z"in t?(pt[o++]=3,pt[o++]=r,pt[o++]=t.x,pt[o++]=t.y,pt[o++]=t.z):(pt[o++]=2,pt[o++]=r,pt[o++]=t.x,pt[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(n.HEAPF32.set(pt.subarray(0,o),ft/4),n.draw_meshWithUniforms(e,s.shader,dt,ft,o)):n.draw_mesh(e,s.shader,dt)}},xt={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function vt(e){return xt[e]??-1}var St;!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"}(St||(St={}));let Pt=null,bt=0,Ct=0,Tt=0;function Mt(e){Pt=e,bt=Pt._malloc(262144),Ct=Pt._malloc(65536),Tt=Pt._malloc(256)}function Et(){Pt&&(bt&&Pt._free(bt),Ct&&Pt._free(Ct),Tt&&Pt._free(Tt),bt=0,Ct=0,Tt=0),Pt=null}function At(){if(!Pt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Pt}const Rt={create(e){const t=At(),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,bt/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,Tt,s).set(o),t.geometry_init(r,bt,n,Tt,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,Ct,n).set(e.indices),t.geometry_setIndices16(r,Ct,n)}else{new Uint32Array(t.HEAPU8.buffer,Ct,n).set(e.indices),t.geometry_setIndices32(r,Ct,n)}}return r},updateVertices(e,t,r=0){const n=At(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);n.HEAPF32.set(t,bt/4),n.geometry_updateVertices(e,bt,s,r)},release(e){e>0&&At().geometry_release(e)},isValid:e=>!(!Pt||e<=0)&&Pt.geometry_isValid(e),createQuad(e=1,t=1){const r=e/2,n=t/2;return Rt.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:St.Float2},{name:"a_texCoord",type:St.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,c=(Math.sin(s)+1)/2;r.push(o,i,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Rt.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:St.Float2},{name:"a_texCoord",type:St.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 Rt.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:St.Float2},{name:"a_texCoord",type:St.Float2}],indices:new Uint16Array(i)})}};let Ut=null;function Ft(e){Ut=e}function zt(){Ut&&Wt.isInitialized()&&Wt.shutdown(),Ut=null}function It(){if(!Ut)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ut}const Wt={init:(e,t)=>It().postprocess_init(e,t),shutdown(){It().postprocess_shutdown()},resize(e,t){It().postprocess_resize(e,t)},addPass:(e,t)=>It().postprocess_addPass(e,t),removePass(e){It().postprocess_removePass(e)},setEnabled(e,t){It().postprocess_setPassEnabled(e,t)},isEnabled:e=>It().postprocess_isPassEnabled(e),setUniform(e,t,r){It().postprocess_setUniformFloat(e,t,r)},setUniformVec4(e,t,r){It().postprocess_setUniformVec4(e,t,r.x,r.y,r.z,r.w)},begin(){It().postprocess_begin()},end(){It().postprocess_end()},getPassCount:()=>It().postprocess_getPassCount(),isInitialized:()=>!!Ut&&Ut.postprocess_isInitialized(),setBypass(e){It().postprocess_setBypass(e)},isBypassed:()=>!Ut||Ut.postprocess_isBypassed(),createBlur:()=>Ve.createShader(Bt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>Ve.createShader(Bt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Ve.createShader(Bt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Ve.createShader(Bt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},Bt="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var $t;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}($t||($t={}));let kt=null,Dt=0;function Lt(e){kt=e,Dt=kt._malloc(64)}function Ot(){kt&&Dt&&(kt._free(Dt),Dt=0),kt=null}const Ht={init(e,t){kt?.renderer_init(e,t)},resize(e,t){kt?.renderer_resize(e,t)},begin(e,t){kt&&Dt&&(kt.HEAPF32.set(e,Dt/4),kt.renderer_begin(Dt,t??0))},flush(){kt?.renderer_flush()},end(){kt?.renderer_end()},submitSprites(e){kt&&kt.renderer_submitSprites(e._cpp)},submitSpine(e){kt&&kt.renderer_submitSpine?.(e._cpp)},setStage(e){kt?.renderer_setStage(e)},createRenderTarget:(e,t,r=1)=>kt?.renderer_createTarget(e,t,r)??0,releaseRenderTarget(e){kt?.renderer_releaseTarget(e)},getTargetTexture:e=>kt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>kt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,r,n){kt?.renderer_setClearColor?.(e,t,r,n)},getStats:()=>kt?{drawCalls:kt.renderer_getDrawCalls(),triangles:kt.renderer_getTriangles(),sprites:kt.renderer_getSprites(),spine:kt.renderer_getSpine?.()??0,meshes:kt.renderer_getMeshes(),culled:kt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let Nt=null;function jt(e){Nt=e}function Xt(){Nt=null}const Gt={enable(){Nt?.gl_enableErrorCheck(!0)},disable(){Nt?.gl_enableErrorCheck(!1)},check:e=>Nt?.gl_checkErrors(e)??0,diagnose(){Nt?.renderer_diagnose()}},Vt=new Map;function qt(e,t){Vt.set(e,t)}function Yt(e){Vt.delete(e)}function Kt(){Vt.clear()}class Jt{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:r,width:n,height:s,elapsed:o}=e;Ht.resize(n,s),Wt.isInitialized()&&Wt.getPassCount()>0&&!Wt.isBypassed()&&Wt.resize(n,s),Ht.begin(r),Ht.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,o):Ht.submitSpine(t),Ht.flush();const i=Vt;if(i.size>0){wt.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)}wt.end();for(const t of e)Yt(t)}Ht.end()}}class Qt{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 r=t/1e3;for(this.updateTime(r),this.runSchedule(ge.First),this.fixedAccumulator_+=r;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ge.FixedPreUpdate),this.runSchedule(ge.FixedUpdate),this.runSchedule(ge.FixedPostUpdate);this.runSchedule(ge.PreUpdate),this.runSchedule(ge.Update),this.runSchedule(ge.PostUpdate),this.runSchedule(ge.Last),requestAnimationFrame(this.mainLoop)},this.world_=new Ae,this.resources_=new ce;for(const e of Object.values(ge))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Qt}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(ge.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(ge.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 be(this.world_,this.resources_),this.resources_.insert(le,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(ge.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Xt(),Ot(),zt(),Et(),Xe(),mt()}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(le),r={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(le,r)}}function Zt(e,t){const r=Qt.new(),n=new e.Registry;r.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),_t(e),je(e),Mt(e),Ft(e),Lt(e),jt(e);const s=new Jt;r.pipeline_=s;let o=d();const i=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}=i(),r=function(e,t,r){const n=e.entityCount()+1e3;for(let s=0;s<n;s++){if(!e.valid(s)||!e.hasCamera(s)||!e.hasLocalTransform(s))continue;const o=e.getCamera(s);if(!o.isActive)continue;const i=e.getLocalTransform(s),a=t/r;let c;if(1===o.projectionType){let t=o.orthoSize;const r=rr(e,n);if(r){t=nr(r.designResolution.y/2,r.designResolution.x/r.designResolution.y,a,r.scaleMode,r.matchWidthOrHeight)}const s=t*a;c=sr(-s,s,-t,t,-o.farPlane,o.farPlane)}else c=or(o.fov*Math.PI/180,a,o.nearPlane,o.farPlane);return ar(c,ir(i.position.x,i.position.y,i.position.z))}return tr}(n,e,t),a=(d()-o)/1e3;s.render({registry:{_cpp:n},viewProjection:r,width:e,height:t,elapsed:a})}};return r.addSystemToSchedule(ge.Last,a),r.addPlugin(lt),r.addPlugin(Ee),r.addPlugin($e),r}function er(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}}const tr=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function rr(e,t){for(let r=0;r<t;r++){if(!e.valid(r)||!e.hasCanvas(r))continue;return e.getCanvas(r)}return null}function nr(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 sr(e,t,r,n,s,o){const i=new Float32Array(16),a=t-e,c=n-r,l=o-s;return i[0]=2/a,i[5]=2/c,i[10]=-2/l,i[12]=-(t+e)/a,i[13]=-(n+r)/c,i[14]=-(o+s)/l,i[15]=1,i}function or(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 ir(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 ar(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}function cr(e,t){const r=e.getResourceManager(),n=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,n);const s=r.createTexture(t.width,t.height,n,t.pixels.length,1);return e._free(n),s}function lr(e,t){const r=t.substring(0,t.lastIndexOf("/"));r&&e.FS.mkdirTree(r)}function ur(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}async function hr(e,t,r,n,s){const o=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]=cr(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,o);let i={};s&&(i=await async function(e,t,r,n){const s={};for(const o of r.entities)for(const r of o.components){if("SpineAnimation"!==r.type||!r.data)continue;const o=r.data.skeletonPath,i=r.data.atlasPath;if(!o||!i)continue;const a=n.resolvePath(o),c=n.resolvePath(i);try{const r=n.readText(i),l=a.endsWith(".skel");lr(t,a),l?t.FS.writeFile(a,n.readBinary(o)):t.FS.writeFile(a,n.readText(o));const u=t.spine_loadSkeleton(a,r,r.length,l);if(u<0)continue;s[o]=u;const h=ur(r),d=c.substring(0,c.lastIndexOf("/"));for(let r=0;r<h.length;r++){const s=d+"/"+h[r];try{const o=n.loadPixelsRaw?await n.loadPixelsRaw(s):await n.loadPixels(s),i=cr(e,o),a=e.getResourceManager().getTextureGLId(i);t.spine_setAtlasPageTexture(u,r,a,o.width,o.height)}catch{}}}catch{}}return s}(t,s,r,n));const a=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=Ve.createShader(e.vertexSource,e.fragmentSource),n[o]=i),r[s]=Ve.createFromAsset(e,i)}catch{r[s]=0}}return r}(r,n),c=tt(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,q);s&&(s.texture=r[n.data.texture]||0,e.insert(t,q,s))}}}(e.world,r,o,c),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,q);r&&(r.material=s,e.insert(t,q,r))}else if("SpineAnimation"===n.type){const r=e.get(t,ee);r&&(r.material=s,e.insert(t,ee,r))}}}}(e.world,r,a,c),s){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.spine_createInstance(i);if(a<0)continue;const c=n.get(o.id);void 0!==c&&(s[c]=a),t.data.animation&&e.spine_playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.spine_setSkin(a,t.data.skin)}return s}(s,r,i,c);!function(e,t,r,n){let s=0;e.setSpineRenderer((e,o)=>{let i=o-s;s=o,(i<=0||i>.5)&&(i=1/60);for(const e in n){const s=n[e];r.spine_update(s,i);const o=r.spine_getMeshBatchCount(s);for(let e=0;e<o;e++){const n=r.spine_getMeshBatchVertexCount(s,e),o=r.spine_getMeshBatchIndexCount(s,e);if(!n||!o)continue;const i=8*n*4,a=2*o,c=r._malloc(i),l=r._malloc(a),u=r._malloc(4),h=r._malloc(4);r.spine_getMeshBatchData(s,e,c,l,u,h);const d=r.HEAPU32[u>>2],f=r.HEAPU32[h>>2],p=new Float32Array(r.HEAPF32.buffer,c,8*n),_=new Uint16Array(r.HEAPU8.buffer,l,o),m=t._malloc(i),g=t._malloc(a);t.HEAPF32.set(p,m>>2),new Uint16Array(t.HEAPU8.buffer,g,o).set(_),t.renderer_submitTriangles(m,n,g,o,d,f,0),t._free(m),t._free(g),r._free(c),r._free(l),r._free(u),r._free(h)}}})}(e,t,s,n)}}class dr{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}}class fr{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),r=new dr(this.baseUrl_);await r.prefetch(t);let n=null;const s=this.app_.__spineInitPromise;if(s){n=(await s).controller.module}await hr(this.app_,this.app_.wasmModule,t,r,n),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const r=e.getEntitiesWithComponents([Y]);for(const n of r){if(e.get(n,Y).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([K]);for(const s of n){const n=e.get(s,K);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,G,o);const i={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:r,priority:0,showFrustum:!0};e.insert(s,Y,i)}}}const pr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),r=Ht.createRenderTarget(e.width,e.height,t);return{_handle:r,textureId:Ht.getTargetTexture(r),width:e.width,height:e.height}},release(e){Ht.releaseRenderTarget(e._handle)},resize:(e,t,r)=>(Ht.releaseRenderTarget(e._handle),pr.create({width:t,height:r,depth:!0})),begin(e,t){Ht.begin(t,e._handle)},end(){Ht.end()},getDepthTexture:e=>Ht.getTargetDepthTexture(e._handle)};let _r=!1;function mr(e){_r=e}function gr(){return _r}function yr(){return!_r}var wr;M||(M=!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 f(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 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),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=wr=E,console.log(`[ESEngine] Platform: ${wr.name}`);export{Qt as App,ct as AssetPlugin,it as AssetServer,at as Assets,ot as AsyncCache,ke as BlendMode,Y as Camera,K as Canvas,Z as Children,pe as Commands,me as CommandsInstance,St as DataType,wt as Draw,_e as EntityCommands,Gt as GLDebug,Rt as Geometry,A as INVALID_ENTITY,R as INVALID_TEXTURE,Te as Input,Me as InputPlugin,Ce as InputState,G as LocalTransform,Ve as Material,et as MaterialLoader,ue as Mut,Q as Parent,Wt as PostProcess,fr as PreviewPlugin,de as Query,fe as QueryInstance,Jt as RenderPipeline,$t as RenderStage,pr as RenderTexture,Ht as Renderer,oe as Res,ie as ResMut,ge as Schedule,Ze as ShaderSources,ee as SpineAnimation,q as Sprite,be as SystemRunner,ze as Text,Re as TextAlign,Fe as TextOverflow,Be as TextPlugin,Ie as TextRenderer,Ue as TextVerticalAlign,le as Time,We as UIRect,J as Velocity,dr as WebAssetProvider,Ae as World,V as WorldTransform,Se as addStartupSystem,ve as addSystem,Pe as addSystemToSchedule,lt as assetPlugin,Kt as clearDrawCallbacks,H as clearUserComponents,I as color,Zt as createWebApp,D as defineComponent,se as defineResource,we as defineSystem,L as defineTag,er as flushPendingSystems,re as getComponentDefaults,t as getPlatform,n as getPlatformType,O as getUserComponent,_t as initDrawAPI,jt as initGLDebugAPI,Mt as initGeometryAPI,je as initMaterialAPI,Ft as initPostProcessAPI,Lt as initRendererAPI,Ee as inputPlugin,X as isBuiltinComponent,gr as isEditor,r as isPlatformInitialized,yr as isRuntime,De as isTextureRef,s as isWeChat,o as isWeb,nt as loadComponent,hr as loadRuntimeScene,tt as loadSceneData,rt as loadSceneWithAssets,i as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,W as quat,qt as registerDrawCallback,Qe as registerMaterialCallback,mr as setEditorMode,mt as shutdownDrawAPI,Xt as shutdownGLDebugAPI,Et as shutdownGeometryAPI,Xe as shutdownMaterialAPI,zt as shutdownPostProcessAPI,Ot as shutdownRendererAPI,$e as textPlugin,Yt as unregisterDrawCallback,st as updateCameraAspectRatio,U as vec2,F as vec3,z as vec4,w as wxFileExists,x as wxFileExistsSync,C as wxGetImagePixels,b as wxLoadImage,T as wxLoadImagePixels,g as wxReadFile,y as wxReadTextFile,v as wxWriteFile};//# sourceMappingURL=index.wechat.js.mapdiff --git a/desktop/public/sdk/esm/esengine.d.ts b/desktop/public/sdk/esm/esengine.d.tsindex aa96a6b7a..13270506e 100644--- a/desktop/public/sdk/esm/esengine.d.ts+++ b/desktop/public/sdk/esm/esengine.d.ts@@ -1131,9 +1131,10 @@ declare function loadRuntimeScene(app: App, module: ESEngineModule, sceneData: Sdeclare class PreviewPlugin implements Plugin {private sceneUrl_;+ private baseUrl_;private app_;private loadPromise_;- constructor(sceneUrl: string);+ constructor(sceneUrl: string, baseUrl?: string);build(app: App): void;/*** @brief Wait for scene loading to complete@@ -1143,6 +1144,28 @@ declare class PreviewPlugin implements Plugin {private ensureCamera;}+/**+ * @file WebAssetProvider.ts+ * @brief RuntimeAssetProvider for browser-based preview+ */++declare class WebAssetProvider implements RuntimeAssetProvider {+ private textCache_;+ private binaryCache_;+ private baseUrl_;+ constructor(baseUrl: string);+ prefetch(sceneData: SceneData): Promise<void>;+ readText(ref: string): string;+ readBinary(ref: string): Uint8Array;+ loadPixels(ref: string): Promise<{+ width: number;+ height: number;+ pixels: Uint8Array;+ }>;+ resolvePath(ref: string): string;+ private resolveUrl;+}+/*** @file types.ts* @brief Platform adapter interface definitions@@ -1653,5 +1676,5 @@ declare const GLDebug: {diagnose(): void;};-export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BlendMode, Camera, Canvas, Children, Commands, CommandsInstance, DataType, Draw, EntityCommands, GLDebug, Geometry, INVALID_ENTITY, INVALID_TEXTURE, Input, InputPlugin, InputState, LocalTransform, Material, MaterialLoader, Mut, Parent, PostProcess, PreviewPlugin, Query, QueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, Schedule, ShaderSources, SpineAnimation, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIRect, Velocity, World, WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, assetPlugin, clearDrawCallbacks, clearUserComponents, color, createWebApp, defineComponent, defineResource, defineSystem, defineTag, flushPendingSystems, getComponentDefaults, getPlatform, getPlatformType, getUserComponent, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, inputPlugin, isBuiltinComponent, isEditor, isPlatformInitialized, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadRuntimeScene, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, registerDrawCallback, registerMaterialCallback, setEditorMode, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textPlugin, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4 };+export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BlendMode, Camera, Canvas, Children, Commands, CommandsInstance, DataType, Draw, EntityCommands, GLDebug, Geometry, INVALID_ENTITY, INVALID_TEXTURE, Input, InputPlugin, InputState, LocalTransform, Material, MaterialLoader, Mut, Parent, PostProcess, PreviewPlugin, Query, QueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, Schedule, ShaderSources, SpineAnimation, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIRect, Velocity, WebAssetProvider, World, WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, assetPlugin, clearDrawCallbacks, clearUserComponents, color, createWebApp, defineComponent, defineResource, defineSystem, defineTag, flushPendingSystems, getComponentDefaults, getPlatform, getPlatformType, getUserComponent, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, inputPlugin, isBuiltinComponent, isEditor, isPlatformInitialized, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadRuntimeScene, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, registerDrawCallback, registerMaterialCallback, setEditorMode, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textPlugin, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4 };export type { AnyComponentDef, AssetBundle, AssetManifest, AssetsData, BuiltinComponentDef, CameraData, CanvasData, ChildrenData, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DrawAPI, DrawCallback, ESEngineModule, Entity, FileLoadOptions, GeometryHandle, GeometryOptions, InferParam, InferParams, LoadedMaterial, LocalTransformData, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, ParentData, PlatformAdapter, PlatformRequestOptions, PlatformResponse, PlatformType, Plugin, Quat, QueryDescriptor, QueryResult, RenderParams, RenderStats, RenderTargetHandle, RenderTextureHandle, RenderTextureOptions, ResDescriptor, ResMutDescriptor, ResourceDef, RuntimeAssetProvider, SceneComponentData, SceneData, SceneEntityData, SceneLoadOptions, ShaderHandle, ShaderLoader, SliceBorder, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteData, SystemDef, SystemParam, TextData, TextRenderResult, TextureHandle, TextureInfo, TextureRef, TimeData, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WorldTransformData };diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.jsindex 86493807a..ffeb548d6 100644--- a/desktop/public/sdk/esm/esengine.js+++ b/desktop/public/sdk/esm/esengine.js@@ -1,2 +1,2 @@-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function r(){return e?.name??null}function s(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}const f=new class{constructor(){this.name="web"}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),r={};return n.headers.forEach((e,t)=>{r[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:r,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const r=await WebAssembly.instantiate(n,t);return{instance:r.instance,module:r.module}}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){const n=t??document.querySelector("canvas")??document.body;document.addEventListener("keydown",t=>e.onKeyDown(t.code)),document.addEventListener("keyup",t=>e.onKeyUp(t.code)),n.addEventListener("mousemove",t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)}),n.addEventListener("mousedown",t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)}),n.addEventListener("mouseup",t=>{e.onPointerUp(t.button)}),n.addEventListener("touchstart",t=>{const r=t.touches[0];if(r){const t=n.getBoundingClientRect();e.onPointerDown(0,r.clientX-t.left,r.clientY-t.top)}}),n.addEventListener("touchmove",t=>{const r=t.touches[0];if(r){const t=n.getBoundingClientRect();e.onPointerMove(r.clientX-t.left,r.clientY-t.top)}}),n.addEventListener("touchend",()=>{e.onPointerUp(0)}),n.addEventListener("wheel",t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)})}},p=0,_=4294967295,m=(e=0,t=0)=>({x:e,y:t}),g=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),y=(e=0,t=0,n=0,r=1)=>({x:e,y:t,z:n,w:r}),w=(e=1,t=1,n=1,r=1)=>({x:e,y:t,z:n,w:r}),x=(e=1,t=0,n=0,r=0)=>({w:e,x:t,y:n,z:r});let v=0;function S(e,t){const n=++v;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function P(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function C(e,t){const n=P(),r=n.get(e);if(r)return r;const s=S(e,t);return n.set(e,s),M(e,t,!1),s}function T(e){const t=P(),n=t.get(e);if(n)return n;const r=S(e,{});return t.set(e,r),M(e,{},!0),r}function b(e){return P().get(e)}function R(){P().clear()}function M(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function E(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function A(e){return!0===e._builtin}const F=E("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),U=E("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=E("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}),I=E("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0}),B=E("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),k=E("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),$=E("Parent",{entity:0}),L=E("Children",{entities:[]}),D=E("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}),W={LocalTransform:F,WorldTransform:U,Sprite:z,Camera:I,Canvas:B,Velocity:k,Parent:$,Children:L,SpineAnimation:D};function H(e){const t=W[e];if(t)return{...t._default};const n=b(e);return n?{...n._default}:null}let O=0;function N(e,t){const n=++O;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function j(e){return{_type:"res",_resource:e}}function X(e){return{_type:"res_mut",_resource:e}}class V{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 G{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 V(this.get(e),t=>this.set(e,t))}}const Y=N({delta:0,elapsed:0,frameCount:0},"Time");function K(e){return{_type:"mut",_component:e}}function q(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function J(...e){return function(e,t=[],n=[]){const r=[];return e.forEach((e,t)=>{q(e)&&r.push(t)}),{_type:"query",_components:e,_mutIndices:r,_with:t,_without:n}}(e)}class Q{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:n,_without:r}=this.descriptor_,s=e.map(e=>this.getActualComponent(e)),o=[...s,...n],i=this.world_.getEntitiesWithComponents(o);let a=null,c=[];try{for(const e of i){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 o=s.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:s[e],data:o[e]});a=e,yield[e,...o]}}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 Z(){return{_type:"commands"}}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 n;return n=A(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 te{constructor(e,t){this.pending_=[],this.world_=e,this.resources_=t}spawn(){return new ee(this,null)}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,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.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 ne;!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"}(ne||(ne={}));let re=0;function se(e,t,n){const r=++re;return{_id:Symbol(`System_${r}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${r}`}}function oe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function ie(e){oe().push({schedule:ne.Update,system:e})}function ae(e){oe().push({schedule:ne.Startup,system:e})}function ce(e,t){oe().push({schedule:e,system:t})}class le{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 Q(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 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 he=N(new ue,"Input");class de{constructor(e){this.target_=e??null}build(e){const n=new ue;e.insertResource(he,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,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(ne.First,se([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const fe=new de;class pe{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return A(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return A(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return A(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){A(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 _e,me,ge;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(_e||(_e={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(me||(me={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(ge||(ge={}));const ye=C("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:_e.Left,verticalAlign:me.Top,wordWrap:!0,overflow:ge.Visible,lineHeight:1.2,dirty:!0});class we{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,o=s?t.size.x:0,i=s?t.size.y:0,a=e.wordWrap&&s;let c=this.wrapText(e.content,a?o: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(o):h+2*u,p=s?Math.ceil(i):d+2*u;if(s&&e.overflow===ge.Ellipsis&&d>i){const e=Math.floor(i/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,o)}}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===ge.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 me.Top:x=u;break;case me.Middle:x=(p-w)/2;break;case me.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let r;switch(e.align){case _e.Left:r=u;break;case _e.Center:r=f/2;break;case _e.Right:r=f-u;break;default:r=u}n.fillText(t,r,v),v+=l}s&&e.overflow===ge.Clip&&n.restore();const S=n.getImageData(0,0,f,p),P=new Uint8Array(S.data.buffer),C=this.flipVertically(P,f,p),T=this.module.getResourceManager(),b=this.module._malloc(C.length);this.module.HEAPU8.set(C,b);const R=T.createTexture(f,p,b,C.length,1);return this.module._free(b),{textureHandle:R,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 _e.Left:return"left";case _e.Center:return"center";case _e.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}flipVertically(e,t,n){const r=4*t,s=new Uint8Array(e.length);for(let t=0;t<n;t++){const o=t*r,i=(n-1-t)*r;s.set(e.subarray(o,o+r),i)}return s}}const xe=C("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class ve{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new we(t),r=e.world;e.addSystemToSchedule(ne.PreUpdate,se([],()=>{const e=r.getEntitiesWithComponents([ye]);for(const t of e){const e=r.get(t,ye);if(!e.dirty)continue;r.has(t,z)||r.insert(t,z,{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 s=r.has(t,xe)?r.get(t,xe):null,o=n.renderForEntity(t,e,s),i=r.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},r.insert(t,z,i),e.dirty=!1}}))}}const Se=new ve;var Pe;function Ce(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"}(Pe||(Pe={}));let Te=null,be=null,Re=1;const Me=new Map;function Ee(e){Te=e,be=e.getResourceManager(),$e()}function Ae(){0!==Ie&&Te&&(Te._free(Ie),Ie=0),Me.clear(),Re=1,ze=!1,be=null,Te=null}function Fe(){if(!be)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return be}const Ue={createShader:(e,t)=>Fe().createShader(e,t),releaseShader(e){e>0&&Fe().releaseShader(e)},create(e){const t=Re++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Pe.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,r]of Object.entries(e.uniforms))n.uniforms.set(t,r);return Me.set(t,n),t},get:e=>Me.get(e),setUniform(e,t,n){const r=Me.get(e);r&&r.uniforms.set(t,n)},getUniform(e,t){const n=Me.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Me.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Me.get(e);return t?.blendMode??Pe.Normal},setDepthTest(e,t){const n=Me.get(e);n&&(n.depthTest=t)},getShader(e){const t=Me.get(e);return t?.shader??0},release(e){Me.delete(e)},isValid:e=>Me.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??Pe.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Me.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Re++,r={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Me.set(n,r),n},toAssetData(e,t){const n=Me.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=Me.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let ze=!1,Ie=0;const Be=4096;function ke(e){const t=(0===Ie&&Te&&(Ie=Te._malloc(Be)),Ie);if(0===t||!Te)return{ptr:0,count:0};let n=0,r=0;const s=Te.HEAPU8,o=Te.HEAPU32,i=Te.HEAPF32;for(const[a,c]of e){if(n+128>Be)break;const e=(new TextEncoder).encode(a),l=e.length,u=4*Math.ceil(l/4);o[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]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=d[e],n+=4;r++}return{ptr:t,count:r}}function $e(){if(!Te||ze)return;Te.materialDataProvider=(e,t,n,r,s)=>{const o=Me.get(e);if(!o)return Te.HEAPU32[t>>2]=0,Te.HEAPU32[n>>2]=0,Te.HEAPU32[r>>2]=0,void(Te.HEAPU32[s>>2]=0);Te.HEAPU32[t>>2]=o.shader,Te.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=ke(o.uniforms);Te.HEAPU32[r>>2]=i,Te.HEAPU32[s>>2]=a},ze=!0}const Le={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};let De=null,We=0,He=0,Oe=0;const Ne=new Float32Array(256);function je(e){De=e,We=De._malloc(64),He=De._malloc(64),Oe=De._malloc(1024)}function Xe(){De&&(We&&(De._free(We),We=0),He&&(De._free(He),He=0),Oe&&(De._free(Oe),Oe=0)),De=null}function Ve(){if(!De)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return De}const Ge={x:1,y:1,z:1,w:1},Ye={begin(e){const t=Ve();t.HEAPF32.set(e,We/4),t.draw_begin(We)},end(){Ve().draw_end()},line(e,t,n,r=1){Ve().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){Ve().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){Ve().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){Ve().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){Ve().draw_circleOutline(e.x,e.y,t,n.x,n.y,n.z,n.w,r,s)},texture(e,t,n,r=Ge){Ve().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=Ge){Ve().draw_textureRotated(e.x,e.y,t.x,t.y,n,r,s.x,s.y,s.z,s.w)},setLayer(e){Ve().draw_setLayer(e)},setDepth(e){Ve().draw_setDepth(e)},getDrawCallCount:()=>De?De.draw_getDrawCallCount():0,getPrimitiveCount:()=>De?De.draw_getPrimitiveCount():0,setBlendMode(e){Ve().draw_setBlendMode(e)},setDepthTest(e){Ve().draw_setDepthTest(e)},drawMesh(e,t,n){const r=Ve();r.HEAPF32.set(n,He/4),r.draw_mesh(e,t,He)},drawMeshWithMaterial(e,t,n){const r=Ve(),s=Ue.get(t);if(!s)return;if(Ye.setBlendMode(s.blendMode),Ye.setDepthTest(s.depthTest),0===s.uniforms.size)return void Ye.drawMesh(e,s.shader,n);r.HEAPF32.set(n,He/4);let o=0,i=0;for(const[e,t]of s.uniforms){const n=qe(e);if(!(n<0)){if(Ce(t))Ne[o++]=10,Ne[o++]=n,Ne[o++]=t.slot??i++,Ne[o++]=t.textureId;else if("number"==typeof t)Ne[o++]=1,Ne[o++]=n,Ne[o++]=t;else if(Array.isArray(t)){Ne[o++]=t.length,Ne[o++]=n;for(let e=0;e<t.length;e++)Ne[o++]=t[e]}else"w"in t?(Ne[o++]=4,Ne[o++]=n,Ne[o++]=t.x,Ne[o++]=t.y,Ne[o++]=t.z,Ne[o++]=t.w):"z"in t?(Ne[o++]=3,Ne[o++]=n,Ne[o++]=t.x,Ne[o++]=t.y,Ne[o++]=t.z):(Ne[o++]=2,Ne[o++]=n,Ne[o++]=t.x,Ne[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(r.HEAPF32.set(Ne.subarray(0,o),Oe/4),r.draw_meshWithUniforms(e,s.shader,He,Oe,o)):r.draw_mesh(e,s.shader,He)}},Ke={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 qe(e){return Ke[e]??-1}var Je;!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"}(Je||(Je={}));let Qe=null,Ze=0,et=0,tt=0;function nt(e){Qe=e,Ze=Qe._malloc(262144),et=Qe._malloc(65536),tt=Qe._malloc(256)}function rt(){Qe&&(Ze&&Qe._free(Ze),et&&Qe._free(et),tt&&Qe._free(tt),Ze=0,et=0,tt=0),Qe=null}function st(){if(!Qe)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Qe}const ot={create(e){const t=st(),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,Ze/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,tt,s).set(o),t.geometry_init(n,Ze,r,tt,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,et,r).set(e.indices),t.geometry_setIndices16(n,et,r)}else{new Uint32Array(t.HEAPU8.buffer,et,r).set(e.indices),t.geometry_setIndices32(n,et,r)}}return n},updateVertices(e,t,n=0){const r=st(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);r.HEAPF32.set(t,Ze/4),r.geometry_updateVertices(e,Ze,s,n)},release(e){e>0&&st().geometry_release(e)},isValid:e=>!(!Qe||e<=0)&&Qe.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,r=t/2;return ot.create({vertices:new Float32Array([-n,-r,0,0,n,-r,1,0,n,r,1,1,-n,r,0,1]),layout:[{name:"a_position",type:Je.Float2},{name:"a_texCoord",type:Je.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,o=Math.cos(s)*e,i=Math.sin(s)*e,a=(Math.cos(s)+1)/2,c=(Math.sin(s)+1)/2;n.push(o,i,a,c)}for(let e=1;e<=t;e++)r.push(0,e,e+1);return ot.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Je.Float2},{name:"a_texCoord",type:Je.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 o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),r=Math.max(r,o.x),s=Math.max(s,o.y);const o=[];for(const i of e){const e=(i.x-t)/(r-t),a=(i.y-n)/(s-n);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return ot.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Je.Float2},{name:"a_texCoord",type:Je.Float2}],indices:new Uint16Array(i)})}};let it=null;function at(e){it=e}function ct(){it&&ut.isInitialized()&&ut.shutdown(),it=null}function lt(){if(!it)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return it}const ut={init:(e,t)=>lt().postprocess_init(e,t),shutdown(){lt().postprocess_shutdown()},resize(e,t){lt().postprocess_resize(e,t)},addPass:(e,t)=>lt().postprocess_addPass(e,t),removePass(e){lt().postprocess_removePass(e)},setEnabled(e,t){lt().postprocess_setPassEnabled(e,t)},isEnabled:e=>lt().postprocess_isPassEnabled(e),setUniform(e,t,n){lt().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){lt().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){lt().postprocess_begin()},end(){lt().postprocess_end()},getPassCount:()=>lt().postprocess_getPassCount(),isInitialized:()=>!!it&&it.postprocess_isInitialized(),setBypass(e){lt().postprocess_setBypass(e)},isBypassed:()=>!it||it.postprocess_isBypassed(),createBlur:()=>Ue.createShader(ht,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>Ue.createShader(ht,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Ue.createShader(ht,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Ue.createShader(ht,"#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")},ht="#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 dt;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(dt||(dt={}));let ft=null,pt=0;function _t(e){ft=e,pt=ft._malloc(64)}function mt(){ft&&pt&&(ft._free(pt),pt=0),ft=null}const gt={init(e,t){ft?.renderer_init(e,t)},resize(e,t){ft?.renderer_resize(e,t)},begin(e,t){ft&&pt&&(ft.HEAPF32.set(e,pt/4),ft.renderer_begin(pt,t??0))},flush(){ft?.renderer_flush()},end(){ft?.renderer_end()},submitSprites(e){ft&&ft.renderer_submitSprites(e._cpp)},submitSpine(e){ft&&ft.renderer_submitSpine?.(e._cpp)},setStage(e){ft?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>ft?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){ft?.renderer_releaseTarget(e)},getTargetTexture:e=>ft?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>ft?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,r){ft?.renderer_setClearColor?.(e,t,n,r)},getStats:()=>ft?{drawCalls:ft.renderer_getDrawCalls(),triangles:ft.renderer_getTriangles(),sprites:ft.renderer_getSprites(),spine:ft.renderer_getSpine?.()??0,meshes:ft.renderer_getMeshes(),culled:ft.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let yt=null;function wt(e){yt=e}function xt(){yt=null}const vt={enable(){yt?.gl_enableErrorCheck(!0)},disable(){yt?.gl_enableErrorCheck(!1)},check:e=>yt?.gl_checkErrors(e)??0,diagnose(){yt?.renderer_diagnose()}},St=new Map;function Pt(e,t){St.set(e,t)}function Ct(e){St.delete(e)}function Tt(){St.clear()}class bt{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:n,width:r,height:s,elapsed:o}=e;gt.resize(r,s),ut.isInitialized()&&ut.getPassCount()>0&&!ut.isBypassed()&&ut.resize(r,s),gt.begin(n),gt.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,o):gt.submitSpine(t),gt.flush();const i=St;if(i.size>0){Ye.begin(n);const e=[];for(const[t,n]of i.entries())try{n(o)}catch(n){console.error(`[CustomDraw] callback '${t}' error:`,n),e.push(t)}Ye.end();for(const t of e)Ct(t)}gt.end()}}class Rt{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(ne.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ne.FixedPreUpdate),this.runSchedule(ne.FixedUpdate),this.runSchedule(ne.FixedPostUpdate);this.runSchedule(ne.PreUpdate),this.runSchedule(ne.Update),this.runSchedule(ne.PostUpdate),this.runSchedule(ne.Last),requestAnimationFrame(this.mainLoop)},this.world_=new pe,this.resources_=new G;for(const e of Object.values(ne))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Rt}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(ne.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(ne.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 le(this.world_,this.resources_),this.resources_.insert(Y,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(ne.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,xt(),mt(),ct(),rt(),Ae(),Xe()}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(Y),n={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(Y,n)}}function Mt(e,t){const n=Rt.new(),r=new e.Registry;n.connectCpp(r,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),je(e),Ee(e),nt(e),at(e),_t(e),wt(e);const s=new bt;n.pipeline_=s;let o=d();const i=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}=i(),n=function(e,t,n){const r=e.entityCount()+1e3;for(let s=0;s<r;s++){if(!e.valid(s)||!e.hasCamera(s)||!e.hasLocalTransform(s))continue;const o=e.getCamera(s);if(!o.isActive)continue;const i=e.getLocalTransform(s),a=t/n;let c;if(1===o.projectionType){let t=o.orthoSize;const n=Ft(e,r);if(n){t=Ut(n.designResolution.y/2,n.designResolution.x/n.designResolution.y,a,n.scaleMode,n.matchWidthOrHeight)}const s=t*a;c=zt(-s,s,-t,t,-o.farPlane,o.farPlane)}else c=It(o.fov*Math.PI/180,a,o.nearPlane,o.farPlane);return kt(c,Bt(i.position.x,i.position.y,i.position.z))}return At}(r,e,t),a=(d()-o)/1e3;s.render({registry:{_cpp:r},viewProjection:n,width:e,height:t,elapsed:a})}};return n.addSystemToSchedule(ne.Last,a),n.addPlugin(fe),n.addPlugin(Se),n}function Et(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 At=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ft(e,t){for(let n=0;n<t;n++){if(!e.valid(n)||!e.hasCanvas(n))continue;return e.getCanvas(n)}return null}function Ut(e,t,n,r,s){const o=e*t/n,i=e;switch(r){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=s;return Math.pow(o,1-e)*Math.pow(i,e)}}}function zt(e,t,n,r,s,o){const i=new Float32Array(16),a=t-e,c=r-n,l=o-s;return i[0]=2/a,i[5]=2/c,i[10]=-2/l,i[12]=-(t+e)/a,i[13]=-(r+n)/c,i[14]=-(o+s)/l,i[15]=1,i}function It(e,t,n,r){const s=new Float32Array(16),o=1/Math.tan(e/2),i=n-r;return s[0]=o/t,s[5]=o,s[10]=(r+n)/i,s[11]=-1,s[14]=2*r*n/i,s}function Bt(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 kt(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}class $t{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const n=this.pending_.get(e);if(n)return n;const 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&&(Ue.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ue.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await 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),o=await this.shaderLoader_.load(s);return{handle:Ue.createFromAsset(r,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function Lt(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)Wt(e,t,n)}for(const r of t.entities)if(null!==r.parent){const t=n.get(r.id),s=n.get(r.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}return n}async function Dt(e,t,n){const r=new Map,s=n?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();r.set(i.id,t);for(const r of i.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,o.set(t,r)}catch(t){console.warn(`Failed to load texture: ${r}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await 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,o=e.atlasPath;if(t&&o){const e=await s.loadSpine(t,o,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Wt(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=o.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}function Wt(e,t,n){const r=n.data;switch(n.type){case"LocalTransform":e.insert(t,F,r);break;case"Sprite":e.insert(t,z,r);break;case"Camera":e.insert(t,I,r);break;case"Canvas":e.insert(t,B,r);break;case"Text":e.insert(t,ye,r);break;case"SpineAnimation":e.insert(t,D,r);break;case"UIRect":e.insert(t,xe,r);break;default:{const s=b(n.type);s?e.insert(t,s,r):console.warn(`Unknown component type: ${n.type}`);break}}}function Ht(e,t){const n=e.getEntitiesWithComponents([I]);for(const r of n){const n=e.get(r,I);n&&(n.aspectRatio=t,e.insert(r,I,n))}}class Ot{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r)return r;const s=t();this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class Nt{constructor(e){this.textureCache_=new Ot,this.shaderCache_=new Ot,this.jsonCache_=new Ot,this.textCache_=new Ot,this.binaryCache_=new Ot,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,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 $t(t)}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),o=await fetch(s);if(!o.ok)return{success:!1,error:`Failed to fetch atlas: ${s}`};const i=await o.text();if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const a=t.substring(0,t.lastIndexOf("/")),c=this.parseAtlasTextures(i);for(const e of c){const t=a?`${a}/${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 l=this.resolveUrl(e,n),u=await fetch(l);if(!u.ok)return{success:!1,error:`Failed to fetch skeleton: ${l}`};const h=e.endsWith(".skel")?new Uint8Array(await u.arrayBuffer()):await u.text();return this.writeToVirtualFS(e,h)?(this.loadedSpines_.add(r),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return Dt(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];if(e.textures)for(const r of e.textures)n.push(this.loadTexture(r).then(e=>{t.textures.set(r,e)}));if(e.materials)for(const r of e.materials)n.push(this.loadMaterial(r).then(e=>{t.materials.set(r,e)}));if(e.spine)for(const r of e.spine){const e=`${r.skeleton}:${r.atlas}`;n.push(this.loadSpine(r.skeleton,r.atlas,r.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const r of e.json)n.push(this.loadJson(r).then(e=>{t.json.set(r,e)}));if(e.text)for(const r of e.text)n.push(this.loadText(r).then(e=>{t.text.set(r,e)}));if(e.binary)for(const r of e.binary)n.push(this.loadBinary(r).then(e=>{t.binary.set(r,e)}));return await Promise.all(n),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){return new Promise((t,n)=>{const r=new Image;r.crossOrigin="anonymous",r.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(r,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void t(e)}catch{}t(r)},r.onerror=()=>n(new Error(`Failed to load image: ${e}`)),r.src=e})}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 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,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_.save(),r&&(this.ctx_.translate(0,n),this.ctx_.scale(1,-1)),this.ctx_.drawImage(e,0,0),this.ctx_.restore();const s=this.ctx_.getImageData(0,0,t,n),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 c=i.createTexture(t,n,a,o.length,1);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){if(!await l(e))throw new Error(`Shader file not found: ${e}`);const t=await c(e);if(!t)throw new Error(`Failed to read shader file: ${e}`);const{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Ue.createShader(n,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}}async fetchJson(e){const t=await i(e);if(!t.ok)throw new Error(`Failed to fetch JSON: ${e} (${t.status})`);return t.json()}async fetchText(e){const t=await i(e);if(!t.ok)throw new Error(`Failed to fetch text: ${e} (${t.status})`);return t.text()}async fetchBinary(e){const t=await i(e);if(!t.ok)throw new Error(`Failed to fetch binary: ${e} (${t.status})`);return t.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 jt=N(null,"Assets");class Xt{build(e){const t=e.wasmModule;t?e.insertResource(jt,new Nt(t)):console.warn("AssetPlugin: No WASM module available")}}const Vt=new Xt;function Gt(e,t){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const s=n.createTexture(t.width,t.height,r,t.pixels.length,1);return e._free(r),s}function Yt(e,t){const n=t.substring(0,t.lastIndexOf("/"));n&&e.FS.mkdirTree(n)}function Kt(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}async function qt(e,t,n,r,s){const o=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]=Gt(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,o);let i={};s&&(i=await async function(e,t,n,r){const s={};for(const o of n.entities)for(const n of o.components){if("SpineAnimation"!==n.type||!n.data)continue;const o=n.data.skeletonPath,i=n.data.atlasPath;if(!o||!i)continue;const a=r.resolvePath(o),c=r.resolvePath(i);try{const n=r.readText(i),l=a.endsWith(".skel");Yt(t,a),l?t.FS.writeFile(a,r.readBinary(o)):t.FS.writeFile(a,r.readText(o));const u=t.spine_loadSkeleton(a,n,n.length,l);if(u<0)continue;s[o]=u;const h=Kt(n),d=c.substring(0,c.lastIndexOf("/"));for(let n=0;n<h.length;n++){const s=d+"/"+h[n];try{const o=r.loadPixelsRaw??r.loadPixels,i=await o(s),a=Gt(e,i),c=e.getResourceManager().getTextureGLId(a);t.spine_setAtlasPageTexture(u,n,c,i.width,i.height)}catch{}}}catch{}}return s}(t,s,n,r));const a=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 o=e.vertexSource+e.fragmentSource;let i=r[o];i||(i=Ue.createShader(e.vertexSource,e.fragmentSource),r[o]=i),n[s]=Ue.createFromAsset(e,i)}catch{n[s]=0}}return n}(n,r),c=Lt(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,z);s&&(s.texture=n[r.data.texture]||0,e.insert(t,z,s))}}}(e.world,n,o,c),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,z);n&&(n.material=s,e.insert(t,z,n))}else if("SpineAnimation"===r.type){const n=e.get(t,D);n&&(n.material=s,e.insert(t,D,n))}}}}(e.world,n,a,c),s){const r=function(e,t,n,r){const s={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.spine_createInstance(i);if(a<0)continue;const c=r.get(o.id);void 0!==c&&(s[c]=a),t.data.animation&&e.spine_playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.spine_setSkin(a,t.data.skin)}return s}(s,n,i,c);!function(e,t,n,r){if(0===Object.keys(r).length)return;let s=0;e.setSpineRenderer((e,o)=>{let i=o-s;s=o,(i<=0||i>.5)&&(i=1/60);for(const e in r){const s=r[e];n.spine_update(s,i);const o=n.spine_getMeshBatchCount(s);for(let e=0;e<o;e++){const r=n.spine_getMeshBatchVertexCount(s,e),o=n.spine_getMeshBatchIndexCount(s,e);if(!r||!o)continue;const i=8*r*4,a=2*o,c=n._malloc(i),l=n._malloc(a),u=n._malloc(4),h=n._malloc(4);n.spine_getMeshBatchData(s,e,c,l,u,h);const d=n.HEAPU32[u>>2],f=n.HEAPU32[h>>2],p=new Float32Array(n.HEAPF32.buffer,c,8*r),_=new Uint16Array(n.HEAPU8.buffer,l,o),m=t._malloc(i),g=t._malloc(a);t.HEAPF32.set(p,m>>2),new Uint16Array(t.HEAPU8.buffer,g,o).set(_),t.renderer_submitTriangles(m,r,g,o,d,f,0),t._free(m),t._free(g),n._free(c),n._free(l),n._free(u),n._free(h)}}})}(e,t,s,r)}}class Jt{constructor(e){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e}build(e){this.app_=e,e.hasResource(jt)||e.addPlugin(Vt),this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=this.app_.getResource(jt);await n.loadScene(this.app_.world,t),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([I]);for(const r of n){if(e.get(r,I).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([B]);for(const s of r){const r=e.get(s,B);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(),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,F,o);const i={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0};e.insert(s,I,i)}}}const Qt={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=gt.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:gt.getTargetTexture(n),width:e.width,height:e.height}},release(e){gt.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(gt.releaseRenderTarget(e._handle),Qt.create({width:t,height:n,depth:!0})),begin(e,t){gt.begin(t,e._handle)},end(){gt.end()},getDepthTexture:e=>gt.getTargetDepthTexture(e._handle)};let Zt=!1;function en(e){Zt=e}function tn(){return Zt}function nn(){return!Zt}var rn;e=rn=f,console.log(`[ESEngine] Platform: ${rn.name}`);export{Rt as App,Xt as AssetPlugin,Nt as AssetServer,jt as Assets,Ot as AsyncCache,Pe as BlendMode,I as Camera,B as Canvas,L as Children,Z as Commands,te as CommandsInstance,Je as DataType,Ye as Draw,ee as EntityCommands,vt as GLDebug,ot as Geometry,p as INVALID_ENTITY,_ as INVALID_TEXTURE,he as Input,de as InputPlugin,ue as InputState,F as LocalTransform,Ue as Material,$t as MaterialLoader,K as Mut,$ as Parent,ut as PostProcess,Jt as PreviewPlugin,J as Query,Q as QueryInstance,bt as RenderPipeline,dt as RenderStage,Qt as RenderTexture,gt as Renderer,j as Res,X as ResMut,ne as Schedule,Le as ShaderSources,D as SpineAnimation,z as Sprite,le as SystemRunner,ye as Text,_e as TextAlign,ge as TextOverflow,ve as TextPlugin,we as TextRenderer,me as TextVerticalAlign,Y as Time,xe as UIRect,k as Velocity,pe as World,U as WorldTransform,ae as addStartupSystem,ie as addSystem,ce as addSystemToSchedule,Vt as assetPlugin,Tt as clearDrawCallbacks,R as clearUserComponents,w as color,Mt as createWebApp,C as defineComponent,N as defineResource,se as defineSystem,T as defineTag,Et as flushPendingSystems,H as getComponentDefaults,t as getPlatform,r as getPlatformType,b as getUserComponent,je as initDrawAPI,wt as initGLDebugAPI,nt as initGeometryAPI,Ee as initMaterialAPI,at as initPostProcessAPI,_t as initRendererAPI,fe as inputPlugin,A as isBuiltinComponent,tn as isEditor,n as isPlatformInitialized,nn as isRuntime,Ce as isTextureRef,s as isWeChat,o as isWeb,Wt as loadComponent,qt as loadRuntimeScene,Lt as loadSceneData,Dt as loadSceneWithAssets,i as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,x as quat,Pt as registerDrawCallback,$e as registerMaterialCallback,en as setEditorMode,Xe as shutdownDrawAPI,xt as shutdownGLDebugAPI,rt as shutdownGeometryAPI,Ae as shutdownMaterialAPI,ct as shutdownPostProcessAPI,mt as shutdownRendererAPI,Se as textPlugin,Ct as unregisterDrawCallback,Ht 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 r(){return e?.name??null}function s(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}const f=new class{constructor(){this.name="web"}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),r={};return n.headers.forEach((e,t)=>{r[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:r,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const r=await WebAssembly.instantiate(n,t);return{instance:r.instance,module:r.module}}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){const n=t??document.querySelector("canvas")??document.body;document.addEventListener("keydown",t=>e.onKeyDown(t.code)),document.addEventListener("keyup",t=>e.onKeyUp(t.code)),n.addEventListener("mousemove",t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)}),n.addEventListener("mousedown",t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)}),n.addEventListener("mouseup",t=>{e.onPointerUp(t.button)}),n.addEventListener("touchstart",t=>{const r=t.touches[0];if(r){const t=n.getBoundingClientRect();e.onPointerDown(0,r.clientX-t.left,r.clientY-t.top)}}),n.addEventListener("touchmove",t=>{const r=t.touches[0];if(r){const t=n.getBoundingClientRect();e.onPointerMove(r.clientX-t.left,r.clientY-t.top)}}),n.addEventListener("touchend",()=>{e.onPointerUp(0)}),n.addEventListener("wheel",t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)})}},p=0,_=4294967295,m=(e=0,t=0)=>({x:e,y:t}),g=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),y=(e=0,t=0,n=0,r=1)=>({x:e,y:t,z:n,w:r}),w=(e=1,t=1,n=1,r=1)=>({x:e,y:t,z:n,w:r}),x=(e=1,t=0,n=0,r=0)=>({w:e,x:t,y:n,z:r});let v=0;function S(e,t){const n=++v;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function P(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function C(e,t){const n=P(),r=n.get(e);if(r)return r;const s=S(e,t);return n.set(e,s),R(e,t,!1),s}function T(e){const t=P(),n=t.get(e);if(n)return n;const r=S(e,{});return t.set(e,r),R(e,{},!0),r}function b(e){return P().get(e)}function M(){P().clear()}function R(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function E(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function A(e){return!0===e._builtin}const U=E("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),F=E("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=E("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}),I=E("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0}),B=E("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),k=E("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),$=E("Parent",{entity:0}),L=E("Children",{entities:[]}),D=E("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}),W={LocalTransform:U,WorldTransform:F,Sprite:z,Camera:I,Canvas:B,Velocity:k,Parent:$,Children:L,SpineAnimation:D};function H(e){const t=W[e];if(t)return{...t._default};const n=b(e);return n?{...n._default}:null}let O=0;function N(e,t){const n=++O;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function j(e){return{_type:"res",_resource:e}}function X(e){return{_type:"res_mut",_resource:e}}class V{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 G{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 V(this.get(e),t=>this.set(e,t))}}const Y=N({delta:0,elapsed:0,frameCount:0},"Time");function K(e){return{_type:"mut",_component:e}}function q(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function J(...e){return function(e,t=[],n=[]){const r=[];return e.forEach((e,t)=>{q(e)&&r.push(t)}),{_type:"query",_components:e,_mutIndices:r,_with:t,_without:n}}(e)}class Q{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:n,_without:r}=this.descriptor_,s=e.map(e=>this.getActualComponent(e)),o=[...s,...n],i=this.world_.getEntitiesWithComponents(o);let a=null,c=[];try{for(const e of i){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 o=s.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:s[e],data:o[e]});a=e,yield[e,...o]}}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 Z(){return{_type:"commands"}}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 n;return n=A(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 te{constructor(e,t){this.pending_=[],this.world_=e,this.resources_=t}spawn(){return new ee(this,null)}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,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.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 ne;!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"}(ne||(ne={}));let re=0;function se(e,t,n){const r=++re;return{_id:Symbol(`System_${r}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${r}`}}function oe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function ie(e){oe().push({schedule:ne.Update,system:e})}function ae(e){oe().push({schedule:ne.Startup,system:e})}function ce(e,t){oe().push({schedule:e,system:t})}class le{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 Q(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 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 he=N(new ue,"Input");class de{constructor(e){this.target_=e??null}build(e){const n=new ue;e.insertResource(he,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,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(ne.First,se([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const fe=new de;class pe{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return A(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return A(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return A(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){A(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 _e,me,ge;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(_e||(_e={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(me||(me={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(ge||(ge={}));const ye=C("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:_e.Left,verticalAlign:me.Top,wordWrap:!0,overflow:ge.Visible,lineHeight:1.2,dirty:!0});class we{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,o=s?t.size.x:0,i=s?t.size.y:0,a=e.wordWrap&&s;let c=this.wrapText(e.content,a?o: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(o):h+2*u,p=s?Math.ceil(i):d+2*u;if(s&&e.overflow===ge.Ellipsis&&d>i){const e=Math.floor(i/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,o)}}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===ge.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 me.Top:x=u;break;case me.Middle:x=(p-w)/2;break;case me.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let r;switch(e.align){case _e.Left:r=u;break;case _e.Center:r=f/2;break;case _e.Right:r=f-u;break;default:r=u}n.fillText(t,r,v),v+=l}s&&e.overflow===ge.Clip&&n.restore();const S=n.getImageData(0,0,f,p),P=new Uint8Array(S.data.buffer),C=this.flipVertically(P,f,p),T=this.module.getResourceManager(),b=this.module._malloc(C.length);this.module.HEAPU8.set(C,b);const M=T.createTexture(f,p,b,C.length,1);return this.module._free(b),{textureHandle:M,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const 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 _e.Left:return"left";case _e.Center:return"center";case _e.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}flipVertically(e,t,n){const r=4*t,s=new Uint8Array(e.length);for(let t=0;t<n;t++){const o=t*r,i=(n-1-t)*r;s.set(e.subarray(o,o+r),i)}return s}}const xe=C("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class ve{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new we(t),r=e.world;e.addSystemToSchedule(ne.PreUpdate,se([],()=>{const e=r.getEntitiesWithComponents([ye]);for(const t of e){const e=r.get(t,ye);if(!e.dirty)continue;r.has(t,z)||r.insert(t,z,{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 s=r.has(t,xe)?r.get(t,xe):null,o=n.renderForEntity(t,e,s),i=r.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},r.insert(t,z,i),e.dirty=!1}}))}}const Se=new ve;var Pe;function Ce(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"}(Pe||(Pe={}));let Te=null,be=null,Me=1;const Re=new Map;function Ee(e){Te=e,be=e.getResourceManager(),$e()}function Ae(){0!==Ie&&Te&&(Te._free(Ie),Ie=0),Re.clear(),Me=1,ze=!1,be=null,Te=null}function Ue(){if(!be)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return be}const Fe={createShader:(e,t)=>Ue().createShader(e,t),releaseShader(e){e>0&&Ue().releaseShader(e)},create(e){const t=Me++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Pe.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,r]of Object.entries(e.uniforms))n.uniforms.set(t,r);return Re.set(t,n),t},get:e=>Re.get(e),setUniform(e,t,n){const r=Re.get(e);r&&r.uniforms.set(t,n)},getUniform(e,t){const n=Re.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Re.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Re.get(e);return t?.blendMode??Pe.Normal},setDepthTest(e,t){const n=Re.get(e);n&&(n.depthTest=t)},getShader(e){const t=Re.get(e);return t?.shader??0},release(e){Re.delete(e)},isValid:e=>Re.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??Pe.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Re.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Me++,r={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Re.set(n,r),n},toAssetData(e,t){const n=Re.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=Re.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let ze=!1,Ie=0;const Be=4096;function ke(e){const t=(0===Ie&&Te&&(Ie=Te._malloc(Be)),Ie);if(0===t||!Te)return{ptr:0,count:0};let n=0,r=0;const s=Te.HEAPU8,o=Te.HEAPU32,i=Te.HEAPF32;for(const[a,c]of e){if(n+128>Be)break;const e=(new TextEncoder).encode(a),l=e.length,u=4*Math.ceil(l/4);o[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]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=d[e],n+=4;r++}return{ptr:t,count:r}}function $e(){if(!Te||ze)return;Te.materialDataProvider=(e,t,n,r,s)=>{const o=Re.get(e);if(!o)return Te.HEAPU32[t>>2]=0,Te.HEAPU32[n>>2]=0,Te.HEAPU32[r>>2]=0,void(Te.HEAPU32[s>>2]=0);Te.HEAPU32[t>>2]=o.shader,Te.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=ke(o.uniforms);Te.HEAPU32[r>>2]=i,Te.HEAPU32[s>>2]=a},ze=!0}const Le={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class De{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&&(Fe.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Fe.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),o=await this.shaderLoader_.load(s);return{handle:Fe.createFromAsset(r,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function We(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)Oe(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 He(e,t,n){const r=new Map,s=n?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();r.set(i.id,t);for(const r of i.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,o.set(t,r)}catch(t){console.warn(`Failed to load texture: ${r}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await 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,o=e.atlasPath;if(t&&o){const e=await s.loadSpine(t,o,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Oe(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=o.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}function Oe(e,t,n){const r=n.data;switch(n.type){case"LocalTransform":e.insert(t,U,r);break;case"Sprite":e.insert(t,z,r);break;case"Camera":e.insert(t,I,r);break;case"Canvas":e.insert(t,B,r);break;case"Text":e.insert(t,ye,r);break;case"SpineAnimation":e.insert(t,D,r);break;case"UIRect":e.insert(t,xe,r);break;default:{const s=b(n.type);s?e.insert(t,s,r):console.warn(`Unknown component type: ${n.type}`);break}}}function Ne(e,t){const n=e.getEntitiesWithComponents([I]);for(const r of n){const n=e.get(r,I);n&&(n.aspectRatio=t,e.insert(r,I,n))}}class je{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 Xe{constructor(e){this.textureCache_=new je,this.shaderCache_=new je,this.jsonCache_=new je,this.textCache_=new je,this.binaryCache_=new je,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.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 De(t)}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),o=await fetch(s);if(!o.ok)return{success:!1,error:`Failed to fetch atlas: ${s}`};const i=await o.text();if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const a=t.substring(0,t.lastIndexOf("/")),c=this.parseAtlasTextures(i);for(const e of c){const t=a?`${a}/${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 l=this.resolveUrl(e,n),u=await fetch(l);if(!u.ok)return{success:!1,error:`Failed to fetch skeleton: ${l}`};const h=e.endsWith(".skel")?new Uint8Array(await u.arrayBuffer()):await u.text();return this.writeToVirtualFS(e,h)?(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 He(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){return new Promise((t,n)=>{const r=new Image;r.crossOrigin="anonymous",r.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(r,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void t(e)}catch{}t(r)},r.onerror=()=>n(new Error(`Failed to load image: ${e}`)),r.src=e})}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 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,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_.save(),r&&(this.ctx_.translate(0,n),this.ctx_.scale(1,-1)),this.ctx_.drawImage(e,0,0),this.ctx_.restore();const s=this.ctx_.getImageData(0,0,t,n),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 c=i.createTexture(t,n,a,o.length,1);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){if(!await l(e))throw new Error(`Shader file not found: ${e}`);const t=await c(e);if(!t)throw new Error(`Failed to read shader file: ${e}`);const{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Fe.createShader(n,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}}async fetchJson(e){const t=await i(e);if(!t.ok)throw new Error(`Failed to fetch JSON: ${e} (${t.status})`);return t.json()}async fetchText(e){const t=await i(e);if(!t.ok)throw new Error(`Failed to fetch text: ${e} (${t.status})`);return t.text()}async fetchBinary(e){const t=await i(e);if(!t.ok)throw new Error(`Failed to fetch binary: ${e} (${t.status})`);return t.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 Ve=N(null,"Assets");class Ge{build(e){const t=e.wasmModule;t?e.insertResource(Ve,new Xe(t)):console.warn("AssetPlugin: No WASM module available")}}const Ye=new Ge;let Ke=null,qe=0,Je=0,Qe=0;const Ze=new Float32Array(256);function et(e){Ke=e,qe=Ke._malloc(64),Je=Ke._malloc(64),Qe=Ke._malloc(1024)}function tt(){Ke&&(qe&&(Ke._free(qe),qe=0),Je&&(Ke._free(Je),Je=0),Qe&&(Ke._free(Qe),Qe=0)),Ke=null}function nt(){if(!Ke)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Ke}const rt={x:1,y:1,z:1,w:1},st={begin(e){const t=nt();t.HEAPF32.set(e,qe/4),t.draw_begin(qe)},end(){nt().draw_end()},line(e,t,n,r=1){nt().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){nt().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){nt().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){nt().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){nt().draw_circleOutline(e.x,e.y,t,n.x,n.y,n.z,n.w,r,s)},texture(e,t,n,r=rt){nt().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=rt){nt().draw_textureRotated(e.x,e.y,t.x,t.y,n,r,s.x,s.y,s.z,s.w)},setLayer(e){nt().draw_setLayer(e)},setDepth(e){nt().draw_setDepth(e)},getDrawCallCount:()=>Ke?Ke.draw_getDrawCallCount():0,getPrimitiveCount:()=>Ke?Ke.draw_getPrimitiveCount():0,setBlendMode(e){nt().draw_setBlendMode(e)},setDepthTest(e){nt().draw_setDepthTest(e)},drawMesh(e,t,n){const r=nt();r.HEAPF32.set(n,Je/4),r.draw_mesh(e,t,Je)},drawMeshWithMaterial(e,t,n){const r=nt(),s=Fe.get(t);if(!s)return;if(st.setBlendMode(s.blendMode),st.setDepthTest(s.depthTest),0===s.uniforms.size)return void st.drawMesh(e,s.shader,n);r.HEAPF32.set(n,Je/4);let o=0,i=0;for(const[e,t]of s.uniforms){const n=it(e);if(!(n<0)){if(Ce(t))Ze[o++]=10,Ze[o++]=n,Ze[o++]=t.slot??i++,Ze[o++]=t.textureId;else if("number"==typeof t)Ze[o++]=1,Ze[o++]=n,Ze[o++]=t;else if(Array.isArray(t)){Ze[o++]=t.length,Ze[o++]=n;for(let e=0;e<t.length;e++)Ze[o++]=t[e]}else"w"in t?(Ze[o++]=4,Ze[o++]=n,Ze[o++]=t.x,Ze[o++]=t.y,Ze[o++]=t.z,Ze[o++]=t.w):"z"in t?(Ze[o++]=3,Ze[o++]=n,Ze[o++]=t.x,Ze[o++]=t.y,Ze[o++]=t.z):(Ze[o++]=2,Ze[o++]=n,Ze[o++]=t.x,Ze[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(r.HEAPF32.set(Ze.subarray(0,o),Qe/4),r.draw_meshWithUniforms(e,s.shader,Je,Qe,o)):r.draw_mesh(e,s.shader,Je)}},ot={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function it(e){return ot[e]??-1}var at;!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"}(at||(at={}));let ct=null,lt=0,ut=0,ht=0;function dt(e){ct=e,lt=ct._malloc(262144),ut=ct._malloc(65536),ht=ct._malloc(256)}function ft(){ct&&(lt&&ct._free(lt),ut&&ct._free(ut),ht&&ct._free(ht),lt=0,ut=0,ht=0),ct=null}function pt(){if(!ct)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ct}const _t={create(e){const t=pt(),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,lt/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,ht,s).set(o),t.geometry_init(n,lt,r,ht,s,e.dynamic??!1),e.indices){const r=e.indices.length;if(4*r>65536)throw new Error(`Index data too large: ${r} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,ut,r).set(e.indices),t.geometry_setIndices16(n,ut,r)}else{new Uint32Array(t.HEAPU8.buffer,ut,r).set(e.indices),t.geometry_setIndices32(n,ut,r)}}return n},updateVertices(e,t,n=0){const r=pt(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);r.HEAPF32.set(t,lt/4),r.geometry_updateVertices(e,lt,s,n)},release(e){e>0&&pt().geometry_release(e)},isValid:e=>!(!ct||e<=0)&&ct.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,r=t/2;return _t.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:at.Float2},{name:"a_texCoord",type:at.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,o=Math.cos(s)*e,i=Math.sin(s)*e,a=(Math.cos(s)+1)/2,c=(Math.sin(s)+1)/2;n.push(o,i,a,c)}for(let e=1;e<=t;e++)r.push(0,e,e+1);return _t.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:at.Float2},{name:"a_texCoord",type:at.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 o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),r=Math.max(r,o.x),s=Math.max(s,o.y);const o=[];for(const i of e){const e=(i.x-t)/(r-t),a=(i.y-n)/(s-n);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return _t.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:at.Float2},{name:"a_texCoord",type:at.Float2}],indices:new Uint16Array(i)})}};let mt=null;function gt(e){mt=e}function yt(){mt&&xt.isInitialized()&&xt.shutdown(),mt=null}function wt(){if(!mt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return mt}const xt={init:(e,t)=>wt().postprocess_init(e,t),shutdown(){wt().postprocess_shutdown()},resize(e,t){wt().postprocess_resize(e,t)},addPass:(e,t)=>wt().postprocess_addPass(e,t),removePass(e){wt().postprocess_removePass(e)},setEnabled(e,t){wt().postprocess_setPassEnabled(e,t)},isEnabled:e=>wt().postprocess_isPassEnabled(e),setUniform(e,t,n){wt().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){wt().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){wt().postprocess_begin()},end(){wt().postprocess_end()},getPassCount:()=>wt().postprocess_getPassCount(),isInitialized:()=>!!mt&&mt.postprocess_isInitialized(),setBypass(e){wt().postprocess_setBypass(e)},isBypassed:()=>!mt||mt.postprocess_isBypassed(),createBlur:()=>Fe.createShader(vt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>Fe.createShader(vt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Fe.createShader(vt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Fe.createShader(vt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},vt="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var St;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(St||(St={}));let Pt=null,Ct=0;function Tt(e){Pt=e,Ct=Pt._malloc(64)}function bt(){Pt&&Ct&&(Pt._free(Ct),Ct=0),Pt=null}const Mt={init(e,t){Pt?.renderer_init(e,t)},resize(e,t){Pt?.renderer_resize(e,t)},begin(e,t){Pt&&Ct&&(Pt.HEAPF32.set(e,Ct/4),Pt.renderer_begin(Ct,t??0))},flush(){Pt?.renderer_flush()},end(){Pt?.renderer_end()},submitSprites(e){Pt&&Pt.renderer_submitSprites(e._cpp)},submitSpine(e){Pt&&Pt.renderer_submitSpine?.(e._cpp)},setStage(e){Pt?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Pt?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Pt?.renderer_releaseTarget(e)},getTargetTexture:e=>Pt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Pt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,r){Pt?.renderer_setClearColor?.(e,t,n,r)},getStats:()=>Pt?{drawCalls:Pt.renderer_getDrawCalls(),triangles:Pt.renderer_getTriangles(),sprites:Pt.renderer_getSprites(),spine:Pt.renderer_getSpine?.()??0,meshes:Pt.renderer_getMeshes(),culled:Pt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let Rt=null;function Et(e){Rt=e}function At(){Rt=null}const Ut={enable(){Rt?.gl_enableErrorCheck(!0)},disable(){Rt?.gl_enableErrorCheck(!1)},check:e=>Rt?.gl_checkErrors(e)??0,diagnose(){Rt?.renderer_diagnose()}},Ft=new Map;function zt(e,t){Ft.set(e,t)}function It(e){Ft.delete(e)}function Bt(){Ft.clear()}class kt{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:n,width:r,height:s,elapsed:o}=e;Mt.resize(r,s),xt.isInitialized()&&xt.getPassCount()>0&&!xt.isBypassed()&&xt.resize(r,s),Mt.begin(n),Mt.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,o):Mt.submitSpine(t),Mt.flush();const i=Ft;if(i.size>0){st.begin(n);const e=[];for(const[t,n]of i.entries())try{n(o)}catch(n){console.error(`[CustomDraw] callback '${t}' error:`,n),e.push(t)}st.end();for(const t of e)It(t)}Mt.end()}}class $t{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(ne.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ne.FixedPreUpdate),this.runSchedule(ne.FixedUpdate),this.runSchedule(ne.FixedPostUpdate);this.runSchedule(ne.PreUpdate),this.runSchedule(ne.Update),this.runSchedule(ne.PostUpdate),this.runSchedule(ne.Last),requestAnimationFrame(this.mainLoop)},this.world_=new pe,this.resources_=new G;for(const e of Object.values(ne))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new $t}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(ne.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(ne.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 le(this.world_,this.resources_),this.resources_.insert(Y,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(ne.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,At(),bt(),yt(),ft(),Ae(),tt()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(Y),n={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(Y,n)}}function Lt(e,t){const n=$t.new(),r=new e.Registry;n.connectCpp(r,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),et(e),Ee(e),dt(e),gt(e),Tt(e),Et(e);const s=new kt;n.pipeline_=s;let o=d();const i=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}=i(),n=function(e,t,n){const r=e.entityCount()+1e3;for(let s=0;s<r;s++){if(!e.valid(s)||!e.hasCamera(s)||!e.hasLocalTransform(s))continue;const o=e.getCamera(s);if(!o.isActive)continue;const i=e.getLocalTransform(s),a=t/n;let c;if(1===o.projectionType){let t=o.orthoSize;const n=Ht(e,r);if(n){t=Ot(n.designResolution.y/2,n.designResolution.x/n.designResolution.y,a,n.scaleMode,n.matchWidthOrHeight)}const s=t*a;c=Nt(-s,s,-t,t,-o.farPlane,o.farPlane)}else c=jt(o.fov*Math.PI/180,a,o.nearPlane,o.farPlane);return Vt(c,Xt(i.position.x,i.position.y,i.position.z))}return Wt}(r,e,t),a=(d()-o)/1e3;s.render({registry:{_cpp:r},viewProjection:n,width:e,height:t,elapsed:a})}};return n.addSystemToSchedule(ne.Last,a),n.addPlugin(Ye),n.addPlugin(fe),n.addPlugin(Se),n}function Dt(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 Wt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ht(e,t){for(let n=0;n<t;n++){if(!e.valid(n)||!e.hasCanvas(n))continue;return e.getCanvas(n)}return null}function Ot(e,t,n,r,s){const o=e*t/n,i=e;switch(r){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=s;return Math.pow(o,1-e)*Math.pow(i,e)}}}function Nt(e,t,n,r,s,o){const i=new Float32Array(16),a=t-e,c=r-n,l=o-s;return i[0]=2/a,i[5]=2/c,i[10]=-2/l,i[12]=-(t+e)/a,i[13]=-(r+n)/c,i[14]=-(o+s)/l,i[15]=1,i}function jt(e,t,n,r){const s=new Float32Array(16),o=1/Math.tan(e/2),i=n-r;return s[0]=o/t,s[5]=o,s[10]=(r+n)/i,s[11]=-1,s[14]=2*r*n/i,s}function Xt(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 Vt(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}function Gt(e,t){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const s=n.createTexture(t.width,t.height,r,t.pixels.length,1);return e._free(r),s}function Yt(e,t){const n=t.substring(0,t.lastIndexOf("/"));n&&e.FS.mkdirTree(n)}function Kt(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}async function qt(e,t,n,r,s){const o=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]=Gt(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,o);let i={};s&&(i=await async function(e,t,n,r){const s={};for(const o of n.entities)for(const n of o.components){if("SpineAnimation"!==n.type||!n.data)continue;const o=n.data.skeletonPath,i=n.data.atlasPath;if(!o||!i)continue;const a=r.resolvePath(o),c=r.resolvePath(i);try{const n=r.readText(i),l=a.endsWith(".skel");Yt(t,a),l?t.FS.writeFile(a,r.readBinary(o)):t.FS.writeFile(a,r.readText(o));const u=t.spine_loadSkeleton(a,n,n.length,l);if(u<0)continue;s[o]=u;const h=Kt(n),d=c.substring(0,c.lastIndexOf("/"));for(let n=0;n<h.length;n++){const s=d+"/"+h[n];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=Gt(e,o),a=e.getResourceManager().getTextureGLId(i);t.spine_setAtlasPageTexture(u,n,a,o.width,o.height)}catch{}}}catch{}}return s}(t,s,n,r));const a=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 o=e.vertexSource+e.fragmentSource;let i=r[o];i||(i=Fe.createShader(e.vertexSource,e.fragmentSource),r[o]=i),n[s]=Fe.createFromAsset(e,i)}catch{n[s]=0}}return n}(n,r),c=We(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,z);s&&(s.texture=n[r.data.texture]||0,e.insert(t,z,s))}}}(e.world,n,o,c),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,z);n&&(n.material=s,e.insert(t,z,n))}else if("SpineAnimation"===r.type){const n=e.get(t,D);n&&(n.material=s,e.insert(t,D,n))}}}}(e.world,n,a,c),s){const r=function(e,t,n,r){const s={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.spine_createInstance(i);if(a<0)continue;const c=r.get(o.id);void 0!==c&&(s[c]=a),t.data.animation&&e.spine_playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.spine_setSkin(a,t.data.skin)}return s}(s,n,i,c);!function(e,t,n,r){let s=0;e.setSpineRenderer((e,o)=>{let i=o-s;s=o,(i<=0||i>.5)&&(i=1/60);for(const e in r){const s=r[e];n.spine_update(s,i);const o=n.spine_getMeshBatchCount(s);for(let e=0;e<o;e++){const r=n.spine_getMeshBatchVertexCount(s,e),o=n.spine_getMeshBatchIndexCount(s,e);if(!r||!o)continue;const i=8*r*4,a=2*o,c=n._malloc(i),l=n._malloc(a),u=n._malloc(4),h=n._malloc(4);n.spine_getMeshBatchData(s,e,c,l,u,h);const d=n.HEAPU32[u>>2],f=n.HEAPU32[h>>2],p=new Float32Array(n.HEAPF32.buffer,c,8*r),_=new Uint16Array(n.HEAPU8.buffer,l,o),m=t._malloc(i),g=t._malloc(a);t.HEAPF32.set(p,m>>2),new Uint16Array(t.HEAPU8.buffer,g,o).set(_),t.renderer_submitTriangles(m,r,g,o,d,f,0),t._free(m),t._free(g),n._free(c),n._free(l),n._free(u),n._free(h)}}})}(e,t,s,r)}}class Jt{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),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}}class Qt{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new Jt(this.baseUrl_);await n.prefetch(t);let r=null;const s=this.app_.__spineInitPromise;if(s){r=(await s).controller.module}await qt(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([I]);for(const r of n){if(e.get(r,I).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([B]);for(const s of r){const r=e.get(s,B);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(),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,U,o);const i={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0};e.insert(s,I,i)}}}const Zt={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Mt.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Mt.getTargetTexture(n),width:e.width,height:e.height}},release(e){Mt.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Mt.releaseRenderTarget(e._handle),Zt.create({width:t,height:n,depth:!0})),begin(e,t){Mt.begin(t,e._handle)},end(){Mt.end()},getDepthTexture:e=>Mt.getTargetDepthTexture(e._handle)};let en=!1;function tn(e){en=e}function nn(){return en}function rn(){return!en}var sn;e=sn=f,console.log(`[ESEngine] Platform: ${sn.name}`);export{$t as App,Ge as AssetPlugin,Xe as AssetServer,Ve as Assets,je as AsyncCache,Pe as BlendMode,I as Camera,B as Canvas,L as Children,Z as Commands,te as CommandsInstance,at as DataType,st as Draw,ee as EntityCommands,Ut as GLDebug,_t as Geometry,p as INVALID_ENTITY,_ as INVALID_TEXTURE,he as Input,de as InputPlugin,ue as InputState,U as LocalTransform,Fe as Material,De as MaterialLoader,K as Mut,$ as Parent,xt as PostProcess,Qt as PreviewPlugin,J as Query,Q as QueryInstance,kt as RenderPipeline,St as RenderStage,Zt as RenderTexture,Mt as Renderer,j as Res,X as ResMut,ne as Schedule,Le as ShaderSources,D as SpineAnimation,z as Sprite,le as SystemRunner,ye as Text,_e as TextAlign,ge as TextOverflow,ve as TextPlugin,we as TextRenderer,me as TextVerticalAlign,Y as Time,xe as UIRect,k as Velocity,Jt as WebAssetProvider,pe as World,F as WorldTransform,ae as addStartupSystem,ie as addSystem,ce as addSystemToSchedule,Ye as assetPlugin,Bt as clearDrawCallbacks,M as clearUserComponents,w as color,Lt as createWebApp,C as defineComponent,N as defineResource,se as defineSystem,T as defineTag,Dt as flushPendingSystems,H as getComponentDefaults,t as getPlatform,r as getPlatformType,b as getUserComponent,et as initDrawAPI,Et as initGLDebugAPI,dt as initGeometryAPI,Ee as initMaterialAPI,gt as initPostProcessAPI,Tt as initRendererAPI,fe as inputPlugin,A as isBuiltinComponent,nn as isEditor,n as isPlatformInitialized,rn as isRuntime,Ce as isTextureRef,s as isWeChat,o as isWeb,Oe as loadComponent,qt as loadRuntimeScene,We as loadSceneData,He as loadSceneWithAssets,i as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,x as quat,zt as registerDrawCallback,$e as registerMaterialCallback,tn as setEditorMode,tt as shutdownDrawAPI,At as shutdownGLDebugAPI,ft as shutdownGeometryAPI,Ae as shutdownMaterialAPI,yt as shutdownPostProcessAPI,bt as shutdownRendererAPI,Se as textPlugin,It as unregisterDrawCallback,Ne as updateCameraAspectRatio,m as vec2,g as vec3,y as vec4};//# sourceMappingURL=index.js.mapdiff --git a/desktop/public/sdk/esm/index.d.ts b/desktop/public/sdk/esm/index.d.tsindex b50e4ba13..13270506e 100644--- a/desktop/public/sdk/esm/index.d.ts+++ b/desktop/public/sdk/esm/index.d.ts@@ -48,6 +48,8 @@ interface ComponentDef<T> {}declare function defineComponent<T extends object>(name: string, defaults: T): ComponentDef<T>;declare function defineTag(name: string): ComponentDef<{}>;+declare function getUserComponent(name: string): ComponentDef<any> | undefined;+declare function clearUserComponents(): void;interface BuiltinComponentDef<T> {readonly _id: symbol;readonly _name: string;@@ -87,6 +89,7 @@ interface CameraData {aspectRatio: number;isActive: boolean;priority: number;+ showFrustum: boolean;}interface CanvasData {designResolution: Vec2;@@ -175,15 +178,6 @@ interface TimeData {frameCount: number;}declare const Time: ResourceDef<TimeData>;-interface InputState {- keysDown: Set<string>;- keysPressed: Set<string>;- keysReleased: Set<string>;- mouseX: number;- mouseY: number;- mouseButtons: Set<number>;-}-declare const Input: ResourceDef<InputState>;/*** @file wasm.ts@@ -237,6 +231,8 @@ interface CppRegistry {interface CppResourceManager {createTexture(width: number, height: number, pixels: number, pixelsLen: number, format: number): number;createShader(vertSrc: string, fragSrc: string): number;+ registerExternalTexture(glTextureId: number, width: number, height: number): number;+ getTextureGLId(handle: number): number;releaseTexture(handle: number): void;releaseShader(handle: number): void;setTextureMetadata(handle: number, left: number, right: number, top: number, bottom: number): void;@@ -274,8 +270,7 @@ interface ESEngineModule {HEAPU32: Uint32Array;HEAPF32: Float32Array;FS: EmscriptenFS;- addFunction(func: (...args: any[]) => any, signature: string): number;- setMaterialCallback(callbackPtr: number): void;+ materialDataProvider?: (materialId: number, outShaderIdPtr: number, outBlendModePtr: number, outUniformBufferPtr: number, outUniformCountPtr: number) => void;initRenderer(): void;initRendererWithCanvas(canvasSelector: string): boolean;initRendererWithContext(contextHandle: number): boolean;@@ -290,7 +285,7 @@ interface ESEngineModule {renderFrame(registry: CppRegistry, width: number, height: number): void;renderFrameWithMatrix(registry: CppRegistry, width: number, height: number, matrixPtr: number): void;getResourceManager(): CppResourceManager;- getSpineBounds(registry: CppRegistry, entity: number): SpineBounds;+ getSpineBounds?(registry: CppRegistry, entity: number): SpineBounds;draw_begin(matrixPtr: number): void;draw_end(): void;draw_line(fromX: number, fromY: number, toX: number, toY: number, r: number, g: number, b: number, a: number, thickness: number): void;@@ -333,20 +328,26 @@ interface ESEngineModule {renderer_init(width: number, height: number): void;renderer_resize(width: number, height: number): void;renderer_begin(matrixPtr: number, targetHandle: number): void;+ renderer_flush(): void;renderer_end(): void;renderer_submitSprites(registry: CppRegistry): void;- renderer_submitSpine(registry: CppRegistry): void;+ renderer_submitSpine?(registry: CppRegistry): void;+ renderer_submitTriangles(verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, transformPtr: number): void;renderer_setStage(stage: number): void;- renderer_createTarget(width: number, height: number): number;+ renderer_createTarget(width: number, height: number, flags: number): number;renderer_releaseTarget(handle: number): void;renderer_getTargetTexture(handle: number): number;+ renderer_getTargetDepthTexture(handle: number): number;renderer_getDrawCalls(): number;renderer_getTriangles(): number;renderer_getSprites(): number;- renderer_getSpine(): number;+ renderer_getSpine?(): number;renderer_getMeshes(): number;renderer_getCulled(): number;renderer_setClearColor(r: number, g: number, b: number, a: number): void;+ gl_enableErrorCheck(enabled: boolean): void;+ gl_checkErrors(context: string): number;+ renderer_diagnose(): void;_malloc(size: number): number;_free(ptr: number): void;}@@ -500,6 +501,9 @@ interface SystemDef {declare function defineSystem<P extends readonly SystemParam[]>(params: [...P], fn: (...args: InferParams<P>) => void, options?: {name?: string;}): SystemDef;+declare function addSystem(system: SystemDef): void;+declare function addStartupSystem(system: SystemDef): void;+declare function addSystemToSchedule(schedule: Schedule, system: SystemDef): void;declare class SystemRunner {private readonly world_;private readonly resources_;@@ -508,6 +512,29 @@ declare class SystemRunner {private resolveParam;}+/**+ * @file renderPipeline.ts+ * @brief Unified render pipeline for runtime and editor+ */++interface RenderParams {+ registry: {+ _cpp: CppRegistry;+ };+ viewProjection: Float32Array;+ width: number;+ height: number;+ elapsed: number;+}+type SpineRendererFn = (registry: {+ _cpp: CppRegistry;+}, elapsed: number) => void;+declare class RenderPipeline {+ private spineRenderer_;+ setSpineRenderer(fn: SpineRendererFn | null): void;+ render(params: RenderParams): void;+}+/*** @file app.ts* @brief Application builder and web platform integration@@ -523,7 +550,10 @@ declare class App {private runner_;private running_;private lastTime_;+ private fixedTimestep_;+ private fixedAccumulator_;private module_;+ private pipeline_;private constructor();static new(): App;addPlugin(plugin: Plugin): this;@@ -532,6 +562,7 @@ declare class App {addStartupSystem(system: SystemDef): this;connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this;get wasmModule(): ESEngineModule | null;+ setSpineRenderer(fn: SpineRendererFn | null): void;get world(): World;insertResource<T>(resource: ResourceDef<T>, value: T): this;getResource<T>(resource: ResourceDef<T>): T;@@ -550,6 +581,41 @@ interface WebAppOptions {glContextHandle?: number;}declare function createWebApp(module: ESEngineModule, options?: WebAppOptions): App;+declare function flushPendingSystems(app: App): void;++declare class InputState {+ keysDown: Set<string>;+ keysPressed: Set<string>;+ keysReleased: Set<string>;+ mouseX: number;+ mouseY: number;+ mouseButtons: Set<number>;+ mouseButtonsPressed: Set<number>;+ mouseButtonsReleased: Set<number>;+ scrollDeltaX: number;+ scrollDeltaY: number;+ isKeyDown(key: string): boolean;+ isKeyPressed(key: string): boolean;+ isKeyReleased(key: string): boolean;+ getMousePosition(): {+ x: number;+ y: number;+ };+ isMouseButtonDown(button: number): boolean;+ isMouseButtonPressed(button: number): boolean;+ isMouseButtonReleased(button: number): boolean;+ getScrollDelta(): {+ x: number;+ y: number;+ };+}+declare const Input: ResourceDef<InputState>;+declare class InputPlugin implements Plugin {+ private target_;+ constructor(target?: unknown);+ build(app: App): void;+}+declare const inputPlugin: InputPlugin;declare enum TextAlign {Left = 0,@@ -661,7 +727,13 @@ declare enum BlendMode {type ShaderHandle = number;type MaterialHandle = number;-type UniformValue = number | Vec2 | Vec3 | Vec4 | number[];+interface TextureRef {+ __textureRef: true;+ textureId: number;+ slot?: number;+}+type UniformValue = number | Vec2 | Vec3 | Vec4 | number[] | TextureRef;+declare function isTextureRef(v: UniformValue): v is TextureRef;interface MaterialOptions {shader: ShaderHandle;uniforms?: Record<string, UniformValue>;@@ -784,6 +856,7 @@ declare const Material: {* @returns Map of uniform names to values*/getUniforms(material: MaterialHandle): Map<string, UniformValue>;+ tex(textureId: number, slot?: number): TextureRef;};declare function registerMaterialCallback(): void;declare const ShaderSources: {@@ -956,6 +1029,9 @@ declare class AssetServer {private loadTextureInternal;private loadImage;private createTextureFromImage;+ private getWebGL2Context;+ private createTextureWebGL2;+ private createTextureFallback;private unpremultiplyAlpha;private loadShaderInternal;private parseEsShader;@@ -965,7 +1041,6 @@ declare class AssetServer {private writeToVirtualFS;private ensureVirtualDir;private resolveUrl;- private createCanvas;private nextPowerOf2;private parseAtlasTextures;}@@ -988,6 +1063,67 @@ declare class AssetPlugin implements Plugin {}declare const assetPlugin: AssetPlugin;+/**+ * @file SpineModuleLoader.ts+ * @brief Loads and initializes the standalone Spine WASM module+ */+interface SpineWasmModule {+ spine_loadSkeleton(skelPath: string, atlasText: string, atlasLen: number, isBinary: boolean): number;+ spine_unloadSkeleton(handle: number): void;+ spine_getAtlasPageCount(handle: number): number;+ spine_getAtlasPageTextureName(handle: number, pageIndex: number): string;+ spine_setAtlasPageTexture(handle: number, pageIndex: number, textureId: number, width: number, height: number): void;+ spine_createInstance(skeletonHandle: number): number;+ spine_destroyInstance(instanceId: number): void;+ spine_playAnimation(instanceId: number, name: string, loop: boolean, track: number): boolean;+ spine_addAnimation(instanceId: number, name: string, loop: boolean, delay: number, track: number): boolean;+ spine_setSkin(instanceId: number, name: string): void;+ spine_update(instanceId: number, dt: number): void;+ spine_getAnimations(instanceId: number): string;+ spine_getSkins(instanceId: number): string;+ spine_getBonePosition(instanceId: number, bone: string, outXPtr: number, outYPtr: number): boolean;+ spine_getBoneRotation(instanceId: number, bone: string): number;+ spine_getBounds(instanceId: number, outXPtr: number, outYPtr: number, outWPtr: number, outHPtr: number): void;+ spine_getMeshBatchCount(instanceId: number): number;+ spine_getMeshBatchVertexCount(instanceId: number, batchIndex: number): number;+ spine_getMeshBatchIndexCount(instanceId: number, batchIndex: number): number;+ spine_getMeshBatchData(instanceId: number, batchIndex: number, outVerticesPtr: number, outIndicesPtr: number, outTextureIdPtr: number, outBlendModePtr: number): void;+ HEAPF32: Float32Array;+ HEAPU8: Uint8Array;+ HEAPU32: Uint32Array;+ _malloc(size: number): number;+ _free(ptr: number): void;+ FS: {+ writeFile(path: string, data: string | Uint8Array): void;+ mkdirTree(path: string): void;+ analyzePath(path: string): {+ exists: boolean;+ };+ };+}++/**+ * @file runtimeLoader.ts+ * @brief Runtime scene loader for builder targets (WeChat, Playable, etc.)+ */++interface RuntimeAssetProvider {+ loadPixels(ref: string): Promise<{+ width: number;+ height: number;+ pixels: Uint8Array;+ }>;+ loadPixelsRaw?(ref: string): Promise<{+ width: number;+ height: number;+ pixels: Uint8Array;+ }>;+ readText(ref: string): string;+ readBinary(ref: string): Uint8Array;+ resolvePath(ref: string): string;+}+declare function loadRuntimeScene(app: App, module: ESEngineModule, sceneData: SceneData, provider: RuntimeAssetProvider, spineModule?: SpineWasmModule | null): Promise<void>;+/*** @file PreviewPlugin.ts* @brief Plugin for editor preview functionality@@ -995,9 +1131,10 @@ declare const assetPlugin: AssetPlugin;declare class PreviewPlugin implements Plugin {private sceneUrl_;+ private baseUrl_;private app_;private loadPromise_;- constructor(sceneUrl: string);+ constructor(sceneUrl: string, baseUrl?: string);build(app: App): void;/*** @brief Wait for scene loading to complete@@ -1007,6 +1144,28 @@ declare class PreviewPlugin implements Plugin {private ensureCamera;}+/**+ * @file WebAssetProvider.ts+ * @brief RuntimeAssetProvider for browser-based preview+ */++declare class WebAssetProvider implements RuntimeAssetProvider {+ private textCache_;+ private binaryCache_;+ private baseUrl_;+ constructor(baseUrl: string);+ prefetch(sceneData: SceneData): Promise<void>;+ readText(ref: string): string;+ readBinary(ref: string): Uint8Array;+ loadPixels(ref: string): Promise<{+ width: number;+ height: number;+ pixels: Uint8Array;+ }>;+ resolvePath(ref: string): string;+ private resolveUrl;+}+/*** @file types.ts* @brief Platform adapter interface definitions@@ -1031,6 +1190,14 @@ interface WasmInstantiateResult {instance: WebAssembly.Instance;module: WebAssembly.Module;}+interface InputEventCallbacks {+ onKeyDown(code: string): void;+ onKeyUp(code: string): void;+ onPointerMove(x: number, y: number): void;+ onPointerDown(button: number, x: number, y: number): void;+ onPointerUp(button: number): void;+ onWheel(deltaX: number, deltaY: number): void;+}interface PlatformAdapter {/*** Platform name identifier@@ -1061,6 +1228,20 @@ interface PlatformAdapter {* @param imports - Import object*/instantiateWasm(pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Imports): Promise<WasmInstantiateResult>;+ /**+ * Create a 2D canvas for offscreen rendering+ */+ createCanvas(width: number, height: number): HTMLCanvasElement | OffscreenCanvas;+ /**+ * High-resolution timestamp in milliseconds+ */+ now(): number;+ /**+ * Bind input events (keyboard, pointer, wheel)+ * @param callbacks - Event callbacks+ * @param target - Optional event target (canvas element)+ */+ bindInputEvents(callbacks: InputEventCallbacks, target?: unknown): void;}type PlatformType = 'web' | 'wechat';@@ -1091,206 +1272,6 @@ declare function platformReadTextFile(path: string): Promise<string>;declare function platformFileExists(path: string): Promise<boolean>;declare function platformInstantiateWasm(pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Imports): Promise<WasmInstantiateResult>;-/**- * @file spine.ts- * @brief Spine animation control API- */--/**- * Spine event types- */-type SpineEventType = 'start' | 'interrupt' | 'end' | 'complete' | 'dispose' | 'event';-/**- * Spine event callback- */-type SpineEventCallback = (event: SpineEvent) => void;-/**- * Spine event data- */-interface SpineEvent {- type: SpineEventType;- entity: Entity;- track: number;- animation: string | null;- eventName?: string;- intValue?: number;- floatValue?: number;- stringValue?: string;-}-/**- * Track entry info for animation queries- */-interface TrackEntryInfo {- animation: string;- track: number;- loop: boolean;- timeScale: number;- trackTime: number;- animationTime: number;- duration: number;- isComplete: boolean;-}-/**- * Controller for Spine skeletal animations- *- * @example- * ```typescript- * const spine = new SpineController(wasmModule);- *- * // Play animation- * spine.play(entity, 'run', true);- *- * // Queue next animation- * spine.addAnimation(entity, 'idle', true, 0.2);- *- * // Change skin- * spine.setSkin(entity, 'warrior');- *- * // Get bone position for effects- * const pos = spine.getBonePosition(entity, 'weapon');- * if (pos) {- * spawnEffect(pos.x, pos.y);- * }- *- * // Listen for events- * spine.on(entity, 'event', (e) => {- * if (e.eventName === 'footstep') {- * playSound('footstep');- * }- * });- * ```- */-declare class SpineController {- private module_;- private listeners_;- constructor(wasmModule: any);- /**- * Plays an animation, replacing any current animation on the track- * @param entity Target entity- * @param animation Animation name- * @param loop Whether to loop the animation- * @param track Animation track (default 0)- * @returns True if animation was set- */- play(entity: Entity, animation: string, loop?: boolean, track?: number): boolean;- /**- * Adds an animation to the queue- * @param entity Target entity- * @param animation Animation name- * @param loop Whether to loop- * @param delay Delay before starting (seconds)- * @param track Animation track (default 0)- * @returns True if animation was queued- */- addAnimation(entity: Entity, animation: string, loop?: boolean, delay?: number, track?: number): boolean;- /**- * Sets an empty animation to mix out the current animation- * @param entity Target entity- * @param mixDuration Duration of the mix out- * @param track Animation track (default 0)- */- setEmptyAnimation(entity: Entity, mixDuration?: number, track?: number): void;- /**- * Clears all animations on a track- * @param entity Target entity- * @param track Animation track (default 0)- */- clearTrack(entity: Entity, track?: number): void;- /**- * Clears all tracks- * @param entity Target entity- */- clearTracks(entity: Entity): void;- /**- * Sets the current skin- * @param entity Target entity- * @param skinName Skin name- * @returns True if skin was set- */- setSkin(entity: Entity, skinName: string): boolean;- /**- * Gets available skin names- * @param entity Target entity- * @returns Array of skin names- */- getSkins(entity: Entity): string[];- /**- * Gets available animation names- * @param entity Target entity- * @returns Array of animation names- */- getAnimations(entity: Entity): string[];- /**- * Gets the current animation on a track- * @param entity Target entity- * @param track Animation track (default 0)- * @returns Animation name or null- */- getCurrentAnimation(entity: Entity, track?: number): string | null;- /**- * Gets the duration of an animation- * @param entity Target entity- * @param animation Animation name- * @returns Duration in seconds, or 0 if not found- */- getAnimationDuration(entity: Entity, animation: string): number;- /**- * Gets detailed track entry info- * @param entity Target entity- * @param track Animation track (default 0)- * @returns Track entry info or null- */- getTrackEntry(entity: Entity, track?: number): TrackEntryInfo | null;- /**- * Gets world position of a bone- * @param entity Target entity- * @param boneName Bone name- * @returns Position or null if not found- */- getBonePosition(entity: Entity, boneName: string): Vec2 | null;- /**- * Gets world rotation of a bone in degrees- * @param entity Target entity- * @param boneName Bone name- * @returns Rotation in degrees or null- */- getBoneRotation(entity: Entity, boneName: string): number | null;- /**- * Sets the attachment for a slot- * @param entity Target entity- * @param slotName Slot name- * @param attachmentName Attachment name (null to clear)- */- setAttachment(entity: Entity, slotName: string, attachmentName: string | null): void;- /**- * Registers an event callback- * @param entity Target entity- * @param type Event type- * @param callback Callback function- */- on(entity: Entity, type: SpineEventType, callback: SpineEventCallback): void;- /**- * Unregisters an event callback- * @param entity Target entity- * @param type Event type- * @param callback Callback function- */- off(entity: Entity, type: SpineEventType, callback: SpineEventCallback): void;- /**- * Removes all event listeners for an entity- * @param entity Target entity- */- removeAllListeners(entity: Entity): void;- private setupEventBridge;- private dispatchEvent;-}-/**- * Creates a SpineController instance- * @param wasmModule The ESEngine WASM module- * @returns SpineController instance- */-declare function createSpineController(wasmModule: any): SpineController;-/*** @file geometry.ts* @brief Geometry API for custom mesh rendering@@ -1630,6 +1611,7 @@ declare const Renderer: {init(width: number, height: number): void;resize(width: number, height: number): void;begin(viewProjection: Float32Array, target?: RenderTargetHandle): void;+ flush(): void;end(): void;submitSprites(registry: {_cpp: CppRegistry;@@ -1638,30 +1620,34 @@ declare const Renderer: {_cpp: CppRegistry;}): void;setStage(stage: RenderStage): void;- createRenderTarget(width: number, height: number): RenderTargetHandle;+ createRenderTarget(width: number, height: number, flags?: number): RenderTargetHandle;releaseRenderTarget(handle: RenderTargetHandle): void;getTargetTexture(handle: RenderTargetHandle): number;+ getTargetDepthTexture(handle: RenderTargetHandle): number;setClearColor(r: number, g: number, b: number, a: number): void;getStats(): RenderStats;};-/**- * @file renderPipeline.ts- * @brief Unified render pipeline for runtime and editor- */--interface RenderParams {- registry: {- _cpp: CppRegistry;- };- viewProjection: Float32Array;+interface RenderTextureOptions {width: number;height: number;- elapsed: number;+ depth?: boolean;+ filter?: 'nearest' | 'linear';}-declare class RenderPipeline {- render(params: RenderParams): void;+interface RenderTextureHandle {+ _handle: RenderTargetHandle;+ textureId: number;+ width: number;+ height: number;}+declare const RenderTexture: {+ create(options: RenderTextureOptions): RenderTextureHandle;+ release(rt: RenderTextureHandle): void;+ resize(rt: RenderTextureHandle, width: number, height: number): RenderTextureHandle;+ begin(rt: RenderTextureHandle, viewProjection: Float32Array): void;+ end(): void;+ getDepthTexture(rt: RenderTextureHandle): number;+};/*** @file customDraw.ts@@ -1676,5 +1662,19 @@ declare function setEditorMode(active: boolean): void;declare function isEditor(): boolean;declare function isRuntime(): boolean;-export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BlendMode, Camera, Canvas, Children, Commands, CommandsInstance, DataType, Draw, EntityCommands, Geometry, INVALID_ENTITY, INVALID_TEXTURE, Input, LocalTransform, Material, MaterialLoader, Mut, Parent, PostProcess, PreviewPlugin, Query, QueryInstance, RenderPipeline, RenderStage, Renderer, Res, ResMut, ResMutInstance, Schedule, ShaderSources, SpineAnimation, SpineController, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIRect, Velocity, World, WorldTransform, assetPlugin, clearDrawCallbacks, color, createSpineController, createWebApp, defineComponent, defineResource, defineSystem, defineTag, getComponentDefaults, getPlatform, getPlatformType, initDrawAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, isBuiltinComponent, isEditor, isPlatformInitialized, isRuntime, isWeChat, isWeb, loadComponent, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, registerDrawCallback, registerMaterialCallback, setEditorMode, shutdownDrawAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textPlugin, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4 };-export type { AnyComponentDef, AssetBundle, AssetManifest, AssetsData, BuiltinComponentDef, CameraData, CanvasData, ChildrenData, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DrawAPI, DrawCallback, ESEngineModule, Entity, FileLoadOptions, GeometryHandle, GeometryOptions, InferParam, InferParams, InputState, LoadedMaterial, LocalTransformData, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, ParentData, PlatformAdapter, PlatformRequestOptions, PlatformResponse, PlatformType, Plugin, Quat, QueryDescriptor, QueryResult, RenderParams, RenderStats, RenderTargetHandle, ResDescriptor, ResMutDescriptor, ResourceDef, SceneComponentData, SceneData, SceneEntityData, SceneLoadOptions, ShaderHandle, ShaderLoader, SliceBorder, SpineAnimationData, SpineDescriptor, SpineEvent, SpineEventCallback, SpineEventType, SpineLoadResult, SpriteData, SystemDef, SystemParam, TextData, TextRenderResult, TextureHandle, TextureInfo, TimeData, TrackEntryInfo, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WorldTransformData };+/**+ * @file glDebug.ts+ * @brief GL error checking API for debugging rendering issues+ */++declare function initGLDebugAPI(wasmModule: ESEngineModule): void;+declare function shutdownGLDebugAPI(): void;+declare const GLDebug: {+ enable(): void;+ disable(): void;+ check(context: string): number;+ diagnose(): void;+};++export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BlendMode, Camera, Canvas, Children, Commands, CommandsInstance, DataType, Draw, EntityCommands, GLDebug, Geometry, INVALID_ENTITY, INVALID_TEXTURE, Input, InputPlugin, InputState, LocalTransform, Material, MaterialLoader, Mut, Parent, PostProcess, PreviewPlugin, Query, QueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, Schedule, ShaderSources, SpineAnimation, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIRect, Velocity, WebAssetProvider, World, WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, assetPlugin, clearDrawCallbacks, clearUserComponents, color, createWebApp, defineComponent, defineResource, defineSystem, defineTag, flushPendingSystems, getComponentDefaults, getPlatform, getPlatformType, getUserComponent, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, inputPlugin, isBuiltinComponent, isEditor, isPlatformInitialized, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadRuntimeScene, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, registerDrawCallback, registerMaterialCallback, setEditorMode, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textPlugin, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4 };+export type { AnyComponentDef, AssetBundle, AssetManifest, AssetsData, BuiltinComponentDef, CameraData, CanvasData, ChildrenData, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DrawAPI, DrawCallback, ESEngineModule, Entity, FileLoadOptions, GeometryHandle, GeometryOptions, InferParam, InferParams, LoadedMaterial, LocalTransformData, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, ParentData, PlatformAdapter, PlatformRequestOptions, PlatformResponse, PlatformType, Plugin, Quat, QueryDescriptor, QueryResult, RenderParams, RenderStats, RenderTargetHandle, RenderTextureHandle, RenderTextureOptions, ResDescriptor, ResMutDescriptor, ResourceDef, RuntimeAssetProvider, SceneComponentData, SceneData, SceneEntityData, SceneLoadOptions, ShaderHandle, ShaderLoader, SliceBorder, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteData, SystemDef, SystemParam, TextData, TextRenderResult, TextureHandle, TextureInfo, TextureRef, TimeData, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WorldTransformData };diff --git a/desktop/public/sdk/esm/index.js b/desktop/public/sdk/esm/index.jsindex 1b3ba834e..ffeb548d6 100644--- a/desktop/public/sdk/esm/index.js+++ b/desktop/public/sdk/esm/index.js@@ -1,3867 +1,2 @@-/**- * @file base.ts- * @brief Base platform adapter - no platform-specific code- */-// =============================================================================-// Platform Instance (set by entry point)-// =============================================================================-let currentPlatform = null;-/**- * Set the platform adapter (called by entry point)- */-function setPlatform(adapter) {- currentPlatform = adapter;- console.log(`[ESEngine] Platform: ${adapter.name}`);-}-/**- * Get the current platform adapter- * @throws Error if platform not initialized- */-function getPlatform() {- if (!currentPlatform) {- throw new Error('[ESEngine] Platform not initialized. ' +- 'Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');- }- return currentPlatform;-}-/**- * Check if platform is initialized- */-function isPlatformInitialized() {- return currentPlatform !== null;-}-/**- * Get platform type- */-function getPlatformType() {- return currentPlatform?.name ?? null;-}-/**- * Check if running on WeChat- */-function isWeChat() {- return currentPlatform?.name === 'wechat';-}-/**- * Check if running on Web- */-function isWeb() {- return currentPlatform?.name === 'web';-}-// =============================================================================-// Convenience Functions-// =============================================================================-async function platformFetch(url, options) {- return getPlatform().fetch(url, options);-}-async function platformReadFile(path) {- return getPlatform().readFile(path);-}-async function platformReadTextFile(path) {- return getPlatform().readTextFile(path);-}-async function platformFileExists(path) {- return getPlatform().fileExists(path);-}-async function platformInstantiateWasm(pathOrBuffer, imports) {- return getPlatform().instantiateWasm(pathOrBuffer, imports);-}--/**- * @file web.ts- * @brief Web platform adapter implementation- */-// =============================================================================-// Web Platform Adapter-// =============================================================================-class WebPlatformAdapter {- constructor() {- this.name = 'web';- }- async fetch(url, options) {- const response = await globalThis.fetch(url, {- method: options?.method ?? 'GET',- headers: options?.headers,- body: options?.body,- });- const headers = {};- response.headers.forEach((value, key) => {- headers[key] = value;- });- return {- ok: response.ok,- status: response.status,- statusText: response.statusText,- headers,- json: () => response.json(),- text: () => response.text(),- arrayBuffer: () => response.arrayBuffer(),- };- }- async readFile(path) {- const response = await this.fetch(path);- if (!response.ok) {- throw new Error(`Failed to read file: ${path} (${response.status})`);- }- return response.arrayBuffer();- }- async readTextFile(path) {- const response = await this.fetch(path);- if (!response.ok) {- throw new Error(`Failed to read file: ${path} (${response.status})`);- }- return response.text();- }- async fileExists(path) {- try {- const response = await globalThis.fetch(path, { method: 'HEAD' });- return response.ok;- }- catch {- return false;- }- }- async instantiateWasm(pathOrBuffer, imports) {- let buffer;- if (typeof pathOrBuffer === 'string') {- buffer = await this.readFile(pathOrBuffer);- }- else {- buffer = pathOrBuffer;- }- const result = await WebAssembly.instantiate(buffer, imports);- return {- instance: result.instance,- module: result.module,- };- }-}-// =============================================================================-// Export Singleton-// =============================================================================-const webAdapter = new WebPlatformAdapter();--/**- * @file types.ts- * @brief Core type definitions for ESEngine SDK- */-const INVALID_ENTITY = 0;-const INVALID_TEXTURE = 0xFFFFFFFF;-// =============================================================================-// Factory Functions-// =============================================================================-const vec2 = (x = 0, y = 0) => ({ x, y });-const vec3 = (x = 0, y = 0, z = 0) => ({ x, y, z });-const vec4 = (x = 0, y = 0, z = 0, w = 1) => ({ x, y, z, w });-const color = (r = 1, g = 1, b = 1, a = 1) => ({ x: r, y: g, z: b, w: a });-const quat = (w = 1, x = 0, y = 0, z = 0) => ({ w, x, y, z });--/**- * @file component.ts- * @brief Component definition and builtin components- */-let componentCounter = 0;-function createComponentDef(name, defaults) {- const id = ++componentCounter;- return {- _id: Symbol(`Component_${id}_${name}`),- _name: name,- _default: defaults,- _builtin: false,- create(data) {- return { ...defaults, ...data };- }- };-}-function defineComponent(name, defaults) {- const def = createComponentDef(name, defaults);- registerToEditor(name, defaults, false);- return def;-}-function defineTag(name) {- const def = createComponentDef(name, {});- registerToEditor(name, {}, true);- return def;-}-function registerToEditor(name, defaults, isTag) {- if (typeof window !== 'undefined' && window.__esengine_registerComponent) {- window.__esengine_registerComponent(name, defaults, isTag);- }-}-function defineBuiltin(name, defaults) {- return {- _id: Symbol(`Builtin_${name}`),- _name: name,- _cppName: name,- _builtin: true,- _default: defaults- };-}-function isBuiltinComponent(comp) {- return comp._builtin === true;-}-// =============================================================================-// Builtin Component Instances-// =============================================================================-const LocalTransform = defineBuiltin('LocalTransform', {- position: { x: 0, y: 0, z: 0 },- rotation: { w: 1, x: 0, y: 0, z: 0 },- scale: { x: 1, y: 1, z: 1 }-});-const WorldTransform = defineBuiltin('WorldTransform', {- position: { x: 0, y: 0, z: 0 },- rotation: { w: 1, x: 0, y: 0, z: 0 },- scale: { x: 1, y: 1, z: 1 }-});-const Sprite = defineBuiltin('Sprite', {- texture: INVALID_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: false,- flipY: false,- material: 0-});-const Camera = defineBuiltin('Camera', {- projectionType: 0,- fov: 60,- orthoSize: 5,- nearPlane: 0.1,- farPlane: 1000,- aspectRatio: 1.77,- isActive: true,- priority: 0-});-const Canvas = defineBuiltin('Canvas', {- designResolution: { x: 1920, y: 1080 },- pixelsPerUnit: 100,- scaleMode: 0,- matchWidthOrHeight: 0.5,- backgroundColor: { x: 0, y: 0, z: 0, w: 1 }-});-const Velocity = defineBuiltin('Velocity', {- linear: { x: 0, y: 0, z: 0 },- angular: { x: 0, y: 0, z: 0 }-});-const Parent = defineBuiltin('Parent', {- entity: 0-});-const Children = defineBuiltin('Children', {- entities: []-});-const SpineAnimation = defineBuiltin('SpineAnimation', {- skeletonPath: '',- atlasPath: '',- skin: '',- animation: '',- timeScale: 1.0,- loop: true,- playing: true,- flipX: false,- flipY: false,- color: { x: 1, y: 1, z: 1, w: 1 },- layer: 0,- skeletonScale: 1.0,- material: 0-});-// =============================================================================-// Component Defaults Registry-// =============================================================================-const builtinComponents = {- LocalTransform,- WorldTransform,- Sprite,- Camera,- Canvas,- Velocity,- Parent,- Children,- SpineAnimation,-};-function getComponentDefaults(typeName) {- const component = builtinComponents[typeName];- if (component) {- return { ...component._default };- }- return null;-}--/**- * @file resource.ts- * @brief Resource system for global singleton data- */-let resourceCounter = 0;-function defineResource(defaultValue, name) {- const id = ++resourceCounter;- return {- _id: Symbol(`Resource_${id}_${name ?? ''}`),- _name: name ?? `Resource_${id}`,- _default: defaultValue- };-}-function Res(resource) {- return { _type: 'res', _resource: resource };-}-function ResMut(resource) {- return { _type: 'res_mut', _resource: resource };-}-// =============================================================================-// Resource Instances (Runtime)-// =============================================================================-class ResMutInstance {- constructor(value, setter) {- this.value_ = value;- this.setter_ = setter;- }- get() {- return this.value_;- }- set(value) {- this.value_ = value;- this.setter_(value);- }- modify(fn) {- fn(this.value_);- this.setter_(this.value_);- }-}-// =============================================================================-// Resource Storage-// =============================================================================-class ResourceStorage {- constructor() {- this.resources_ = new Map();- }- insert(resource, value) {- this.resources_.set(resource._id, value);- }- get(resource) {- if (!this.resources_.has(resource._id)) {- this.resources_.set(resource._id, resource._default);- }- return this.resources_.get(resource._id);- }- set(resource, value) {- this.resources_.set(resource._id, value);- }- has(resource) {- return this.resources_.has(resource._id);- }- remove(resource) {- this.resources_.delete(resource._id);- }- getResMut(resource) {- return new ResMutInstance(this.get(resource), (v) => this.set(resource, v));- }-}-const Time = defineResource({- delta: 0,- elapsed: 0,- frameCount: 0-}, 'Time');-const Input = defineResource({- keysDown: new Set(),- keysPressed: new Set(),- keysReleased: new Set(),- mouseX: 0,- mouseY: 0,- mouseButtons: new Set()-}, 'Input');--/**- * @file query.ts- * @brief Component query system with mutable component support- */-function Mut(component) {- return { _type: 'mut', _component: component };-}-function isMutWrapper(value) {- return typeof value === 'object' && value !== null && value._type === 'mut';-}-function createQueryDescriptor(components, withFilters = [], withoutFilters = []) {- const mutIndices = [];- components.forEach((comp, i) => {- if (isMutWrapper(comp)) {- mutIndices.push(i);- }- });- return {- _type: 'query',- _components: components,- _mutIndices: mutIndices,- _with: withFilters,- _without: withoutFilters- };-}-// =============================================================================-// Query Factory-// =============================================================================-function Query(...components) {- return createQueryDescriptor(components);-}-class QueryInstance {- constructor(world, descriptor) {- this.pendingMutations_ = [];- this.world_ = world;- this.descriptor_ = descriptor;- }- getActualComponent(arg) {- return isMutWrapper(arg) ? arg._component : arg;- }- commitPending() {- for (const mutation of this.pendingMutations_) {- this.world_.insert(mutation.entity, mutation.component, mutation.data);- }- this.pendingMutations_ = [];- }- *[Symbol.iterator]() {- const { _components, _mutIndices, _with, _without } = this.descriptor_;- const actualComponents = _components.map(c => this.getActualComponent(c));- const allRequired = [...actualComponents, ..._with];- const entities = this.world_.getEntitiesWithComponents(allRequired);- let prevEntity = null;- let prevMutData = [];- try {- for (const entity of entities) {- // Commit previous entity's mutations before moving to next- if (prevEntity !== null) {- for (const mut of prevMutData) {- this.world_.insert(prevEntity, mut.component, mut.data);- }- }- prevMutData = [];- let excluded = false;- for (const comp of _without) {- if (this.world_.has(entity, comp)) {- excluded = true;- break;- }- }- if (excluded)- continue;- const components = actualComponents.map(comp => this.world_.get(entity, comp));- // Track mutable components for write-back- for (const idx of _mutIndices) {- prevMutData.push({- component: actualComponents[idx],- data: components[idx]- });- }- prevEntity = entity;- yield [entity, ...components];- }- }- finally {- // Commit last entity's mutations- if (prevEntity !== null) {- for (const mut of prevMutData) {- this.world_.insert(prevEntity, mut.component, mut.data);- }- }- }- }- forEach(callback) {- for (const [entity, ...components] of this) {- callback(entity, ...components);- }- }- single() {- for (const result of this) {- return result;- }- return null;- }- isEmpty() {- return this.single() === null;- }- count() {- let n = 0;- for (const _ of this) {- n++;- }- return n;- }- toArray() {- return [...this];- }-}--/**- * @file commands.ts- * @brief Deferred entity/component operations- */-function Commands() {- return { _type: 'commands' };-}-// =============================================================================-// Entity Commands (Builder for spawning)-// =============================================================================-class EntityCommands {- constructor(commands, entity) {- this.components_ = [];- this.commands_ = commands;- if (entity === null) {- this.entityRef_ = { entity: 0 };- this.isNew_ = true;- }- else {- this.entityRef_ = { entity };- this.isNew_ = false;- }- }- insert(component, data) {- let instance;- if (isBuiltinComponent(component)) {- instance = { ...component._default, ...data };- }- else {- instance = component.create(data);- }- if (this.isNew_) {- this.components_.push({ component, data: instance });- }- else {- this.commands_.queueInsert(this.entityRef_.entity, component, instance);- }- return this;- }- remove(component) {- if (!this.isNew_) {- this.commands_.queueRemove(this.entityRef_.entity, component);- }- return this;- }- id() {- if (this.isNew_ && this.entityRef_.entity === 0) {- this.finalize();- }- return this.entityRef_.entity;- }- finalize() {- if (this.isNew_) {- this.commands_.spawnImmediate(this.components_, this.entityRef_);- this.isNew_ = false;- }- }-}-// =============================================================================-// Commands Instance (Runtime)-// =============================================================================-class CommandsInstance {- constructor(world, resources) {- this.pending_ = [];- this.world_ = world;- this.resources_ = resources;- }- spawn() {- return new EntityCommands(this, null);- }- entity(entity) {- return new EntityCommands(this, entity);- }- despawn(entity) {- this.pending_.push({ type: 'despawn', entity });- return this;- }- insertResource(resource, value) {- this.pending_.push({- type: 'insert_resource',- resource: resource,- value- });- return this;- }- queueInsert(entity, component, data) {- this.pending_.push({ type: 'insert', entity, component, data });- }- queueRemove(entity, component) {- this.pending_.push({ type: 'remove', entity, component });- }- spawnImmediate(components, entityRef) {- const entity = this.world_.spawn();- entityRef.entity = entity;- for (const entry of components) {- this.world_.insert(entity, entry.component, entry.data);- }- }- flush() {- for (const cmd of this.pending_) {- this.executeCommand(cmd);- }- this.pending_ = [];- }- executeCommand(cmd) {- switch (cmd.type) {- case 'spawn': {- const entity = this.world_.spawn();- cmd.entityRef.entity = entity;- for (const entry of cmd.components) {- this.world_.insert(entity, entry.component, entry.data);- }- break;- }- case 'despawn':- this.world_.despawn(cmd.entity);- break;- case 'insert':- this.world_.insert(cmd.entity, cmd.component, cmd.data);- break;- case 'remove':- this.world_.remove(cmd.entity, cmd.component);- break;- case 'insert_resource':- this.resources_.insert(cmd.resource, cmd.value);- break;- }- }-}--/**- * @file system.ts- * @brief System definition and scheduling- */-// =============================================================================-// Schedule Phases-// =============================================================================-var Schedule;-(function (Schedule) {- Schedule[Schedule["Startup"] = 0] = "Startup";- Schedule[Schedule["First"] = 1] = "First";- Schedule[Schedule["PreUpdate"] = 2] = "PreUpdate";- Schedule[Schedule["Update"] = 3] = "Update";- Schedule[Schedule["PostUpdate"] = 4] = "PostUpdate";- Schedule[Schedule["Last"] = 5] = "Last";- Schedule[Schedule["FixedPreUpdate"] = 10] = "FixedPreUpdate";- Schedule[Schedule["FixedUpdate"] = 11] = "FixedUpdate";- Schedule[Schedule["FixedPostUpdate"] = 12] = "FixedPostUpdate";-})(Schedule || (Schedule = {}));-let systemCounter = 0;-function defineSystem(params, fn, options) {- const id = ++systemCounter;- return {- _id: Symbol(`System_${id}_${options?.name ?? ''}`),- _params: params,- _fn: fn,- _name: options?.name ?? `System_${id}`- };-}-// =============================================================================-// System Runner-// =============================================================================-class SystemRunner {- constructor(world, resources) {- this.world_ = world;- this.resources_ = resources;- }- run(system) {- const args = system._params.map(param => this.resolveParam(param));- system._fn(...args);- for (const arg of args) {- if (arg instanceof CommandsInstance) {- arg.flush();- }- }- }- resolveParam(param) {- switch (param._type) {- case 'query':- return new QueryInstance(this.world_, param);- case 'res':- return this.resources_.get(param._resource);- case 'res_mut':- return this.resources_.getResMut(param._resource);- case 'commands':- return new CommandsInstance(this.world_, this.resources_);- default:- throw new Error('Unknown system parameter type');- }- }-}--/**- * @file world.ts- * @brief ECS World with C++ Registry integration- */-// =============================================================================-// World-// =============================================================================-class World {- constructor() {- this.cppRegistry_ = null;- this.entities_ = new Set();- this.tsStorage_ = new Map();- }- connectCpp(cppRegistry) {- this.cppRegistry_ = cppRegistry;- }- get hasCpp() {- return this.cppRegistry_ !== null;- }- // =========================================================================- // Entity Management- // =========================================================================- spawn() {- let entity;- if (this.cppRegistry_) {- entity = this.cppRegistry_.create();- }- else {- entity = (this.entities_.size + 1);- }- this.entities_.add(entity);- return entity;- }- despawn(entity) {- if (this.cppRegistry_) {- this.cppRegistry_.destroy(entity);- }- this.entities_.delete(entity);- for (const storage of this.tsStorage_.values()) {- storage.delete(entity);- }- }- valid(entity) {- if (this.cppRegistry_) {- return this.cppRegistry_.valid(entity);- }- return this.entities_.has(entity);- }- entityCount() {- return this.entities_.size;- }- getAllEntities() {- return Array.from(this.entities_);- }- setParent(child, parent) {- if (this.cppRegistry_) {- this.cppRegistry_.setParent(child, parent);- }- }- removeParent(entity) {- if (this.cppRegistry_) {- this.cppRegistry_.removeParent(entity);- }- }- // =========================================================================- // Component Management- // =========================================================================- insert(entity, component, data) {- if (isBuiltinComponent(component)) {- return this.insertBuiltin(entity, component, data);- }- return this.insertScript(entity, component, data);- }- get(entity, component) {- if (isBuiltinComponent(component)) {- return this.getBuiltin(entity, component);- }- return this.getScript(entity, component);- }- has(entity, component) {- if (isBuiltinComponent(component)) {- return this.hasBuiltin(entity, component);- }- return this.hasScript(entity, component);- }- remove(entity, component) {- if (isBuiltinComponent(component)) {- this.removeBuiltin(entity, component);- }- else {- this.removeScript(entity, component);- }- }- // =========================================================================- // Builtin Component Operations (C++ Registry)- // =========================================================================- insertBuiltin(entity, component, data) {- const merged = { ...component._default, ...data };- if (this.cppRegistry_) {- const adder = `add${component._cppName}`;- const fn = this.cppRegistry_[adder];- fn.call(this.cppRegistry_, entity, merged);- }- return merged;- }- getBuiltin(entity, component) {- if (!this.cppRegistry_) {- throw new Error('C++ Registry not connected');- }- const getter = `get${component._cppName}`;- const fn = this.cppRegistry_[getter];- return fn.call(this.cppRegistry_, entity);- }- hasBuiltin(entity, component) {- if (!this.cppRegistry_) {- return false;- }- const checker = `has${component._cppName}`;- const fn = this.cppRegistry_[checker];- return fn.call(this.cppRegistry_, entity);- }- removeBuiltin(entity, component) {- if (!this.cppRegistry_) {- return;- }- const remover = `remove${component._cppName}`;- const fn = this.cppRegistry_[remover];- fn.call(this.cppRegistry_, entity);- }- // =========================================================================- // Script Component Operations (TypeScript storage)- // =========================================================================- insertScript(entity, component, data) {- const value = component.create(data);- this.getStorage(component).set(entity, value);- return value;- }- getScript(entity, component) {- const storage = this.tsStorage_.get(component._id);- if (!storage) {- throw new Error(`Component not found: ${component._name}`);- }- return storage.get(entity);- }- hasScript(entity, component) {- const storage = this.tsStorage_.get(component._id);- return storage?.has(entity) ?? false;- }- removeScript(entity, component) {- const storage = this.tsStorage_.get(component._id);- storage?.delete(entity);- }- getStorage(component) {- let storage = this.tsStorage_.get(component._id);- if (!storage) {- storage = new Map();- this.tsStorage_.set(component._id, storage);- }- return storage;- }- // =========================================================================- // Query Support- // =========================================================================- getEntitiesWithComponents(components) {- if (components.length === 0) {- return this.getAllEntities();- }- const entities = [];- for (const entity of this.entities_) {- let hasAll = true;- for (const comp of components) {- if (!this.has(entity, comp)) {- hasAll = false;- break;- }- }- if (hasAll) {- entities.push(entity);- }- }- return entities;- }-}--/**- * @file text.ts- * @brief Text component definition for UI text rendering- */-// =============================================================================-// Text Alignment Enums-// =============================================================================-var TextAlign;-(function (TextAlign) {- TextAlign[TextAlign["Left"] = 0] = "Left";- TextAlign[TextAlign["Center"] = 1] = "Center";- TextAlign[TextAlign["Right"] = 2] = "Right";-})(TextAlign || (TextAlign = {}));-var TextVerticalAlign;-(function (TextVerticalAlign) {- TextVerticalAlign[TextVerticalAlign["Top"] = 0] = "Top";- TextVerticalAlign[TextVerticalAlign["Middle"] = 1] = "Middle";- TextVerticalAlign[TextVerticalAlign["Bottom"] = 2] = "Bottom";-})(TextVerticalAlign || (TextVerticalAlign = {}));-var TextOverflow;-(function (TextOverflow) {- TextOverflow[TextOverflow["Visible"] = 0] = "Visible";- TextOverflow[TextOverflow["Clip"] = 1] = "Clip";- TextOverflow[TextOverflow["Ellipsis"] = 2] = "Ellipsis";-})(TextOverflow || (TextOverflow = {}));-// =============================================================================-// Text Component Definition-// =============================================================================-const Text = defineComponent('Text', {- content: '',- fontFamily: 'Arial',- fontSize: 24,- color: { x: 1, y: 1, z: 1, w: 1 },- align: TextAlign.Left,- verticalAlign: TextVerticalAlign.Top,- wordWrap: true,- overflow: TextOverflow.Visible,- lineHeight: 1.2,- dirty: true,-});--/**- * @file TextRenderer.ts- * @brief Renders text to GPU textures using Canvas 2D API- */-// =============================================================================-// Text Renderer-// =============================================================================-class TextRenderer {- constructor(module) {- this.cache = new Map();- this.module = module;- if (typeof OffscreenCanvas !== 'undefined') {- this.canvas = new OffscreenCanvas(512, 512);- this.ctx = this.canvas.getContext('2d', { willReadFrequently: true });- }- else {- this.canvas = document.createElement('canvas');- this.canvas.width = 512;- this.canvas.height = 512;- this.ctx = this.canvas.getContext('2d', { willReadFrequently: true });- }- }- /**- * Renders text to a texture and returns the handle- */- renderText(text, uiRect) {- const ctx = this.ctx;- const canvas = this.canvas;- ctx.font = `${text.fontSize}px ${text.fontFamily}`;- const hasContainer = uiRect && uiRect.size.x > 0 && uiRect.size.y > 0;- const containerWidth = hasContainer ? uiRect.size.x : 0;- const containerHeight = hasContainer ? uiRect.size.y : 0;- const shouldWrap = text.wordWrap && hasContainer;- let lines = this.wrapText(text.content, shouldWrap ? containerWidth : 0);- const lineHeightPx = Math.ceil(text.fontSize * text.lineHeight);- const padding = Math.ceil(text.fontSize * 0.2);- const measuredWidth = Math.ceil(this.measureWidth(lines));- const measuredHeight = Math.ceil(lines.length * lineHeightPx);- const width = hasContainer ? Math.ceil(containerWidth) : measuredWidth + padding * 2;- const height = hasContainer ? Math.ceil(containerHeight) : measuredHeight + padding * 2;- // Handle overflow ellipsis- if (hasContainer && text.overflow === TextOverflow.Ellipsis && measuredHeight > containerHeight) {- const maxLines = Math.floor(containerHeight / lineHeightPx);- if (maxLines > 0 && lines.length > maxLines) {- lines = lines.slice(0, maxLines);- const lastLine = lines[maxLines - 1];- lines[maxLines - 1] = this.truncateWithEllipsis(lastLine, containerWidth);- }- }- if (canvas.width < width || canvas.height < height) {- const newWidth = Math.max(canvas.width, this.nextPowerOf2(width));- const newHeight = Math.max(canvas.height, this.nextPowerOf2(height));- canvas.width = newWidth;- 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;- ctx.clearRect(0, 0, canvas.width, canvas.height);- ctx.font = `${text.fontSize}px ${text.fontFamily}`;- ctx.textAlign = this.mapAlign(text.align);- ctx.textBaseline = 'top';- ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${a})`;- // Handle overflow clip- if (hasContainer && text.overflow === TextOverflow.Clip) {- ctx.save();- ctx.beginPath();- ctx.rect(0, 0, width, height);- ctx.clip();- }- const textBlockHeight = lines.length * lineHeightPx;- let startY;- if (hasContainer) {- switch (text.verticalAlign) {- case TextVerticalAlign.Top:- startY = padding;- break;- case TextVerticalAlign.Middle:- startY = (height - textBlockHeight) / 2;- break;- case TextVerticalAlign.Bottom:- startY = height - textBlockHeight - padding;- break;- default: startY = padding;- }- }- else {- startY = padding;- }- let y = startY;- for (const line of lines) {- let x;- switch (text.align) {- case TextAlign.Left:- x = padding;- break;- case TextAlign.Center:- x = width / 2;- break;- case TextAlign.Right:- x = width - padding;- break;- default:- x = padding;- }- ctx.fillText(line, x, y);- y += lineHeightPx;- }- if (hasContainer && text.overflow === TextOverflow.Clip) {- ctx.restore();- }- const imageData = ctx.getImageData(0, 0, width, height);- const pixels = new Uint8Array(imageData.data.buffer);- const flipped = this.flipVertically(pixels, width, height);- const rm = this.module.getResourceManager();- const ptr = this.module._malloc(flipped.length);- this.module.HEAPU8.set(flipped, ptr);- const textureHandle = rm.createTexture(width, height, ptr, flipped.length, 1);- this.module._free(ptr);- return { textureHandle, width, height };- }- truncateWithEllipsis(text, maxWidth) {- const ellipsis = '...';- if (this.ctx.measureText(text).width <= maxWidth) {- return text;- }- let truncated = text;- while (truncated.length > 0 && this.ctx.measureText(truncated + ellipsis).width > maxWidth) {- truncated = truncated.slice(0, -1);- }- return truncated + ellipsis;- }- /**- * Renders text for an entity and caches the result- */- renderForEntity(entity, text, uiRect) {- const existing = this.cache.get(entity);- if (existing) {- const rm = this.module.getResourceManager();- rm.releaseTexture(existing.textureHandle);- }- const result = this.renderText(text, uiRect);- this.cache.set(entity, result);- return result;- }- /**- * Gets cached render result for entity- */- getCached(entity) {- return this.cache.get(entity);- }- /**- * Releases texture for entity- */- release(entity) {- const cached = this.cache.get(entity);- if (cached) {- const rm = this.module.getResourceManager();- rm.releaseTexture(cached.textureHandle);- this.cache.delete(entity);- }- }- /**- * Releases all cached textures- */- releaseAll() {- const rm = this.module.getResourceManager();- for (const result of this.cache.values()) {- rm.releaseTexture(result.textureHandle);- }- this.cache.clear();- }- // =========================================================================- // Private Methods- // =========================================================================- wrapText(text, maxWidth) {- if (!text)- return [''];- if (maxWidth <= 0)- return text.split('\n');- const paragraphs = text.split('\n');- const lines = [];- for (const paragraph of paragraphs) {- if (!paragraph) {- lines.push('');- continue;- }- let currentLine = '';- for (const char of paragraph) {- const testLine = currentLine + char;- const metrics = this.ctx.measureText(testLine);- if (metrics.width > maxWidth && currentLine) {- lines.push(currentLine);- currentLine = char;- }- else {- currentLine = testLine;- }- }- if (currentLine) {- lines.push(currentLine);- }- }- return lines.length > 0 ? lines : [''];- }- measureWidth(lines) {- let maxWidth = 0;- for (const line of lines) {- const metrics = this.ctx.measureText(line);- const width = metrics.actualBoundingBoxLeft !== undefined- ? metrics.actualBoundingBoxLeft + metrics.actualBoundingBoxRight- : metrics.width;- maxWidth = Math.max(maxWidth, width);- }- return maxWidth;- }- mapAlign(align) {- switch (align) {- case TextAlign.Left:- return 'left';- case TextAlign.Center:- return 'center';- case TextAlign.Right:- return 'right';- }- }- nextPowerOf2(n) {- let p = 1;- while (p < n)- p *= 2;- return p;- }- flipVertically(pixels, width, height) {- const rowSize = width * 4;- const flipped = new Uint8Array(pixels.length);- for (let y = 0; y < height; y++) {- const srcOffset = y * rowSize;- const dstOffset = (height - 1 - y) * rowSize;- flipped.set(pixels.subarray(srcOffset, srcOffset + rowSize), dstOffset);- }- return flipped;- }-}--/**- * @file UIRect.ts- * @brief UIRect component for UI layout with anchor and pivot- */-// =============================================================================-// UIRect Component Definition-// =============================================================================-const UIRect = defineComponent('UIRect', {- size: { x: 100, y: 100 },- anchor: { x: 0.5, y: 0.5 },- pivot: { x: 0.5, y: 0.5 },-});--/**- * @file TextPlugin.ts- * @brief Plugin that automatically syncs Text components to Sprite textures- */-// =============================================================================-// Text Plugin-// =============================================================================-class TextPlugin {- build(app) {- const module = app.wasmModule;- if (!module) {- console.warn('TextPlugin: No WASM module available');- return;- }- const renderer = new TextRenderer(module);- const world = app.world;- app.addSystemToSchedule(Schedule.PreUpdate, defineSystem([], () => {- const entities = world.getEntitiesWithComponents([Text]);- for (const entity of entities) {- const text = world.get(entity, Text);- if (!text.dirty)- continue;- if (!world.has(entity, Sprite)) {- world.insert(entity, Sprite, {- texture: INVALID_TEXTURE,- size: { x: 0, y: 0 },- color: { x: 1, y: 1, z: 1, w: 1 },- anchor: { x: 0.5, y: 0.5 },- flip: { x: false, y: false }- });- }- const uiRect = world.has(entity, UIRect)- ? world.get(entity, UIRect)- : null;- const result = renderer.renderForEntity(entity, text, uiRect);- const sprite = world.get(entity, Sprite);- sprite.texture = result.textureHandle;- sprite.size = { x: result.width, y: result.height };- sprite.uvOffset = { x: 0, y: 0 };- sprite.uvScale = { x: 1, y: 1 };- world.insert(entity, Sprite, sprite);- text.dirty = false;- }- }));- }-}-const textPlugin = new TextPlugin();--/**- * @file blend.ts- * @brief Blend mode definitions for rendering- */-var BlendMode;-(function (BlendMode) {- BlendMode[BlendMode["Normal"] = 0] = "Normal";- BlendMode[BlendMode["Additive"] = 1] = "Additive";- BlendMode[BlendMode["Multiply"] = 2] = "Multiply";- BlendMode[BlendMode["Screen"] = 3] = "Screen";- BlendMode[BlendMode["PremultipliedAlpha"] = 4] = "PremultipliedAlpha";-})(BlendMode || (BlendMode = {}));--/**- * @file material.ts- * @brief Material and Shader API for custom rendering- * @details Provides shader creation and material management for custom visual effects.- */-// =============================================================================-// Internal State-// =============================================================================-let module$5 = null;-let resourceManager = null;-let nextMaterialId = 1;-const materials = new Map();-// =============================================================================-// Initialization-// =============================================================================-function initMaterialAPI(wasmModule) {- module$5 = wasmModule;- resourceManager = wasmModule.getResourceManager();- registerMaterialCallback();-}-function shutdownMaterialAPI() {- if (uniformBuffer$1 !== 0 && module$5) {- module$5._free(uniformBuffer$1);- uniformBuffer$1 = 0;- }- materials.clear();- nextMaterialId = 1;- materialCallbackRegistered = false;- resourceManager = null;- module$5 = null;-}-// =============================================================================-// Shader API-// =============================================================================-function getResourceManager() {- if (!resourceManager) {- throw new Error('Material API not initialized. Call initMaterialAPI() first.');- }- return resourceManager;-}-const Material = {- /**- * Creates a shader from vertex and fragment source code.- * @param vertexSrc GLSL vertex shader source- * @param fragmentSrc GLSL fragment shader source- * @returns Shader handle, or 0 on failure- */- createShader(vertexSrc, fragmentSrc) {- return getResourceManager().createShader(vertexSrc, fragmentSrc);- },- /**- * Releases a shader.- * @param shader Shader handle to release- */- releaseShader(shader) {- if (shader > 0) {- getResourceManager().releaseShader(shader);- }- },- /**- * Creates a material with a shader and optional settings.- * @param options Material creation options- * @returns Material handle- */- create(options) {- const handle = nextMaterialId++;- const data = {- shader: options.shader,- uniforms: new Map(),- blendMode: options.blendMode ?? BlendMode.Normal,- depthTest: options.depthTest ?? false,- };- if (options.uniforms) {- for (const [key, value] of Object.entries(options.uniforms)) {- data.uniforms.set(key, value);- }- }- materials.set(handle, data);- return handle;- },- /**- * Gets material data by handle.- * @param material Material handle- * @returns Material data or undefined- */- get(material) {- return materials.get(material);- },- /**- * Sets a uniform value on a material.- * @param material Material handle- * @param name Uniform name- * @param value Uniform value- */- setUniform(material, name, value) {- const data = materials.get(material);- if (data) {- data.uniforms.set(name, value);- }- },- /**- * Gets a uniform value from a material.- * @param material Material handle- * @param name Uniform name- * @returns Uniform value or undefined- */- getUniform(material, name) {- const data = materials.get(material);- return data?.uniforms.get(name);- },- /**- * Sets the blend mode for a material.- * @param material Material handle- * @param mode Blend mode- */- setBlendMode(material, mode) {- const data = materials.get(material);- if (data) {- data.blendMode = mode;- }- },- /**- * Gets the blend mode of a material.- * @param material Material handle- * @returns Blend mode- */- getBlendMode(material) {- const data = materials.get(material);- return data?.blendMode ?? BlendMode.Normal;- },- /**- * Sets depth test enabled for a material.- * @param material Material handle- * @param enabled Whether depth test is enabled- */- setDepthTest(material, enabled) {- const data = materials.get(material);- if (data) {- data.depthTest = enabled;- }- },- /**- * Gets the shader handle for a material.- * @param material Material handle- * @returns Shader handle- */- getShader(material) {- const data = materials.get(material);- return data?.shader ?? 0;- },- /**- * Releases a material (does not release the shader).- * @param material Material handle- */- release(material) {- materials.delete(material);- },- /**- * Checks if a material exists.- * @param material Material handle- * @returns True if material exists- */- isValid(material) {- return materials.has(material);- },- /**- * Creates a material from asset data.- * @param data Material asset data (properties object)- * @param shaderHandle Pre-loaded shader handle- * @returns Material handle- */- createFromAsset(data, shaderHandle) {- const uniforms = {};- for (const [key, value] of Object.entries(data.properties)) {- if (typeof value === 'number') {- uniforms[key] = value;- }- else if (typeof value === 'object' && value !== null) {- const obj = value;- 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 };- }- else if ('y' in obj) {- uniforms[key] = { x: obj.x ?? 0, y: obj.y ?? 0 };- }- }- }- return this.create({- shader: shaderHandle,- uniforms,- blendMode: data.blendMode ?? BlendMode.Normal,- depthTest: data.depthTest ?? false,- });- },- /**- * Creates a material instance that shares the shader with source.- * @param source Source material handle- * @returns New material handle with copied settings- */- createInstance(source) {- const sourceData = materials.get(source);- if (!sourceData) {- throw new Error(`Invalid source material: ${source}`);- }- const handle = nextMaterialId++;- const data = {- shader: sourceData.shader,- uniforms: new Map(sourceData.uniforms),- blendMode: sourceData.blendMode,- depthTest: sourceData.depthTest,- };- materials.set(handle, data);- return handle;- },- /**- * Exports material to serializable asset data.- * @param material Material handle- * @param shaderPath Shader file path for asset reference- * @returns Material asset data- */- toAssetData(material, shaderPath) {- const data = materials.get(material);- if (!data)- return null;- const properties = {};- for (const [key, value] of data.uniforms) {- properties[key] = value;- }- return {- version: '1.0',- type: 'material',- shader: shaderPath,- blendMode: data.blendMode,- depthTest: data.depthTest,- properties,- };- },- /**- * Gets all uniforms from a material.- * @param material Material handle- * @returns Map of uniform names to values- */- getUniforms(material) {- const data = materials.get(material);- return data ? new Map(data.uniforms) : new Map();- },-};-// =============================================================================-// Material Callback Registration-// =============================================================================-let materialCallbackRegistered = false;-let uniformBuffer$1 = 0;-const UNIFORM_BUFFER_SIZE = 4096;-function ensureUniformBuffer() {- if (uniformBuffer$1 === 0 && module$5) {- uniformBuffer$1 = module$5._malloc(UNIFORM_BUFFER_SIZE);- }- return uniformBuffer$1;-}-function serializeUniforms(uniforms) {- const bufferPtr = ensureUniformBuffer();- if (bufferPtr === 0 || !module$5)- return { ptr: 0, count: 0 };- let offset = 0;- let count = 0;- const heap8 = module$5.HEAPU8;- const heap32 = module$5.HEAPU32;- const heapF32 = module$5.HEAPF32;- for (const [name, value] of uniforms) {- if (offset + 128 > UNIFORM_BUFFER_SIZE)- break;- const nameBytes = new TextEncoder().encode(name);- const nameLen = nameBytes.length;- const namePadded = Math.ceil(nameLen / 4) * 4;- heap32[(bufferPtr + offset) >> 2] = nameLen;- offset += 4;- heap8.set(nameBytes, bufferPtr + offset);- offset += namePadded;- let type = 0;- let values = [0, 0, 0, 0];- if (typeof value === 'number') {- type = 0;- values[0] = value;- }- else if (Array.isArray(value)) {- type = Math.min(value.length - 1, 3);- for (let i = 0; i < Math.min(value.length, 4); i++) {- values[i] = value[i];- }- }- else if ('w' in value) {- type = 3;- values = [value.x, value.y, value.z, value.w];- }- else if ('z' in value) {- type = 2;- values = [value.x, value.y, value.z, 0];- }- else if ('y' in value) {- type = 1;- values = [value.x, value.y, 0, 0];- }- heap32[(bufferPtr + offset) >> 2] = type;- offset += 4;- for (let i = 0; i < 4; i++) {- heapF32[(bufferPtr + offset) >> 2] = values[i];- offset += 4;- }- count++;- }- return { ptr: bufferPtr, count };-}-function registerMaterialCallback() {- if (!module$5 || materialCallbackRegistered)- return;- if (!module$5.addFunction || !module$5.setMaterialCallback) {- console.warn('[Material] Callback registration not available (requires -sALLOW_TABLE_GROWTH)');- return;- }- const callback = (materialId, outShaderIdPtr, outBlendModePtr, outUniformBufferPtr, outUniformCountPtr) => {- const data = materials.get(materialId);- if (!data) {- module$5.HEAPU32[outShaderIdPtr >> 2] = 0;- module$5.HEAPU32[outBlendModePtr >> 2] = 0;- module$5.HEAPU32[outUniformBufferPtr >> 2] = 0;- module$5.HEAPU32[outUniformCountPtr >> 2] = 0;- return;- }- module$5.HEAPU32[outShaderIdPtr >> 2] = data.shader;- module$5.HEAPU32[outBlendModePtr >> 2] = data.blendMode;- const { ptr, count } = serializeUniforms(data.uniforms);- module$5.HEAPU32[outUniformBufferPtr >> 2] = ptr;- module$5.HEAPU32[outUniformCountPtr >> 2] = count;- };- const callbackPtr = module$5.addFunction(callback, 'viiiii');- module$5.setMaterialCallback(callbackPtr);- materialCallbackRegistered = true;-}-// =============================================================================-// Built-in Shader Sources-// =============================================================================-const ShaderSources = {- SPRITE_VERTEX: `#version 300 es-precision highp float;--layout(location = 0) in vec3 a_position;-layout(location = 1) in vec4 a_color;-layout(location = 2) in vec2 a_texCoord;--uniform mat4 u_projection;-uniform mat4 u_model;--out vec4 v_color;-out vec2 v_texCoord;--void main() {- v_color = a_color;- v_texCoord = a_texCoord;- gl_Position = u_projection * u_model * vec4(a_position, 1.0);-}-`,- SPRITE_FRAGMENT: `#version 300 es-precision highp float;--in vec4 v_color;-in vec2 v_texCoord;--uniform sampler2D u_texture;--out vec4 fragColor;--void main() {- fragColor = texture(u_texture, v_texCoord) * v_color;-}-`,- COLOR_VERTEX: `#version 300 es-precision highp float;--layout(location = 0) in vec3 a_position;-layout(location = 1) in vec4 a_color;--uniform mat4 u_projection;-uniform mat4 u_model;--out vec4 v_color;--void main() {- v_color = a_color;- gl_Position = u_projection * u_model * vec4(a_position, 1.0);-}-`,- COLOR_FRAGMENT: `#version 300 es-precision highp float;--in vec4 v_color;--out vec4 fragColor;--void main() {- fragColor = v_color;-}-`,-};--/**- * @file draw.ts- * @brief Immediate mode 2D drawing API- * @details Provides simple drawing primitives (lines, rectangles, circles)- * with automatic batching. All draw commands are cleared each frame.- */-// =============================================================================-// Internal State-// =============================================================================-let module$4 = null;-let viewProjectionPtr$1 = 0;-let transformPtr = 0;-let uniformsPtr = 0;-const UNIFORMS_BUFFER_SIZE = 256;-const uniformBuffer = new Float32Array(UNIFORMS_BUFFER_SIZE);-// =============================================================================-// Initialization-// =============================================================================-function initDrawAPI(wasmModule) {- module$4 = wasmModule;- viewProjectionPtr$1 = module$4._malloc(16 * 4);- transformPtr = module$4._malloc(16 * 4);- uniformsPtr = module$4._malloc(UNIFORMS_BUFFER_SIZE * 4);-}-function shutdownDrawAPI() {- if (module$4) {- if (viewProjectionPtr$1) {- module$4._free(viewProjectionPtr$1);- viewProjectionPtr$1 = 0;- }- if (transformPtr) {- module$4._free(transformPtr);- transformPtr = 0;- }- if (uniformsPtr) {- module$4._free(uniformsPtr);- uniformsPtr = 0;- }- }- module$4 = null;-}-// =============================================================================-// Draw Implementation-// =============================================================================-function getModule$2() {- if (!module$4) {- throw new Error('Draw API not initialized. Call initDrawAPI() first.');- }- return module$4;-}-const WHITE = { x: 1, y: 1, z: 1, w: 1 };-const Draw = {- begin(viewProjection) {- const m = getModule$2();- m.HEAPF32.set(viewProjection, viewProjectionPtr$1 / 4);- m.draw_begin(viewProjectionPtr$1);- },- end() {- getModule$2().draw_end();- },- line(from, to, color, thickness = 1) {- getModule$2().draw_line(from.x, from.y, to.x, to.y, color.x, color.y, color.z, color.w, thickness);- },- rect(position, size, color, filled = true) {- getModule$2().draw_rect(position.x, position.y, size.x, size.y, color.x, color.y, color.z, color.w, filled);- },- rectOutline(position, size, color, thickness = 1) {- getModule$2().draw_rectOutline(position.x, position.y, size.x, size.y, color.x, color.y, color.z, color.w, thickness);- },- circle(center, radius, color, filled = true, segments = 32) {- getModule$2().draw_circle(center.x, center.y, radius, color.x, color.y, color.z, color.w, filled, segments);- },- circleOutline(center, radius, color, thickness = 1, segments = 32) {- getModule$2().draw_circleOutline(center.x, center.y, radius, color.x, color.y, color.z, color.w, thickness, segments);- },- texture(position, size, textureHandle, tint = WHITE) {- getModule$2().draw_texture(position.x, position.y, size.x, size.y, textureHandle, tint.x, tint.y, tint.z, tint.w);- },- textureRotated(position, size, rotation, textureHandle, tint = WHITE) {- getModule$2().draw_textureRotated(position.x, position.y, size.x, size.y, rotation, textureHandle, tint.x, tint.y, tint.z, tint.w);- },- setLayer(layer) {- getModule$2().draw_setLayer(layer);- },- setDepth(depth) {- getModule$2().draw_setDepth(depth);- },- getDrawCallCount() {- if (!module$4)- return 0;- return module$4.draw_getDrawCallCount();- },- getPrimitiveCount() {- if (!module$4)- return 0;- return module$4.draw_getPrimitiveCount();- },- setBlendMode(mode) {- getModule$2().draw_setBlendMode(mode);- },- setDepthTest(enabled) {- getModule$2().draw_setDepthTest(enabled);- },- drawMesh(geometry, shader, transform) {- const m = getModule$2();- m.HEAPF32.set(transform, transformPtr / 4);- m.draw_mesh(geometry, shader, transformPtr);- },- drawMeshWithMaterial(geometry, material, transform) {- const m = getModule$2();- const matData = Material.get(material);- if (!matData)- return;- Draw.setBlendMode(matData.blendMode);- Draw.setDepthTest(matData.depthTest);- if (matData.uniforms.size === 0) {- Draw.drawMesh(geometry, matData.shader, transform);- return;- }- m.HEAPF32.set(transform, transformPtr / 4);- let idx = 0;- for (const [name, value] of matData.uniforms) {- const nameId = getUniformNameId(name);- if (nameId < 0)- continue;- if (typeof value === 'number') {- uniformBuffer[idx++] = 1;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value;- }- else if (Array.isArray(value)) {- uniformBuffer[idx++] = value.length;- uniformBuffer[idx++] = nameId;- for (let i = 0; i < value.length; i++) {- uniformBuffer[idx++] = value[i];- }- }- else if ('w' in value) {- uniformBuffer[idx++] = 4;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value.x;- uniformBuffer[idx++] = value.y;- uniformBuffer[idx++] = value.z;- uniformBuffer[idx++] = value.w;- }- else if ('z' in value) {- uniformBuffer[idx++] = 3;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value.x;- uniformBuffer[idx++] = value.y;- uniformBuffer[idx++] = value.z;- }- else {- uniformBuffer[idx++] = 2;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value.x;- uniformBuffer[idx++] = value.y;- }- if (idx > UNIFORMS_BUFFER_SIZE - 6) {- console.warn('Uniform buffer overflow, some uniforms will be ignored');- break;- }- }- if (idx === 0) {- m.draw_mesh(geometry, matData.shader, transformPtr);- return;- }- m.HEAPF32.set(uniformBuffer.subarray(0, idx), uniformsPtr / 4);- m.draw_meshWithUniforms(geometry, matData.shader, transformPtr, uniformsPtr, idx);- },-};-const UNIFORM_NAME_MAP = {- '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 getUniformNameId(name) {- return UNIFORM_NAME_MAP[name] ?? -1;-}--/**- * @file geometry.ts- * @brief Geometry API for custom mesh rendering- * @details Provides geometry creation and management for custom shapes,- * particles, trails, and other procedural meshes.- */-var DataType;-(function (DataType) {- DataType[DataType["Float"] = 1] = "Float";- DataType[DataType["Float2"] = 2] = "Float2";- DataType[DataType["Float3"] = 3] = "Float3";- DataType[DataType["Float4"] = 4] = "Float4";- DataType[DataType["Int"] = 5] = "Int";- DataType[DataType["Int2"] = 6] = "Int2";- DataType[DataType["Int3"] = 7] = "Int3";- DataType[DataType["Int4"] = 8] = "Int4";-})(DataType || (DataType = {}));-// =============================================================================-// Internal State-// =============================================================================-let module$3 = null;-let vertexPtr = 0;-let indexPtr = 0;-let layoutPtr = 0;-const VERTEX_BUFFER_SIZE = 64 * 1024;-const INDEX_BUFFER_SIZE = 16 * 1024;-const LAYOUT_BUFFER_SIZE = 64;-// =============================================================================-// Initialization-// =============================================================================-function initGeometryAPI(wasmModule) {- module$3 = wasmModule;- vertexPtr = module$3._malloc(VERTEX_BUFFER_SIZE * 4);- indexPtr = module$3._malloc(INDEX_BUFFER_SIZE * 4);- layoutPtr = module$3._malloc(LAYOUT_BUFFER_SIZE * 4);-}-function shutdownGeometryAPI() {- if (module$3) {- if (vertexPtr)- module$3._free(vertexPtr);- if (indexPtr)- module$3._free(indexPtr);- if (layoutPtr)- module$3._free(layoutPtr);- vertexPtr = 0;- indexPtr = 0;- layoutPtr = 0;- }- module$3 = null;-}-// =============================================================================-// Geometry API-// =============================================================================-function getModule$1() {- if (!module$3) {- throw new Error('Geometry API not initialized. Call initGeometryAPI() first.');- }- return module$3;-}-const Geometry = {- /**- * Creates a new geometry with vertices and optional indices.- * @param options Geometry creation options- * @returns Geometry handle- */- create(options) {- const m = getModule$1();- const handle = m.geometry_create();- if (handle === 0) {- throw new Error('Failed to create geometry');- }- const vertexCount = options.vertices.length;- if (vertexCount * 4 > VERTEX_BUFFER_SIZE * 4) {- throw new Error(`Vertex data too large: ${vertexCount} floats (max ${VERTEX_BUFFER_SIZE})`);- }- m.HEAPF32.set(options.vertices, vertexPtr / 4);- const layoutCount = options.layout.length;- const layoutArray = new Int32Array(layoutCount);- for (let i = 0; i < layoutCount; i++) {- layoutArray[i] = options.layout[i].type;- }- const heap32 = new Int32Array(m.HEAPU8.buffer, layoutPtr, layoutCount);- heap32.set(layoutArray);- m.geometry_init(handle, vertexPtr, vertexCount, layoutPtr, layoutCount, options.dynamic ?? false);- if (options.indices) {- const indexCount = options.indices.length;- if (indexCount * 4 > INDEX_BUFFER_SIZE * 4) {- throw new Error(`Index data too large: ${indexCount} indices (max ${INDEX_BUFFER_SIZE})`);- }- if (options.indices instanceof Uint16Array) {- const heap16 = new Uint16Array(m.HEAPU8.buffer, indexPtr, indexCount);- heap16.set(options.indices);- m.geometry_setIndices16(handle, indexPtr, indexCount);- }- else {- const heap32 = new Uint32Array(m.HEAPU8.buffer, indexPtr, indexCount);- heap32.set(options.indices);- m.geometry_setIndices32(handle, indexPtr, indexCount);- }- }- return handle;- },- /**- * Updates vertices of a dynamic geometry.- * @param handle Geometry handle- * @param vertices New vertex data- * @param offset Offset in floats- */- updateVertices(handle, vertices, offset = 0) {- const m = getModule$1();- const vertexCount = vertices.length;- if (vertexCount * 4 > VERTEX_BUFFER_SIZE * 4) {- throw new Error(`Vertex data too large: ${vertexCount} floats (max ${VERTEX_BUFFER_SIZE})`);- }- m.HEAPF32.set(vertices, vertexPtr / 4);- m.geometry_updateVertices(handle, vertexPtr, vertexCount, offset);- },- /**- * Releases a geometry.- * @param handle Geometry handle- */- release(handle) {- if (handle > 0) {- getModule$1().geometry_release(handle);- }- },- /**- * Checks if a geometry handle is valid.- * @param handle Geometry handle- * @returns True if valid- */- isValid(handle) {- if (!module$3 || handle <= 0)- return false;- return module$3.geometry_isValid(handle);- },- // =========================================================================- // Helper Functions- // =========================================================================- /**- * Creates a unit quad geometry (1x1, centered at origin).- * @returns Geometry handle- */- createQuad(width = 1, height = 1) {- const hw = width / 2;- const hh = height / 2;- return Geometry.create({- vertices: new Float32Array([- // x, y, u, v- -hw, -hh, 0, 0,- hw, -hh, 1, 0,- hw, hh, 1, 1,- -hw, hh, 0, 1,- ]),- layout: [- { name: 'a_position', type: DataType.Float2 },- { name: 'a_texCoord', type: DataType.Float2 },- ],- indices: new Uint16Array([0, 1, 2, 2, 3, 0]),- });- },- /**- * Creates a circle geometry.- * @param radius Circle radius- * @param segments Number of segments- * @returns Geometry handle- */- createCircle(radius = 1, segments = 32) {- const vertices = [];- const indices = [];- vertices.push(0, 0, 0.5, 0.5);- for (let i = 0; i <= segments; i++) {- const angle = (i / segments) * Math.PI * 2;- const x = Math.cos(angle) * radius;- const y = Math.sin(angle) * radius;- const u = (Math.cos(angle) + 1) / 2;- const v = (Math.sin(angle) + 1) / 2;- vertices.push(x, y, u, v);- }- for (let i = 1; i <= segments; i++) {- indices.push(0, i, i + 1);- }- return Geometry.create({- vertices: new Float32Array(vertices),- layout: [- { name: 'a_position', type: DataType.Float2 },- { name: 'a_texCoord', type: DataType.Float2 },- ],- indices: new Uint16Array(indices),- });- },- /**- * Creates a polygon geometry from vertices.- * @param points Array of {x, y} points- * @returns Geometry handle- */- createPolygon(points) {- if (points.length < 3) {- throw new Error('Polygon must have at least 3 points');- }- let minX = Infinity, minY = Infinity;- let maxX = -Infinity, maxY = -Infinity;- for (const p of points) {- minX = Math.min(minX, p.x);- minY = Math.min(minY, p.y);- maxX = Math.max(maxX, p.x);- maxY = Math.max(maxY, p.y);- }- const vertices = [];- for (const p of points) {- const u = (p.x - minX) / (maxX - minX);- const v = (p.y - minY) / (maxY - minY);- vertices.push(p.x, p.y, u, v);- }- const indices = [];- for (let i = 1; i < points.length - 1; i++) {- indices.push(0, i, i + 1);- }- return Geometry.create({- vertices: new Float32Array(vertices),- layout: [- { name: 'a_position', type: DataType.Float2 },- { name: 'a_texCoord', type: DataType.Float2 },- ],- indices: new Uint16Array(indices),- });- },-};--/**- * @file postprocess.ts- * @brief Post-processing effects API- * @details Provides full-screen post-processing effects like blur, vignette, etc.- */-// =============================================================================-// Internal State-// =============================================================================-let module$2 = null;-// =============================================================================-// Initialization-// =============================================================================-function initPostProcessAPI(wasmModule) {- module$2 = wasmModule;-}-function shutdownPostProcessAPI() {- if (module$2 && PostProcess.isInitialized()) {- PostProcess.shutdown();- }- module$2 = null;-}-// =============================================================================-// PostProcess API-// =============================================================================-function getModule() {- if (!module$2) {- throw new Error('PostProcess API not initialized. Call initPostProcessAPI() first.');- }- return module$2;-}-const PostProcess = {- /**- * Initializes the post-processing pipeline.- * @param width Framebuffer width- * @param height Framebuffer height- * @returns True on success- */- init(width, height) {- return getModule().postprocess_init(width, height);- },- /**- * Shuts down the post-processing pipeline.- */- shutdown() {- getModule().postprocess_shutdown();- },- /**- * Resizes the framebuffers.- * @param width New width- * @param height New height- */- resize(width, height) {- getModule().postprocess_resize(width, height);- },- /**- * Adds a post-processing pass.- * @param name Unique name for the pass- * @param shader Shader handle- * @returns Pass index- */- addPass(name, shader) {- return getModule().postprocess_addPass(name, shader);- },- /**- * Removes a pass by name.- * @param name Pass name- */- removePass(name) {- getModule().postprocess_removePass(name);- },- /**- * Enables or disables a pass.- * @param name Pass name- * @param enabled Whether to enable the pass- */- setEnabled(name, enabled) {- getModule().postprocess_setPassEnabled(name, enabled);- },- /**- * Checks if a pass is enabled.- * @param name Pass name- * @returns True if enabled- */- isEnabled(name) {- return getModule().postprocess_isPassEnabled(name);- },- /**- * Sets a float uniform on a pass.- * @param passName Pass name- * @param uniform Uniform name- * @param value Float value- */- setUniform(passName, uniform, value) {- getModule().postprocess_setUniformFloat(passName, uniform, value);- },- /**- * Sets a vec4 uniform on a pass.- * @param passName Pass name- * @param uniform Uniform name- * @param value Vec4 value- */- setUniformVec4(passName, uniform, value) {- getModule().postprocess_setUniformVec4(passName, uniform, value.x, value.y, value.z, value.w);- },- /**- * Begins rendering to the post-process pipeline.- * Call this before rendering your scene.- */- begin() {- getModule().postprocess_begin();- },- /**- * Ends and processes all passes.- * Call this after rendering your scene.- */- end() {- getModule().postprocess_end();- },- /**- * Gets the number of passes.- */- getPassCount() {- return getModule().postprocess_getPassCount();- },- /**- * Checks if the pipeline is initialized.- */- isInitialized() {- if (!module$2)- return false;- return module$2.postprocess_isInitialized();- },- /**- * Sets bypass mode to skip FBO rendering entirely.- * When bypassed, begin()/end() become no-ops and scene renders directly to screen.- * Use this when no post-processing passes are needed for maximum performance.- * @param bypass Whether to bypass the pipeline- */- setBypass(bypass) {- getModule().postprocess_setBypass(bypass);- },- /**- * Checks if bypass mode is enabled.- * @returns True if bypassed- */- isBypassed() {- if (!module$2)- return true;- return module$2.postprocess_isBypassed();- },- // =========================================================================- // Built-in Effects- // =========================================================================- /**- * Creates a blur effect shader.- * @returns Shader handle- */- createBlur() {- const fragmentSrc = `#version 300 es-precision highp float;--in vec2 v_texCoord;-uniform sampler2D u_texture;-uniform vec2 u_resolution;-uniform float u_intensity;-out vec4 fragColor;--void main() {- vec2 texelSize = 1.0 / u_resolution;- float offset = u_intensity;-- vec4 color = vec4(0.0);- color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;- color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;- color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;- color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;- color += texture(u_texture, v_texCoord) * 0.25;- color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;- color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;- color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;- color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;-- fragColor = color;-}-`;- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);- },- /**- * Creates a vignette effect shader.- * @returns Shader handle- */- createVignette() {- const fragmentSrc = `#version 300 es-precision highp float;--in vec2 v_texCoord;-uniform sampler2D u_texture;-uniform float u_intensity;-uniform float u_softness;-out vec4 fragColor;--void main() {- vec4 color = texture(u_texture, v_texCoord);- vec2 uv = v_texCoord * 2.0 - 1.0;- float dist = length(uv);- float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);- fragColor = vec4(color.rgb * vignette, color.a);-}-`;- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);- },- /**- * Creates a grayscale effect shader.- * @returns Shader handle- */- createGrayscale() {- const fragmentSrc = `#version 300 es-precision highp float;--in vec2 v_texCoord;-uniform sampler2D u_texture;-uniform float u_intensity;-out vec4 fragColor;--void main() {- vec4 color = texture(u_texture, v_texCoord);- float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));- fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);-}-`;- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);- },- /**- * Creates a chromatic aberration effect shader.- * @returns Shader handle- */- createChromaticAberration() {- const fragmentSrc = `#version 300 es-precision highp float;--in vec2 v_texCoord;-uniform sampler2D u_texture;-uniform vec2 u_resolution;-uniform float u_intensity;-out vec4 fragColor;--void main() {- vec2 offset = u_intensity / u_resolution;- float r = texture(u_texture, v_texCoord + offset).r;- float g = texture(u_texture, v_texCoord).g;- float b = texture(u_texture, v_texCoord - offset).b;- float a = texture(u_texture, v_texCoord).a;- fragColor = vec4(r, g, b, a);-}-`;- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);- },-};-// =============================================================================-// Shared Vertex Shader-// =============================================================================-const POSTPROCESS_VERTEX = `#version 300 es-precision highp float;--layout(location = 0) in vec2 a_position;-layout(location = 1) in vec2 a_texCoord;--out vec2 v_texCoord;--void main() {- v_texCoord = a_texCoord;- gl_Position = vec4(a_position, 0.0, 1.0);-}-`;--var RenderStage;-(function (RenderStage) {- RenderStage[RenderStage["Background"] = 0] = "Background";- RenderStage[RenderStage["Opaque"] = 1] = "Opaque";- RenderStage[RenderStage["Transparent"] = 2] = "Transparent";- RenderStage[RenderStage["Overlay"] = 3] = "Overlay";-})(RenderStage || (RenderStage = {}));-let module$1 = null;-let viewProjectionPtr = 0;-function initRendererAPI(wasmModule) {- module$1 = wasmModule;- viewProjectionPtr = module$1._malloc(16 * 4);-}-function shutdownRendererAPI() {- if (module$1 && viewProjectionPtr) {- module$1._free(viewProjectionPtr);- viewProjectionPtr = 0;- }- module$1 = null;-}-const Renderer = {- init(width, height) {- module$1?.renderer_init(width, height);- },- resize(width, height) {- module$1?.renderer_resize(width, height);- },- begin(viewProjection, target) {- if (!module$1 || !viewProjectionPtr)- return;- module$1.HEAPF32.set(viewProjection, viewProjectionPtr / 4);- module$1.renderer_begin(viewProjectionPtr, target ?? 0);- },- end() {- module$1?.renderer_end();- },- submitSprites(registry) {- if (!module$1)- return;- module$1.renderer_submitSprites(registry._cpp);- },- submitSpine(registry) {- if (!module$1)- return;- module$1.renderer_submitSpine(registry._cpp);- },- setStage(stage) {- module$1?.renderer_setStage(stage);- },- createRenderTarget(width, height) {- return module$1?.renderer_createTarget(width, height) ?? 0;- },- releaseRenderTarget(handle) {- module$1?.renderer_releaseTarget(handle);- },- getTargetTexture(handle) {- return module$1?.renderer_getTargetTexture(handle) ?? 0;- },- setClearColor(r, g, b, a) {- module$1?.renderer_setClearColor?.(r, g, b, a);- },- getStats() {- if (!module$1) {- return { drawCalls: 0, triangles: 0, sprites: 0, spine: 0, meshes: 0, culled: 0 };- }- return {- drawCalls: module$1.renderer_getDrawCalls(),- triangles: module$1.renderer_getTriangles(),- sprites: module$1.renderer_getSprites(),- spine: module$1.renderer_getSpine(),- meshes: module$1.renderer_getMeshes(),- culled: module$1.renderer_getCulled(),- };- },-};--/**- * @file customDraw.ts- * @brief Custom draw callback registration for the render pipeline- */-const callbacks = new Map();-function registerDrawCallback(id, fn) {- callbacks.set(id, fn);-}-function unregisterDrawCallback(id) {- callbacks.delete(id);-}-function clearDrawCallbacks() {- callbacks.clear();-}-function getDrawCallbacks() {- return callbacks;-}--/**- * @file renderPipeline.ts- * @brief Unified render pipeline for runtime and editor- */-class RenderPipeline {- render(params) {- const { registry, viewProjection, width, height, elapsed } = params;- Renderer.resize(width, height);- const usePostProcess = PostProcess.isInitialized()- && PostProcess.getPassCount() > 0- && !PostProcess.isBypassed();- if (usePostProcess) {- PostProcess.resize(width, height);- PostProcess.begin();- }- Renderer.begin(viewProjection);- Renderer.submitSprites(registry);- Renderer.submitSpine(registry);- Renderer.end();- const cbs = getDrawCallbacks();- if (cbs.size > 0) {- Draw.begin(viewProjection);- for (const fn of cbs.values()) {- try {- fn(elapsed);- }- catch (e) {- console.warn('[CustomDraw]', e);- }- }- Draw.end();- }- if (usePostProcess) {- PostProcess.end();- }- }-}--/**- * @file app.ts- * @brief Application builder and web platform integration- */-// =============================================================================-// App-// =============================================================================-class App {- constructor() {- this.systems_ = new Map();- this.runner_ = null;- this.running_ = false;- this.lastTime_ = 0;- this.module_ = null;- this.mainLoop = () => {- if (!this.running_) {- return;- }- const now = performance.now();- const deltaMs = now - this.lastTime_;- this.lastTime_ = now;- const delta = deltaMs / 1000;- this.updateTime(delta);- this.runSchedule(Schedule.First);- this.runSchedule(Schedule.PreUpdate);- this.runSchedule(Schedule.Update);- this.runSchedule(Schedule.PostUpdate);- this.runSchedule(Schedule.Last);- requestAnimationFrame(this.mainLoop);- };- this.world_ = new World();- this.resources_ = new ResourceStorage();- for (const s of Object.values(Schedule)) {- if (typeof s === 'number') {- this.systems_.set(s, []);- }- }- }- static new() {- return new App();- }- // =========================================================================- // Plugins- // =========================================================================- addPlugin(plugin) {- plugin.build(this);- return this;- }- // =========================================================================- // Systems- // =========================================================================- addSystemToSchedule(schedule, system) {- this.systems_.get(schedule).push({ system });- return this;- }- addSystem(system) {- return this.addSystemToSchedule(Schedule.Update, system);- }- addStartupSystem(system) {- return this.addSystemToSchedule(Schedule.Startup, system);- }- // =========================================================================- // C++ Integration- // =========================================================================- connectCpp(cppRegistry, module) {- this.world_.connectCpp(cppRegistry);- if (module) {- this.module_ = module;- }- return this;- }- get wasmModule() {- return this.module_;- }- // =========================================================================- // World Access- // =========================================================================- get world() {- return this.world_;- }- // =========================================================================- // Resource Access- // =========================================================================- insertResource(resource, value) {- this.resources_.insert(resource, value);- return this;- }- getResource(resource) {- return this.resources_.get(resource);- }- hasResource(resource) {- return this.resources_.has(resource);- }- // =========================================================================- // Run- // =========================================================================- run() {- if (this.running_) {- return;- }- this.running_ = true;- this.runner_ = new SystemRunner(this.world_, this.resources_);- this.resources_.insert(Time, { delta: 0, elapsed: 0, frameCount: 0 });- this.runSchedule(Schedule.Startup);- this.lastTime_ = performance.now();- this.mainLoop();- }- quit() {- this.running_ = false;- shutdownRendererAPI();- shutdownPostProcessAPI();- shutdownGeometryAPI();- shutdownMaterialAPI();- shutdownDrawAPI();- }- // =========================================================================- // Internal- // =========================================================================- runSchedule(schedule) {- const systems = this.systems_.get(schedule);- if (!systems || !this.runner_) {- return;- }- for (const entry of systems) {- this.runner_.run(entry.system);- }- }- updateTime(delta) {- const time = this.resources_.get(Time);- const newTime = {- delta,- elapsed: time.elapsed + delta,- frameCount: time.frameCount + 1- };- this.resources_.set(Time, newTime);- }-}-function createWebApp(module, options) {- const app = App.new();- const cppRegistry = new module.Registry();- app.connectCpp(cppRegistry, module);- if (options?.glContextHandle) {- module.initRendererWithContext(options.glContextHandle);- }- else {- module.initRenderer();- }- initDrawAPI(module);- initMaterialAPI(module);- initGeometryAPI(module);- initPostProcessAPI(module);- initRendererAPI(module);- const pipeline = new RenderPipeline();- let startTime = performance.now();- const getViewportSize = options?.getViewportSize ?? (() => ({- width: window.innerWidth * (window.devicePixelRatio || 1),- height: window.innerHeight * (window.devicePixelRatio || 1)- }));- const renderSystem = {- _id: Symbol('RenderSystem'),- _name: 'RenderSystem',- _params: [],- _fn: () => {- const { width, height } = getViewportSize();- const vp = computeViewProjection(cppRegistry, width, height);- const elapsed = (performance.now() - startTime) / 1000;- pipeline.render({- registry: { _cpp: cppRegistry },- viewProjection: vp,- width, height, elapsed,- });- }- };- app.addSystemToSchedule(Schedule.Last, renderSystem);- app.addPlugin(textPlugin);- return app;-}-// =============================================================================-// View-Projection Computation-// =============================================================================-const IDENTITY = new Float32Array([- 1, 0, 0, 0,- 0, 1, 0, 0,- 0, 0, 1, 0,- 0, 0, 0, 1,-]);-function computeViewProjection(registry, width, height) {- const count = registry.entityCount();- const scanLimit = count + 1000;- for (let e = 0; e < scanLimit; e++) {- if (!registry.valid(e) || !registry.hasCamera(e) || !registry.hasLocalTransform(e)) {- continue;- }- const camera = registry.getCamera(e);- if (!camera.isActive)- continue;- const transform = registry.getLocalTransform(e);- const aspect = width / height;- let projection;- if (camera.projectionType === 1) {- const halfH = camera.orthoSize;- const halfW = halfH * aspect;- projection = ortho(-halfW, halfW, -halfH, halfH, camera.nearPlane, camera.farPlane);- }- else {- projection = perspective(camera.fov * Math.PI / 180, aspect, camera.nearPlane, camera.farPlane);- }- const view = invertTranslation(transform.position.x, transform.position.y, transform.position.z);- return multiply(projection, view);- }- return IDENTITY;-}-function ortho(left, right, bottom, top, near, far) {- const m = new Float32Array(16);- const rl = right - left;- const tb = top - bottom;- const fn = far - near;- m[0] = 2 / rl;- m[5] = 2 / tb;- m[10] = -2 / fn;- m[12] = -(right + left) / rl;- m[13] = -(top + bottom) / tb;- m[14] = -(far + near) / fn;- m[15] = 1;- return m;-}-function perspective(fovRad, aspect, near, far) {- const m = new Float32Array(16);- const f = 1.0 / Math.tan(fovRad / 2);- const nf = near - far;- m[0] = f / aspect;- m[5] = f;- m[10] = (far + near) / nf;- m[11] = -1;- m[14] = (2 * far * near) / nf;- return m;-}-function invertTranslation(x, y, z) {- const m = new Float32Array(16);- m[0] = 1;- m[5] = 1;- m[10] = 1;- m[15] = 1;- m[12] = -x;- m[13] = -y;- m[14] = -z;- return m;-}-function multiply(a, b) {- const m = new Float32Array(16);- for (let i = 0; i < 4; i++) {- for (let j = 0; j < 4; j++) {- m[j * 4 + i] =- a[0 * 4 + i] * b[j * 4 + 0] +- a[1 * 4 + i] * b[j * 4 + 1] +- a[2 * 4 + i] * b[j * 4 + 2] +- a[3 * 4 + i] * b[j * 4 + 3];- }- }- return m;-}--/**- * @file MaterialLoader.ts- * @brief Material asset loading and caching- */-// =============================================================================-// MaterialLoader-// =============================================================================-class MaterialLoader {- constructor(shaderLoader, basePath = '') {- this.cache_ = new Map();- this.pending_ = new Map();- this.shaderLoader_ = shaderLoader;- this.basePath_ = basePath;- }- async load(path) {- const cached = this.cache_.get(path);- if (cached) {- return cached;- }- const pending = this.pending_.get(path);- if (pending) {- return pending;- }- const promise = this.loadInternal(path);- this.pending_.set(path, promise);- try {- const result = await promise;- this.cache_.set(path, result);- return result;- }- finally {- this.pending_.delete(path);- }- }- get(path) {- return this.cache_.get(path);- }- has(path) {- return this.cache_.has(path);- }- release(path) {- const loaded = this.cache_.get(path);- if (loaded) {- Material.release(loaded.handle);- this.cache_.delete(path);- }- }- releaseAll() {- for (const loaded of this.cache_.values()) {- Material.release(loaded.handle);- }- this.cache_.clear();- }- async loadInternal(path) {- const fullPath = this.resolvePath(path);- const exists = await platformFileExists(fullPath);- if (!exists) {- throw new Error(`Material file not found: ${fullPath}`);- }- const content = await platformReadTextFile(fullPath);- if (!content) {- throw new Error(`Failed to read material file: ${fullPath}`);- }- const data = JSON.parse(content);- if (data.type !== 'material') {- throw new Error(`Invalid material file type: ${data.type}`);- }- const shaderPath = this.resolveShaderPath(path, data.shader);- const shaderHandle = await this.shaderLoader_.load(shaderPath);- const materialHandle = Material.createFromAsset(data, shaderHandle);- return {- handle: materialHandle,- shaderHandle,- path,- };- }- resolvePath(path) {- if (path.startsWith('/') || path.startsWith('http')) {- return path;- }- return this.basePath_ ? `${this.basePath_}/${path}` : path;- }- resolveShaderPath(materialPath, shaderPath) {- if (shaderPath.startsWith('/') || shaderPath.startsWith('http') || shaderPath.startsWith('assets/')) {- return shaderPath;- }- const dir = materialPath.substring(0, materialPath.lastIndexOf('/'));- return dir ? `${dir}/${shaderPath}` : shaderPath;- }-}--/**- * @file scene.ts- * @brief Scene loading utilities- */-// =============================================================================-// Scene Loader-// =============================================================================-function loadSceneData(world, sceneData) {- const entityMap = new Map();- for (const entityData of sceneData.entities) {- const entity = world.spawn();- entityMap.set(entityData.id, entity);- for (const compData of entityData.components) {- loadComponent(world, entity, compData);- }- }- // Set parent-child relationships- for (const entityData of sceneData.entities) {- if (entityData.parent !== null) {- const entity = entityMap.get(entityData.id);- const parentEntity = entityMap.get(entityData.parent);- if (entity !== undefined && parentEntity !== undefined) {- world.setParent(entity, parentEntity);- }- }- }- return entityMap;-}-async function loadSceneWithAssets(world, sceneData, options) {- const entityMap = new Map();- const assetServer = options?.assetServer;- const texturePathToUrl = new Map();- for (const entityData of sceneData.entities) {- const entity = world.spawn();- entityMap.set(entityData.id, entity);- for (const compData of entityData.components) {- if (compData.type === 'Sprite' && assetServer) {- const data = compData.data;- if (typeof data.texture === 'string' && data.texture) {- const texturePath = data.texture;- const isDataUrl = texturePath.startsWith('data:');- const url = isDataUrl- ? texturePath- : options?.assetBaseUrl- ? `${options.assetBaseUrl}/${texturePath}`- : `/${texturePath}`;- try {- const info = await assetServer.loadTexture(url);- data.texture = info.handle;- texturePathToUrl.set(texturePath, url);- }- catch (err) {- console.warn(`Failed to load texture: ${url}`, err);- data.texture = 0;- }- }- if (typeof data.material === 'string' && data.material) {- try {- const loaded = await assetServer.loadMaterial(data.material, options?.assetBaseUrl);- data.material = loaded.handle;- }- catch (err) {- console.warn(`Failed to load material: ${data.material}`, err);- data.material = 0;- }- }- }- if (compData.type === 'SpineAnimation' && assetServer) {- const data = compData.data;- const skeletonPath = data.skeletonPath;- const atlasPath = data.atlasPath;- if (skeletonPath && atlasPath) {- const result = await assetServer.loadSpine(skeletonPath, atlasPath, options?.assetBaseUrl);- if (!result.success) {- console.warn(`Failed to load Spine: ${result.error}`);- }- }- if (typeof data.material === 'string' && data.material) {- try {- const loaded = await assetServer.loadMaterial(data.material, options?.assetBaseUrl);- data.material = loaded.handle;- }- catch (err) {- console.warn(`Failed to load material: ${data.material}`, err);- data.material = 0;- }- }- }- loadComponent(world, entity, compData);- }- }- for (const entityData of sceneData.entities) {- if (entityData.parent !== null) {- const entity = entityMap.get(entityData.id);- const parentEntity = entityMap.get(entityData.parent);- if (entity !== undefined && parentEntity !== undefined) {- world.setParent(entity, parentEntity);- }- }- }- if (assetServer && sceneData.textureMetadata) {- for (const [texturePath, metadata] of Object.entries(sceneData.textureMetadata)) {- const url = texturePathToUrl.get(texturePath);- if (url && metadata.sliceBorder) {- assetServer.setTextureMetadataByPath(url, metadata.sliceBorder);- }- }- }- return entityMap;-}-function loadComponent(world, entity, compData) {- const data = compData.data;- switch (compData.type) {- case 'LocalTransform':- world.insert(entity, LocalTransform, data);- break;- case 'Sprite':- world.insert(entity, Sprite, data);- break;- case 'Camera':- world.insert(entity, Camera, data);- break;- case 'Canvas':- world.insert(entity, Canvas, data);- break;- case 'Text':- world.insert(entity, Text, data);- break;- case 'SpineAnimation':- world.insert(entity, SpineAnimation, data);- break;- case 'UIRect':- world.insert(entity, UIRect, data);- break;- default:- console.warn(`Unknown component type: ${compData.type}`);- }-}-function updateCameraAspectRatio(world, aspectRatio) {- const cameraEntities = world.getEntitiesWithComponents([Camera]);- for (const entity of cameraEntities) {- const camera = world.get(entity, Camera);- if (camera) {- camera.aspectRatio = aspectRatio;- world.insert(entity, Camera, camera);- }- }-}--class AsyncCache {- constructor() {- this.cache_ = new Map();- this.pending_ = new Map();- }- async getOrLoad(key, loader) {- const cached = this.cache_.get(key);- if (cached !== undefined) {- return cached;- }- const pending = this.pending_.get(key);- if (pending) {- return pending;- }- const promise = loader();- this.pending_.set(key, promise);- try {- const result = await promise;- this.cache_.set(key, result);- return result;- }- finally {- this.pending_.delete(key);- }- }- get(key) {- return this.cache_.get(key);- }- has(key) {- return this.cache_.has(key);- }- delete(key) {- return this.cache_.delete(key);- }- clear() {- this.cache_.clear();- }- values() {- return this.cache_.values();- }-}--/**- * @file AssetServer.ts- * @brief Asset loading and caching system- */-// =============================================================================-// AssetServer-// =============================================================================-class AssetServer {- constructor(module) {- this.textureCache_ = new AsyncCache();- this.shaderCache_ = new AsyncCache();- this.jsonCache_ = new AsyncCache();- this.textCache_ = new AsyncCache();- this.binaryCache_ = new AsyncCache();- this.loadedSpines_ = new Set();- this.virtualFSPaths_ = new Set();- this.module_ = module;- this.canvas_ = this.createCanvas(512, 512);- this.ctx_ = this.canvas_.getContext('2d', { willReadFrequently: true });- const shaderLoader = {- load: (path) => this.loadShader(path),- get: (path) => this.shaderCache_.get(path),- };- this.materialLoader_ = new MaterialLoader(shaderLoader);- }- // =========================================================================- // Texture- // =========================================================================- /**- * Load texture with vertical flip (for Sprite/UI).- * OpenGL UV origin is bottom-left, so standard images need flipping.- */- async loadTexture(source) {- return this.loadTextureWithFlip(source, true);- }- /**- * Load texture without flip (for Spine).- * Spine runtime handles UV coordinates internally.- */- async loadTextureRaw(source) {- return this.loadTextureWithFlip(source, false);- }- getTexture(source) {- return this.textureCache_.get(this.textureCacheKey(source, true));- }- hasTexture(source) {- return this.textureCache_.has(this.textureCacheKey(source, true));- }- releaseTexture(source) {- const rm = this.module_.getResourceManager();- for (const flip of [true, false]) {- const key = this.textureCacheKey(source, flip);- const info = this.textureCache_.get(key);- if (info) {- rm.releaseTexture(info.handle);- this.textureCache_.delete(key);- }- }- }- releaseAll() {- const rm = this.module_.getResourceManager();- for (const info of this.textureCache_.values()) {- rm.releaseTexture(info.handle);- }- this.textureCache_.clear();- this.jsonCache_.clear();- this.textCache_.clear();- this.binaryCache_.clear();- }- setTextureMetadata(handle, border) {- const rm = this.module_.getResourceManager();- rm.setTextureMetadata(handle, border.left, border.right, border.top, border.bottom);- }- setTextureMetadataByPath(source, border) {- const info = this.textureCache_.get(this.textureCacheKey(source, true));- if (info) {- this.setTextureMetadata(info.handle, border);- return true;- }- return false;- }- // =========================================================================- // Spine- // =========================================================================- async loadSpine(skeletonPath, atlasPath, baseUrl) {- const cacheKey = `${skeletonPath}:${atlasPath}`;- if (this.loadedSpines_.has(cacheKey)) {- return { success: true };- }- try {- const atlasUrl = this.resolveUrl(atlasPath, baseUrl);- const atlasResponse = await fetch(atlasUrl);- if (!atlasResponse.ok) {- return { success: false, error: `Failed to fetch atlas: ${atlasUrl}` };- }- const atlasContent = await atlasResponse.text();- if (!this.writeToVirtualFS(atlasPath, atlasContent)) {- return { success: false, error: `Failed to write atlas to virtual FS: ${atlasPath}` };- }- const atlasDir = atlasPath.substring(0, atlasPath.lastIndexOf('/'));- const textureNames = this.parseAtlasTextures(atlasContent);- for (const texName of textureNames) {- const texPath = atlasDir ? `${atlasDir}/${texName}` : texName;- const texUrl = this.resolveUrl(texPath, baseUrl);- try {- const info = await this.loadTextureRaw(texUrl);- const rm = this.module_.getResourceManager();- rm.registerTextureWithPath(info.handle, texPath);- }- catch (err) {- console.warn(`[AssetServer] Failed to load Spine texture: ${texPath}`, err);- }- }- const skelUrl = this.resolveUrl(skeletonPath, baseUrl);- const skelResponse = await fetch(skelUrl);- if (!skelResponse.ok) {- return { success: false, error: `Failed to fetch skeleton: ${skelUrl}` };- }- const isBinary = skeletonPath.endsWith('.skel');- const skelData = isBinary- ? new Uint8Array(await skelResponse.arrayBuffer())- : await skelResponse.text();- if (!this.writeToVirtualFS(skeletonPath, skelData)) {- return { success: false, error: `Failed to write skeleton to virtual FS: ${skeletonPath}` };- }- this.loadedSpines_.add(cacheKey);- return { success: true };- }- catch (err) {- return { success: false, error: String(err) };- }- }- isSpineLoaded(skeletonPath, atlasPath) {- return this.loadedSpines_.has(`${skeletonPath}:${atlasPath}`);- }- // =========================================================================- // Material & Shader- // =========================================================================- async loadMaterial(path, baseUrl) {- return this.materialLoader_.load(this.resolveUrl(path, baseUrl));- }- getMaterial(path, baseUrl) {- return this.materialLoader_.get(this.resolveUrl(path, baseUrl));- }- hasMaterial(path, baseUrl) {- return this.materialLoader_.has(this.resolveUrl(path, baseUrl));- }- async loadShader(path) {- return this.shaderCache_.getOrLoad(path, () => this.loadShaderInternal(path));- }- // =========================================================================- // Generic File Loading- // =========================================================================- async loadJson(path, options) {- const url = this.resolveUrl(path, options?.baseUrl);- if (options?.noCache) {- return this.fetchJson(url);- }- return this.jsonCache_.getOrLoad(url, () => this.fetchJson(url));- }- async loadText(path, options) {- const url = this.resolveUrl(path, options?.baseUrl);- if (options?.noCache) {- return this.fetchText(url);- }- return this.textCache_.getOrLoad(url, () => this.fetchText(url));- }- async loadBinary(path, options) {- const url = this.resolveUrl(path, options?.baseUrl);- if (options?.noCache) {- return this.fetchBinary(url);- }- return this.binaryCache_.getOrLoad(url, () => this.fetchBinary(url));- }- // =========================================================================- // Scene & Batch- // =========================================================================- async loadScene(world, sceneData) {- return loadSceneWithAssets(world, sceneData, { assetServer: this });- }- async loadAll(manifest) {- const bundle = {- textures: new Map(),- materials: new Map(),- spine: new Map(),- json: new Map(),- text: new Map(),- binary: new Map(),- };- const promises = [];- if (manifest.textures) {- for (const path of manifest.textures) {- promises.push(this.loadTexture(path).then(info => { bundle.textures.set(path, info); }));- }- }- if (manifest.materials) {- for (const path of manifest.materials) {- promises.push(this.loadMaterial(path).then(mat => { bundle.materials.set(path, mat); }));- }- }- if (manifest.spine) {- for (const desc of manifest.spine) {- const key = `${desc.skeleton}:${desc.atlas}`;- promises.push(this.loadSpine(desc.skeleton, desc.atlas, desc.baseUrl).then(result => {- bundle.spine.set(key, result);- }));- }- }- if (manifest.json) {- for (const path of manifest.json) {- promises.push(this.loadJson(path).then(data => { bundle.json.set(path, data); }));- }- }- if (manifest.text) {- for (const path of manifest.text) {- promises.push(this.loadText(path).then(data => { bundle.text.set(path, data); }));- }- }- if (manifest.binary) {- for (const path of manifest.binary) {- promises.push(this.loadBinary(path).then(data => { bundle.binary.set(path, data); }));- }- }- await Promise.all(promises);- return bundle;- }- // =========================================================================- // Private - Texture- // =========================================================================- textureCacheKey(source, flip) {- return `${source}:${flip ? 'f' : 'n'}`;- }- async loadTextureWithFlip(source, flip) {- const cacheKey = this.textureCacheKey(source, flip);- return this.textureCache_.getOrLoad(cacheKey, () => this.loadTextureInternal(source, flip));- }- async loadTextureInternal(source, flip) {- const img = await this.loadImage(source);- return this.createTextureFromImage(img, flip);- }- async loadImage(source) {- return new Promise((resolve, reject) => {- const img = new Image();- img.crossOrigin = 'anonymous';- img.onload = async () => {- if (typeof createImageBitmap !== 'undefined') {- try {- const bitmap = await createImageBitmap(img, {- premultiplyAlpha: 'none',- colorSpaceConversion: 'none'- });- resolve(bitmap);- return;- }- catch {- // Fall back to Image element- }- }- resolve(img);- };- img.onerror = () => reject(new Error(`Failed to load image: ${source}`));- img.src = source;- });- }- createTextureFromImage(img, flip) {- const { width, height } = img;- if (this.canvas_.width < width || this.canvas_.height < height) {- this.canvas_.width = Math.max(this.canvas_.width, this.nextPowerOf2(width));- this.canvas_.height = Math.max(this.canvas_.height, this.nextPowerOf2(height));- }- this.ctx_.clearRect(0, 0, this.canvas_.width, this.canvas_.height);- this.ctx_.save();- if (flip) {- this.ctx_.translate(0, height);- this.ctx_.scale(1, -1);- }- this.ctx_.drawImage(img, 0, 0);- this.ctx_.restore();- const imageData = this.ctx_.getImageData(0, 0, width, height);- const pixels = new Uint8Array(imageData.data.buffer);- this.unpremultiplyAlpha(pixels);- const rm = this.module_.getResourceManager();- const ptr = this.module_._malloc(pixels.length);- this.module_.HEAPU8.set(pixels, ptr);- const handle = rm.createTexture(width, height, ptr, pixels.length, 1);- this.module_._free(ptr);- return { handle, width, height };- }- unpremultiplyAlpha(pixels) {- for (let i = 0; i < pixels.length; i += 4) {- const a = pixels[i + 3];- if (a > 0 && a < 255) {- const scale = 255 / a;- pixels[i] = Math.min(255, Math.round(pixels[i] * scale));- pixels[i + 1] = Math.min(255, Math.round(pixels[i + 1] * scale));- pixels[i + 2] = Math.min(255, Math.round(pixels[i + 2] * scale));- }- }- }- // =========================================================================- // Private - Shader- // =========================================================================- async loadShaderInternal(path) {- const exists = await platformFileExists(path);- if (!exists) {- throw new Error(`Shader file not found: ${path}`);- }- const content = await platformReadTextFile(path);- if (!content) {- throw new Error(`Failed to read shader file: ${path}`);- }- const { vertex, fragment } = this.parseEsShader(content);- if (!vertex || !fragment) {- throw new Error(`Invalid shader format: ${path}`);- }- return Material.createShader(vertex, fragment);- }- parseEsShader(content) {- const vertexMatch = content.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/);- const fragmentMatch = content.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);- return {- vertex: vertexMatch?.[1].trim() ?? null,- fragment: fragmentMatch?.[1].trim() ?? null,- };- }- // =========================================================================- // Private - Generic Fetch- // =========================================================================- async fetchJson(url) {- const response = await platformFetch(url);- if (!response.ok) {- throw new Error(`Failed to fetch JSON: ${url} (${response.status})`);- }- return response.json();- }- async fetchText(url) {- const response = await platformFetch(url);- if (!response.ok) {- throw new Error(`Failed to fetch text: ${url} (${response.status})`);- }- return response.text();- }- async fetchBinary(url) {- const response = await platformFetch(url);- if (!response.ok) {- throw new Error(`Failed to fetch binary: ${url} (${response.status})`);- }- return response.arrayBuffer();- }- // =========================================================================- // Private - Virtual FS- // =========================================================================- writeToVirtualFS(virtualPath, data) {- if (this.virtualFSPaths_.has(virtualPath)) {- return true;- }- const fs = this.module_.FS;- if (!fs) {- return false;- }- try {- this.ensureVirtualDir(virtualPath);- fs.writeFile(virtualPath, data);- this.virtualFSPaths_.add(virtualPath);- return true;- }- catch (e) {- console.error(`[AssetServer] Failed to write to virtual FS: ${virtualPath}`, e);- return false;- }- }- ensureVirtualDir(virtualPath) {- const fs = this.module_.FS;- if (!fs)- return;- const dir = virtualPath.substring(0, virtualPath.lastIndexOf('/'));- if (!dir)- return;- const parts = dir.split('/').filter(p => p);- let currentPath = '';- for (const part of parts) {- currentPath = currentPath ? `${currentPath}/${part}` : part;- try {- const analysis = fs.analyzePath(currentPath);- if (!analysis.exists) {- fs.mkdir(currentPath);- }- }- catch {- try {- fs.mkdir(currentPath);- }- catch {- // Directory might already exist- }- }- }- }- // =========================================================================- // Private - Utilities- // =========================================================================- resolveUrl(path, baseUrl) {- if (path.startsWith('/') || path.startsWith('http://') || path.startsWith('https://')) {- return path;- }- const base = baseUrl ?? this.baseUrl;- return base ? `${base}/${path}` : `/${path}`;- }- createCanvas(width, height) {- const canvas = typeof OffscreenCanvas !== 'undefined'- ? new OffscreenCanvas(width, height)- : document.createElement('canvas');- canvas.width = width;- canvas.height = height;- return canvas;- }- nextPowerOf2(n) {- let p = 1;- while (p < n)- p *= 2;- return p;- }- parseAtlasTextures(atlasContent) {- const textures = [];- for (const line of atlasContent.split('\n')) {- const trimmed = line.trim();- if (trimmed && !trimmed.includes(':') &&- (trimmed.endsWith('.png') || trimmed.endsWith('.jpg'))) {- textures.push(trimmed);- }- }- return textures;- }-}--/**- * @file AssetPlugin.ts- * @brief Plugin that provides asset loading capabilities- */-const Assets = defineResource(null, 'Assets');-// =============================================================================-// Asset Plugin-// =============================================================================-class AssetPlugin {- build(app) {- const module = app.wasmModule;- if (!module) {- console.warn('AssetPlugin: No WASM module available');- return;- }- app.insertResource(Assets, new AssetServer(module));- }-}-const assetPlugin = new AssetPlugin();--/**- * @file PreviewPlugin.ts- * @brief Plugin for editor preview functionality- */-// =============================================================================-// PreviewPlugin-// =============================================================================-class PreviewPlugin {- constructor(sceneUrl) {- this.app_ = null;- this.loadPromise_ = null;- this.sceneUrl_ = sceneUrl;- }- build(app) {- this.app_ = app;- if (!app.hasResource(Assets)) {- app.addPlugin(assetPlugin);- }- this.loadPromise_ = this.loadScene();- }- /**- * @brief Wait for scene loading to complete- */- async waitForReady() {- if (this.loadPromise_) {- await this.loadPromise_;- }- }- async loadScene() {- if (!this.app_)- return;- try {- const response = await platformFetch(this.sceneUrl_);- if (!response.ok) {- throw new Error(`Failed to fetch scene: ${response.status}`);- }- const sceneData = await response.json();- const assets = this.app_.getResource(Assets);- await assets.loadScene(this.app_.world, sceneData);- this.ensureCamera();- }- catch (err) {- console.error('[PreviewPlugin] Failed to load scene:', err);- }- }- ensureCamera() {- if (!this.app_)- return;- const world = this.app_.world;- let hasActiveCamera = false;- const cameraEntities = world.getEntitiesWithComponents([Camera]);- for (const entity of cameraEntities) {- const camera = world.get(entity, Camera);- if (camera.isActive) {- hasActiveCamera = true;- break;- }- }- if (!hasActiveCamera) {- console.warn('[PreviewPlugin] No active camera found, creating default camera');- const cameraEntity = world.spawn();- const transformData = {- position: { x: 0, y: 0, z: 10 },- rotation: { x: 0, y: 0, z: 0, w: 1 },- scale: { x: 1, y: 1, z: 1 },- };- world.insert(cameraEntity, LocalTransform, transformData);- const cameraData = {- isActive: true,- projectionType: 0,- fov: 60,- orthoSize: 540,- nearPlane: 0.1,- farPlane: 1000,- aspectRatio: 1.77,- priority: 0,- };- world.insert(cameraEntity, Camera, cameraData);- }- }-}--/**- * @file spine.ts- * @brief Spine animation control API- */-// =============================================================================-// SpineController-// =============================================================================-/**- * Controller for Spine skeletal animations- *- * @example- * ```typescript- * const spine = new SpineController(wasmModule);- *- * // Play animation- * spine.play(entity, 'run', true);- *- * // Queue next animation- * spine.addAnimation(entity, 'idle', true, 0.2);- *- * // Change skin- * spine.setSkin(entity, 'warrior');- *- * // Get bone position for effects- * const pos = spine.getBonePosition(entity, 'weapon');- * if (pos) {- * spawnEffect(pos.x, pos.y);- * }- *- * // Listen for events- * spine.on(entity, 'event', (e) => {- * if (e.eventName === 'footstep') {- * playSound('footstep');- * }- * });- * ```- */-class SpineController {- constructor(wasmModule) {- this.module_ = wasmModule;- this.listeners_ = new Map();- this.setupEventBridge();- }- // =========================================================================- // Animation Control- // =========================================================================- /**- * Plays an animation, replacing any current animation on the track- * @param entity Target entity- * @param animation Animation name- * @param loop Whether to loop the animation- * @param track Animation track (default 0)- * @returns True if animation was set- */- play(entity, animation, loop = true, track = 0) {- if (!this.module_.spinePlayAnimation)- return false;- return this.module_.spinePlayAnimation(entity, animation, loop, track);- }- /**- * Adds an animation to the queue- * @param entity Target entity- * @param animation Animation name- * @param loop Whether to loop- * @param delay Delay before starting (seconds)- * @param track Animation track (default 0)- * @returns True if animation was queued- */- addAnimation(entity, animation, loop = true, delay = 0, track = 0) {- if (!this.module_.spineAddAnimation)- return false;- return this.module_.spineAddAnimation(entity, animation, loop, delay, track);- }- /**- * Sets an empty animation to mix out the current animation- * @param entity Target entity- * @param mixDuration Duration of the mix out- * @param track Animation track (default 0)- */- setEmptyAnimation(entity, mixDuration = 0.2, track = 0) {- if (!this.module_.spineSetEmptyAnimation)- return;- this.module_.spineSetEmptyAnimation(entity, mixDuration, track);- }- /**- * Clears all animations on a track- * @param entity Target entity- * @param track Animation track (default 0)- */- clearTrack(entity, track = 0) {- if (!this.module_.spineClearTrack)- return;- this.module_.spineClearTrack(entity, track);- }- /**- * Clears all tracks- * @param entity Target entity- */- clearTracks(entity) {- if (!this.module_.spineClearTracks)- return;- this.module_.spineClearTracks(entity);- }- // =========================================================================- // Skin Control- // =========================================================================- /**- * Sets the current skin- * @param entity Target entity- * @param skinName Skin name- * @returns True if skin was set- */- setSkin(entity, skinName) {- if (!this.module_.spineSetSkin)- return false;- return this.module_.spineSetSkin(entity, skinName);- }- /**- * Gets available skin names- * @param entity Target entity- * @returns Array of skin names- */- getSkins(entity) {- if (!this.module_.spineGetSkins)- return [];- return this.module_.spineGetSkins(entity) || [];- }- // =========================================================================- // Queries- // =========================================================================- /**- * Gets available animation names- * @param entity Target entity- * @returns Array of animation names- */- getAnimations(entity) {- if (!this.module_.spineGetAnimations)- return [];- return this.module_.spineGetAnimations(entity) || [];- }- /**- * Gets the current animation on a track- * @param entity Target entity- * @param track Animation track (default 0)- * @returns Animation name or null- */- getCurrentAnimation(entity, track = 0) {- if (!this.module_.spineGetCurrentAnimation)- return null;- return this.module_.spineGetCurrentAnimation(entity, track);- }- /**- * Gets the duration of an animation- * @param entity Target entity- * @param animation Animation name- * @returns Duration in seconds, or 0 if not found- */- getAnimationDuration(entity, animation) {- if (!this.module_.spineGetAnimationDuration)- return 0;- return this.module_.spineGetAnimationDuration(entity, animation);- }- /**- * Gets detailed track entry info- * @param entity Target entity- * @param track Animation track (default 0)- * @returns Track entry info or null- */- getTrackEntry(entity, track = 0) {- if (!this.module_.spineGetTrackEntry)- return null;- return this.module_.spineGetTrackEntry(entity, track);- }- // =========================================================================- // Bone/Slot Access- // =========================================================================- /**- * Gets world position of a bone- * @param entity Target entity- * @param boneName Bone name- * @returns Position or null if not found- */- getBonePosition(entity, boneName) {- if (!this.module_.spineGetBonePosition)- return null;- const result = this.module_.spineGetBonePosition(entity, boneName);- if (!result)- return null;- return { x: result.x, y: result.y };- }- /**- * Gets world rotation of a bone in degrees- * @param entity Target entity- * @param boneName Bone name- * @returns Rotation in degrees or null- */- getBoneRotation(entity, boneName) {- if (!this.module_.spineGetBoneRotation)- return null;- return this.module_.spineGetBoneRotation(entity, boneName);- }- /**- * Sets the attachment for a slot- * @param entity Target entity- * @param slotName Slot name- * @param attachmentName Attachment name (null to clear)- */- setAttachment(entity, slotName, attachmentName) {- if (!this.module_.spineSetAttachment)- return;- this.module_.spineSetAttachment(entity, slotName, attachmentName || '');- }- // =========================================================================- // Events- // =========================================================================- /**- * Registers an event callback- * @param entity Target entity- * @param type Event type- * @param callback Callback function- */- on(entity, type, callback) {- if (!this.listeners_.has(entity)) {- this.listeners_.set(entity, new Map());- }- const entityListeners = this.listeners_.get(entity);- if (!entityListeners.has(type)) {- entityListeners.set(type, new Set());- }- entityListeners.get(type).add(callback);- }- /**- * Unregisters an event callback- * @param entity Target entity- * @param type Event type- * @param callback Callback function- */- off(entity, type, callback) {- const entityListeners = this.listeners_.get(entity);- if (!entityListeners)- return;- const typeListeners = entityListeners.get(type);- if (!typeListeners)- return;- typeListeners.delete(callback);- }- /**- * Removes all event listeners for an entity- * @param entity Target entity- */- removeAllListeners(entity) {- this.listeners_.delete(entity);- }- // =========================================================================- // Private- // =========================================================================- setupEventBridge() {- if (typeof window !== 'undefined') {- window.__esengine_spineEvent = (entity, eventData) => {- this.dispatchEvent(entity, eventData);- };- }- }- dispatchEvent(entity, eventData) {- const entityListeners = this.listeners_.get(entity);- if (!entityListeners)- return;- const event = {- type: eventData.type,- entity,- track: eventData.track ?? 0,- animation: eventData.animation ?? null,- eventName: eventData.eventName,- intValue: eventData.intValue,- floatValue: eventData.floatValue,- stringValue: eventData.stringValue,- };- const typeListeners = entityListeners.get(event.type);- if (typeListeners) {- typeListeners.forEach(callback => {- try {- callback(event);- }- catch (e) {- console.error('Error in Spine event callback:', e);- }- });- }- }-}-// =============================================================================-// Factory Function-// =============================================================================-/**- * Creates a SpineController instance- * @param wasmModule The ESEngine WASM module- * @returns SpineController instance- */-function createSpineController(wasmModule) {- return new SpineController(wasmModule);-}--let editorMode = false;-function setEditorMode(active) {- editorMode = active;-}-function isEditor() {- return editorMode;-}-function isRuntime() {- return !editorMode;-}--/**- * @file index.ts- * @brief ESEngine SDK - Web entry point (auto-initializes Web platform)- */-// Initialize Web platform-setPlatform(webAdapter);--export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BlendMode, Camera, Canvas, Children, Commands, CommandsInstance, DataType, Draw, EntityCommands, Geometry, INVALID_ENTITY, INVALID_TEXTURE, Input, LocalTransform, Material, MaterialLoader, Mut, Parent, PostProcess, PreviewPlugin, Query, QueryInstance, RenderPipeline, RenderStage, Renderer, Res, ResMut, Schedule, ShaderSources, SpineAnimation, SpineController, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIRect, Velocity, World, WorldTransform, assetPlugin, clearDrawCallbacks, color, createSpineController, createWebApp, defineComponent, defineResource, defineSystem, defineTag, getComponentDefaults, getPlatform, getPlatformType, initDrawAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, isBuiltinComponent, isEditor, isPlatformInitialized, isRuntime, isWeChat, isWeb, loadComponent, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, registerDrawCallback, registerMaterialCallback, setEditorMode, shutdownDrawAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textPlugin, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, 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 r(){return e?.name??null}function s(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}const f=new class{constructor(){this.name="web"}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),r={};return n.headers.forEach((e,t)=>{r[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:r,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const r=await WebAssembly.instantiate(n,t);return{instance:r.instance,module:r.module}}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){const n=t??document.querySelector("canvas")??document.body;document.addEventListener("keydown",t=>e.onKeyDown(t.code)),document.addEventListener("keyup",t=>e.onKeyUp(t.code)),n.addEventListener("mousemove",t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)}),n.addEventListener("mousedown",t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)}),n.addEventListener("mouseup",t=>{e.onPointerUp(t.button)}),n.addEventListener("touchstart",t=>{const r=t.touches[0];if(r){const t=n.getBoundingClientRect();e.onPointerDown(0,r.clientX-t.left,r.clientY-t.top)}}),n.addEventListener("touchmove",t=>{const r=t.touches[0];if(r){const t=n.getBoundingClientRect();e.onPointerMove(r.clientX-t.left,r.clientY-t.top)}}),n.addEventListener("touchend",()=>{e.onPointerUp(0)}),n.addEventListener("wheel",t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)})}},p=0,_=4294967295,m=(e=0,t=0)=>({x:e,y:t}),g=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),y=(e=0,t=0,n=0,r=1)=>({x:e,y:t,z:n,w:r}),w=(e=1,t=1,n=1,r=1)=>({x:e,y:t,z:n,w:r}),x=(e=1,t=0,n=0,r=0)=>({w:e,x:t,y:n,z:r});let v=0;function S(e,t){const n=++v;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>({...t,...e})}}function P(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function C(e,t){const n=P(),r=n.get(e);if(r)return r;const s=S(e,t);return n.set(e,s),R(e,t,!1),s}function T(e){const t=P(),n=t.get(e);if(n)return n;const r=S(e,{});return t.set(e,r),R(e,{},!0),r}function b(e){return P().get(e)}function M(){P().clear()}function R(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function E(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function A(e){return!0===e._builtin}const U=E("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),F=E("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=E("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}),I=E("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0}),B=E("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{x:0,y:0,z:0,w:1}}),k=E("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),$=E("Parent",{entity:0}),L=E("Children",{entities:[]}),D=E("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}),W={LocalTransform:U,WorldTransform:F,Sprite:z,Camera:I,Canvas:B,Velocity:k,Parent:$,Children:L,SpineAnimation:D};function H(e){const t=W[e];if(t)return{...t._default};const n=b(e);return n?{...n._default}:null}let O=0;function N(e,t){const n=++O;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function j(e){return{_type:"res",_resource:e}}function X(e){return{_type:"res_mut",_resource:e}}class V{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 G{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 V(this.get(e),t=>this.set(e,t))}}const Y=N({delta:0,elapsed:0,frameCount:0},"Time");function K(e){return{_type:"mut",_component:e}}function q(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function J(...e){return function(e,t=[],n=[]){const r=[];return e.forEach((e,t)=>{q(e)&&r.push(t)}),{_type:"query",_components:e,_mutIndices:r,_with:t,_without:n}}(e)}class Q{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:n,_without:r}=this.descriptor_,s=e.map(e=>this.getActualComponent(e)),o=[...s,...n],i=this.world_.getEntitiesWithComponents(o);let a=null,c=[];try{for(const e of i){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 o=s.map(t=>this.world_.get(e,t));for(const e of t)c.push({component:s[e],data:o[e]});a=e,yield[e,...o]}}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 Z(){return{_type:"commands"}}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 n;return n=A(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 te{constructor(e,t){this.pending_=[],this.world_=e,this.resources_=t}spawn(){return new ee(this,null)}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,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.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 ne;!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"}(ne||(ne={}));let re=0;function se(e,t,n){const r=++re;return{_id:Symbol(`System_${r}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${r}`}}function oe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function ie(e){oe().push({schedule:ne.Update,system:e})}function ae(e){oe().push({schedule:ne.Startup,system:e})}function ce(e,t){oe().push({schedule:e,system:t})}class le{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 Q(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 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 he=N(new ue,"Input");class de{constructor(e){this.target_=e??null}build(e){const n=new ue;e.insertResource(he,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,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(ne.First,se([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const fe=new de;class pe{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return A(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return A(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return A(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){A(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 _e,me,ge;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(_e||(_e={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(me||(me={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(ge||(ge={}));const ye=C("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{x:1,y:1,z:1,w:1},align:_e.Left,verticalAlign:me.Top,wordWrap:!0,overflow:ge.Visible,lineHeight:1.2,dirty:!0});class we{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,o=s?t.size.x:0,i=s?t.size.y:0,a=e.wordWrap&&s;let c=this.wrapText(e.content,a?o: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(o):h+2*u,p=s?Math.ceil(i):d+2*u;if(s&&e.overflow===ge.Ellipsis&&d>i){const e=Math.floor(i/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,o)}}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===ge.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 me.Top:x=u;break;case me.Middle:x=(p-w)/2;break;case me.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let r;switch(e.align){case _e.Left:r=u;break;case _e.Center:r=f/2;break;case _e.Right:r=f-u;break;default:r=u}n.fillText(t,r,v),v+=l}s&&e.overflow===ge.Clip&&n.restore();const S=n.getImageData(0,0,f,p),P=new Uint8Array(S.data.buffer),C=this.flipVertically(P,f,p),T=this.module.getResourceManager(),b=this.module._malloc(C.length);this.module.HEAPU8.set(C,b);const M=T.createTexture(f,p,b,C.length,1);return this.module._free(b),{textureHandle:M,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const 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 _e.Left:return"left";case _e.Center:return"center";case _e.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}flipVertically(e,t,n){const r=4*t,s=new Uint8Array(e.length);for(let t=0;t<n;t++){const o=t*r,i=(n-1-t)*r;s.set(e.subarray(o,o+r),i)}return s}}const xe=C("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class ve{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new we(t),r=e.world;e.addSystemToSchedule(ne.PreUpdate,se([],()=>{const e=r.getEntitiesWithComponents([ye]);for(const t of e){const e=r.get(t,ye);if(!e.dirty)continue;r.has(t,z)||r.insert(t,z,{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 s=r.has(t,xe)?r.get(t,xe):null,o=n.renderForEntity(t,e,s),i=r.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},r.insert(t,z,i),e.dirty=!1}}))}}const Se=new ve;var Pe;function Ce(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"}(Pe||(Pe={}));let Te=null,be=null,Me=1;const Re=new Map;function Ee(e){Te=e,be=e.getResourceManager(),$e()}function Ae(){0!==Ie&&Te&&(Te._free(Ie),Ie=0),Re.clear(),Me=1,ze=!1,be=null,Te=null}function Ue(){if(!be)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return be}const Fe={createShader:(e,t)=>Ue().createShader(e,t),releaseShader(e){e>0&&Ue().releaseShader(e)},create(e){const t=Me++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Pe.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,r]of Object.entries(e.uniforms))n.uniforms.set(t,r);return Re.set(t,n),t},get:e=>Re.get(e),setUniform(e,t,n){const r=Re.get(e);r&&r.uniforms.set(t,n)},getUniform(e,t){const n=Re.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Re.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Re.get(e);return t?.blendMode??Pe.Normal},setDepthTest(e,t){const n=Re.get(e);n&&(n.depthTest=t)},getShader(e){const t=Re.get(e);return t?.shader??0},release(e){Re.delete(e)},isValid:e=>Re.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??Pe.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Re.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Me++,r={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Re.set(n,r),n},toAssetData(e,t){const n=Re.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=Re.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let ze=!1,Ie=0;const Be=4096;function ke(e){const t=(0===Ie&&Te&&(Ie=Te._malloc(Be)),Ie);if(0===t||!Te)return{ptr:0,count:0};let n=0,r=0;const s=Te.HEAPU8,o=Te.HEAPU32,i=Te.HEAPF32;for(const[a,c]of e){if(n+128>Be)break;const e=(new TextEncoder).encode(a),l=e.length,u=4*Math.ceil(l/4);o[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]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=d[e],n+=4;r++}return{ptr:t,count:r}}function $e(){if(!Te||ze)return;Te.materialDataProvider=(e,t,n,r,s)=>{const o=Re.get(e);if(!o)return Te.HEAPU32[t>>2]=0,Te.HEAPU32[n>>2]=0,Te.HEAPU32[r>>2]=0,void(Te.HEAPU32[s>>2]=0);Te.HEAPU32[t>>2]=o.shader,Te.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=ke(o.uniforms);Te.HEAPU32[r>>2]=i,Te.HEAPU32[s>>2]=a},ze=!0}const Le={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class De{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&&(Fe.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Fe.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),o=await this.shaderLoader_.load(s);return{handle:Fe.createFromAsset(r,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function We(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)Oe(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 He(e,t,n){const r=new Map,s=n?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();r.set(i.id,t);for(const r of i.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,o.set(t,r)}catch(t){console.warn(`Failed to load texture: ${r}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await 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,o=e.atlasPath;if(t&&o){const e=await s.loadSpine(t,o,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Oe(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=o.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}function Oe(e,t,n){const r=n.data;switch(n.type){case"LocalTransform":e.insert(t,U,r);break;case"Sprite":e.insert(t,z,r);break;case"Camera":e.insert(t,I,r);break;case"Canvas":e.insert(t,B,r);break;case"Text":e.insert(t,ye,r);break;case"SpineAnimation":e.insert(t,D,r);break;case"UIRect":e.insert(t,xe,r);break;default:{const s=b(n.type);s?e.insert(t,s,r):console.warn(`Unknown component type: ${n.type}`);break}}}function Ne(e,t){const n=e.getEntitiesWithComponents([I]);for(const r of n){const n=e.get(r,I);n&&(n.aspectRatio=t,e.insert(r,I,n))}}class je{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 Xe{constructor(e){this.textureCache_=new je,this.shaderCache_=new je,this.jsonCache_=new je,this.textCache_=new je,this.binaryCache_=new je,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.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 De(t)}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),o=await fetch(s);if(!o.ok)return{success:!1,error:`Failed to fetch atlas: ${s}`};const i=await o.text();if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const a=t.substring(0,t.lastIndexOf("/")),c=this.parseAtlasTextures(i);for(const e of c){const t=a?`${a}/${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 l=this.resolveUrl(e,n),u=await fetch(l);if(!u.ok)return{success:!1,error:`Failed to fetch skeleton: ${l}`};const h=e.endsWith(".skel")?new Uint8Array(await u.arrayBuffer()):await u.text();return this.writeToVirtualFS(e,h)?(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 He(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){return new Promise((t,n)=>{const r=new Image;r.crossOrigin="anonymous",r.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(r,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void t(e)}catch{}t(r)},r.onerror=()=>n(new Error(`Failed to load image: ${e}`)),r.src=e})}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 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,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_.save(),r&&(this.ctx_.translate(0,n),this.ctx_.scale(1,-1)),this.ctx_.drawImage(e,0,0),this.ctx_.restore();const s=this.ctx_.getImageData(0,0,t,n),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 c=i.createTexture(t,n,a,o.length,1);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){if(!await l(e))throw new Error(`Shader file not found: ${e}`);const t=await c(e);if(!t)throw new Error(`Failed to read shader file: ${e}`);const{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Fe.createShader(n,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}}async fetchJson(e){const t=await i(e);if(!t.ok)throw new Error(`Failed to fetch JSON: ${e} (${t.status})`);return t.json()}async fetchText(e){const t=await i(e);if(!t.ok)throw new Error(`Failed to fetch text: ${e} (${t.status})`);return t.text()}async fetchBinary(e){const t=await i(e);if(!t.ok)throw new Error(`Failed to fetch binary: ${e} (${t.status})`);return t.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 Ve=N(null,"Assets");class Ge{build(e){const t=e.wasmModule;t?e.insertResource(Ve,new Xe(t)):console.warn("AssetPlugin: No WASM module available")}}const Ye=new Ge;let Ke=null,qe=0,Je=0,Qe=0;const Ze=new Float32Array(256);function et(e){Ke=e,qe=Ke._malloc(64),Je=Ke._malloc(64),Qe=Ke._malloc(1024)}function tt(){Ke&&(qe&&(Ke._free(qe),qe=0),Je&&(Ke._free(Je),Je=0),Qe&&(Ke._free(Qe),Qe=0)),Ke=null}function nt(){if(!Ke)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Ke}const rt={x:1,y:1,z:1,w:1},st={begin(e){const t=nt();t.HEAPF32.set(e,qe/4),t.draw_begin(qe)},end(){nt().draw_end()},line(e,t,n,r=1){nt().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){nt().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){nt().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){nt().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){nt().draw_circleOutline(e.x,e.y,t,n.x,n.y,n.z,n.w,r,s)},texture(e,t,n,r=rt){nt().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=rt){nt().draw_textureRotated(e.x,e.y,t.x,t.y,n,r,s.x,s.y,s.z,s.w)},setLayer(e){nt().draw_setLayer(e)},setDepth(e){nt().draw_setDepth(e)},getDrawCallCount:()=>Ke?Ke.draw_getDrawCallCount():0,getPrimitiveCount:()=>Ke?Ke.draw_getPrimitiveCount():0,setBlendMode(e){nt().draw_setBlendMode(e)},setDepthTest(e){nt().draw_setDepthTest(e)},drawMesh(e,t,n){const r=nt();r.HEAPF32.set(n,Je/4),r.draw_mesh(e,t,Je)},drawMeshWithMaterial(e,t,n){const r=nt(),s=Fe.get(t);if(!s)return;if(st.setBlendMode(s.blendMode),st.setDepthTest(s.depthTest),0===s.uniforms.size)return void st.drawMesh(e,s.shader,n);r.HEAPF32.set(n,Je/4);let o=0,i=0;for(const[e,t]of s.uniforms){const n=it(e);if(!(n<0)){if(Ce(t))Ze[o++]=10,Ze[o++]=n,Ze[o++]=t.slot??i++,Ze[o++]=t.textureId;else if("number"==typeof t)Ze[o++]=1,Ze[o++]=n,Ze[o++]=t;else if(Array.isArray(t)){Ze[o++]=t.length,Ze[o++]=n;for(let e=0;e<t.length;e++)Ze[o++]=t[e]}else"w"in t?(Ze[o++]=4,Ze[o++]=n,Ze[o++]=t.x,Ze[o++]=t.y,Ze[o++]=t.z,Ze[o++]=t.w):"z"in t?(Ze[o++]=3,Ze[o++]=n,Ze[o++]=t.x,Ze[o++]=t.y,Ze[o++]=t.z):(Ze[o++]=2,Ze[o++]=n,Ze[o++]=t.x,Ze[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(r.HEAPF32.set(Ze.subarray(0,o),Qe/4),r.draw_meshWithUniforms(e,s.shader,Je,Qe,o)):r.draw_mesh(e,s.shader,Je)}},ot={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function it(e){return ot[e]??-1}var at;!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"}(at||(at={}));let ct=null,lt=0,ut=0,ht=0;function dt(e){ct=e,lt=ct._malloc(262144),ut=ct._malloc(65536),ht=ct._malloc(256)}function ft(){ct&&(lt&&ct._free(lt),ut&&ct._free(ut),ht&&ct._free(ht),lt=0,ut=0,ht=0),ct=null}function pt(){if(!ct)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ct}const _t={create(e){const t=pt(),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,lt/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,ht,s).set(o),t.geometry_init(n,lt,r,ht,s,e.dynamic??!1),e.indices){const r=e.indices.length;if(4*r>65536)throw new Error(`Index data too large: ${r} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,ut,r).set(e.indices),t.geometry_setIndices16(n,ut,r)}else{new Uint32Array(t.HEAPU8.buffer,ut,r).set(e.indices),t.geometry_setIndices32(n,ut,r)}}return n},updateVertices(e,t,n=0){const r=pt(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);r.HEAPF32.set(t,lt/4),r.geometry_updateVertices(e,lt,s,n)},release(e){e>0&&pt().geometry_release(e)},isValid:e=>!(!ct||e<=0)&&ct.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,r=t/2;return _t.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:at.Float2},{name:"a_texCoord",type:at.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,o=Math.cos(s)*e,i=Math.sin(s)*e,a=(Math.cos(s)+1)/2,c=(Math.sin(s)+1)/2;n.push(o,i,a,c)}for(let e=1;e<=t;e++)r.push(0,e,e+1);return _t.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:at.Float2},{name:"a_texCoord",type:at.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 o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),r=Math.max(r,o.x),s=Math.max(s,o.y);const o=[];for(const i of e){const e=(i.x-t)/(r-t),a=(i.y-n)/(s-n);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return _t.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:at.Float2},{name:"a_texCoord",type:at.Float2}],indices:new Uint16Array(i)})}};let mt=null;function gt(e){mt=e}function yt(){mt&&xt.isInitialized()&&xt.shutdown(),mt=null}function wt(){if(!mt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return mt}const xt={init:(e,t)=>wt().postprocess_init(e,t),shutdown(){wt().postprocess_shutdown()},resize(e,t){wt().postprocess_resize(e,t)},addPass:(e,t)=>wt().postprocess_addPass(e,t),removePass(e){wt().postprocess_removePass(e)},setEnabled(e,t){wt().postprocess_setPassEnabled(e,t)},isEnabled:e=>wt().postprocess_isPassEnabled(e),setUniform(e,t,n){wt().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){wt().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){wt().postprocess_begin()},end(){wt().postprocess_end()},getPassCount:()=>wt().postprocess_getPassCount(),isInitialized:()=>!!mt&&mt.postprocess_isInitialized(),setBypass(e){wt().postprocess_setBypass(e)},isBypassed:()=>!mt||mt.postprocess_isBypassed(),createBlur:()=>Fe.createShader(vt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>Fe.createShader(vt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Fe.createShader(vt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Fe.createShader(vt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},vt="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var St;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(St||(St={}));let Pt=null,Ct=0;function Tt(e){Pt=e,Ct=Pt._malloc(64)}function bt(){Pt&&Ct&&(Pt._free(Ct),Ct=0),Pt=null}const Mt={init(e,t){Pt?.renderer_init(e,t)},resize(e,t){Pt?.renderer_resize(e,t)},begin(e,t){Pt&&Ct&&(Pt.HEAPF32.set(e,Ct/4),Pt.renderer_begin(Ct,t??0))},flush(){Pt?.renderer_flush()},end(){Pt?.renderer_end()},submitSprites(e){Pt&&Pt.renderer_submitSprites(e._cpp)},submitSpine(e){Pt&&Pt.renderer_submitSpine?.(e._cpp)},setStage(e){Pt?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Pt?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Pt?.renderer_releaseTarget(e)},getTargetTexture:e=>Pt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Pt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,r){Pt?.renderer_setClearColor?.(e,t,n,r)},getStats:()=>Pt?{drawCalls:Pt.renderer_getDrawCalls(),triangles:Pt.renderer_getTriangles(),sprites:Pt.renderer_getSprites(),spine:Pt.renderer_getSpine?.()??0,meshes:Pt.renderer_getMeshes(),culled:Pt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,spine:0,meshes:0,culled:0}};let Rt=null;function Et(e){Rt=e}function At(){Rt=null}const Ut={enable(){Rt?.gl_enableErrorCheck(!0)},disable(){Rt?.gl_enableErrorCheck(!1)},check:e=>Rt?.gl_checkErrors(e)??0,diagnose(){Rt?.renderer_diagnose()}},Ft=new Map;function zt(e,t){Ft.set(e,t)}function It(e){Ft.delete(e)}function Bt(){Ft.clear()}class kt{constructor(){this.spineRenderer_=null}setSpineRenderer(e){this.spineRenderer_=e}render(e){const{registry:t,viewProjection:n,width:r,height:s,elapsed:o}=e;Mt.resize(r,s),xt.isInitialized()&&xt.getPassCount()>0&&!xt.isBypassed()&&xt.resize(r,s),Mt.begin(n),Mt.submitSprites(t),this.spineRenderer_?this.spineRenderer_(t,o):Mt.submitSpine(t),Mt.flush();const i=Ft;if(i.size>0){st.begin(n);const e=[];for(const[t,n]of i.entries())try{n(o)}catch(n){console.error(`[CustomDraw] callback '${t}' error:`,n),e.push(t)}st.end();for(const t of e)It(t)}Mt.end()}}class $t{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(ne.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ne.FixedPreUpdate),this.runSchedule(ne.FixedUpdate),this.runSchedule(ne.FixedPostUpdate);this.runSchedule(ne.PreUpdate),this.runSchedule(ne.Update),this.runSchedule(ne.PostUpdate),this.runSchedule(ne.Last),requestAnimationFrame(this.mainLoop)},this.world_=new pe,this.resources_=new G;for(const e of Object.values(ne))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new $t}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(ne.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(ne.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 le(this.world_,this.resources_),this.resources_.insert(Y,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(ne.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,At(),bt(),yt(),ft(),Ae(),tt()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(Y),n={delta:e,elapsed:t.elapsed+e,frameCount:t.frameCount+1};this.resources_.set(Y,n)}}function Lt(e,t){const n=$t.new(),r=new e.Registry;n.connectCpp(r,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),et(e),Ee(e),dt(e),gt(e),Tt(e),Et(e);const s=new kt;n.pipeline_=s;let o=d();const i=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}=i(),n=function(e,t,n){const r=e.entityCount()+1e3;for(let s=0;s<r;s++){if(!e.valid(s)||!e.hasCamera(s)||!e.hasLocalTransform(s))continue;const o=e.getCamera(s);if(!o.isActive)continue;const i=e.getLocalTransform(s),a=t/n;let c;if(1===o.projectionType){let t=o.orthoSize;const n=Ht(e,r);if(n){t=Ot(n.designResolution.y/2,n.designResolution.x/n.designResolution.y,a,n.scaleMode,n.matchWidthOrHeight)}const s=t*a;c=Nt(-s,s,-t,t,-o.farPlane,o.farPlane)}else c=jt(o.fov*Math.PI/180,a,o.nearPlane,o.farPlane);return Vt(c,Xt(i.position.x,i.position.y,i.position.z))}return Wt}(r,e,t),a=(d()-o)/1e3;s.render({registry:{_cpp:r},viewProjection:n,width:e,height:t,elapsed:a})}};return n.addSystemToSchedule(ne.Last,a),n.addPlugin(Ye),n.addPlugin(fe),n.addPlugin(Se),n}function Dt(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 Wt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ht(e,t){for(let n=0;n<t;n++){if(!e.valid(n)||!e.hasCanvas(n))continue;return e.getCanvas(n)}return null}function Ot(e,t,n,r,s){const o=e*t/n,i=e;switch(r){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=s;return Math.pow(o,1-e)*Math.pow(i,e)}}}function Nt(e,t,n,r,s,o){const i=new Float32Array(16),a=t-e,c=r-n,l=o-s;return i[0]=2/a,i[5]=2/c,i[10]=-2/l,i[12]=-(t+e)/a,i[13]=-(r+n)/c,i[14]=-(o+s)/l,i[15]=1,i}function jt(e,t,n,r){const s=new Float32Array(16),o=1/Math.tan(e/2),i=n-r;return s[0]=o/t,s[5]=o,s[10]=(r+n)/i,s[11]=-1,s[14]=2*r*n/i,s}function Xt(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 Vt(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}function Gt(e,t){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const s=n.createTexture(t.width,t.height,r,t.pixels.length,1);return e._free(r),s}function Yt(e,t){const n=t.substring(0,t.lastIndexOf("/"));n&&e.FS.mkdirTree(n)}function Kt(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}async function qt(e,t,n,r,s){const o=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]=Gt(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,o);let i={};s&&(i=await async function(e,t,n,r){const s={};for(const o of n.entities)for(const n of o.components){if("SpineAnimation"!==n.type||!n.data)continue;const o=n.data.skeletonPath,i=n.data.atlasPath;if(!o||!i)continue;const a=r.resolvePath(o),c=r.resolvePath(i);try{const n=r.readText(i),l=a.endsWith(".skel");Yt(t,a),l?t.FS.writeFile(a,r.readBinary(o)):t.FS.writeFile(a,r.readText(o));const u=t.spine_loadSkeleton(a,n,n.length,l);if(u<0)continue;s[o]=u;const h=Kt(n),d=c.substring(0,c.lastIndexOf("/"));for(let n=0;n<h.length;n++){const s=d+"/"+h[n];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=Gt(e,o),a=e.getResourceManager().getTextureGLId(i);t.spine_setAtlasPageTexture(u,n,a,o.width,o.height)}catch{}}}catch{}}return s}(t,s,n,r));const a=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 o=e.vertexSource+e.fragmentSource;let i=r[o];i||(i=Fe.createShader(e.vertexSource,e.fragmentSource),r[o]=i),n[s]=Fe.createFromAsset(e,i)}catch{n[s]=0}}return n}(n,r),c=We(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,z);s&&(s.texture=n[r.data.texture]||0,e.insert(t,z,s))}}}(e.world,n,o,c),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,z);n&&(n.material=s,e.insert(t,z,n))}else if("SpineAnimation"===r.type){const n=e.get(t,D);n&&(n.material=s,e.insert(t,D,n))}}}}(e.world,n,a,c),s){const r=function(e,t,n,r){const s={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.spine_createInstance(i);if(a<0)continue;const c=r.get(o.id);void 0!==c&&(s[c]=a),t.data.animation&&e.spine_playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.spine_setSkin(a,t.data.skin)}return s}(s,n,i,c);!function(e,t,n,r){let s=0;e.setSpineRenderer((e,o)=>{let i=o-s;s=o,(i<=0||i>.5)&&(i=1/60);for(const e in r){const s=r[e];n.spine_update(s,i);const o=n.spine_getMeshBatchCount(s);for(let e=0;e<o;e++){const r=n.spine_getMeshBatchVertexCount(s,e),o=n.spine_getMeshBatchIndexCount(s,e);if(!r||!o)continue;const i=8*r*4,a=2*o,c=n._malloc(i),l=n._malloc(a),u=n._malloc(4),h=n._malloc(4);n.spine_getMeshBatchData(s,e,c,l,u,h);const d=n.HEAPU32[u>>2],f=n.HEAPU32[h>>2],p=new Float32Array(n.HEAPF32.buffer,c,8*r),_=new Uint16Array(n.HEAPU8.buffer,l,o),m=t._malloc(i),g=t._malloc(a);t.HEAPF32.set(p,m>>2),new Uint16Array(t.HEAPU8.buffer,g,o).set(_),t.renderer_submitTriangles(m,r,g,o,d,f,0),t._free(m),t._free(g),n._free(c),n._free(l),n._free(u),n._free(h)}}})}(e,t,s,r)}}class Jt{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),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}}class Qt{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new Jt(this.baseUrl_);await n.prefetch(t);let r=null;const s=this.app_.__spineInitPromise;if(s){r=(await s).controller.module}await qt(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([I]);for(const r of n){if(e.get(r,I).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([B]);for(const s of r){const r=e.get(s,B);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(),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,U,o);const i={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0};e.insert(s,I,i)}}}const Zt={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Mt.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Mt.getTargetTexture(n),width:e.width,height:e.height}},release(e){Mt.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Mt.releaseRenderTarget(e._handle),Zt.create({width:t,height:n,depth:!0})),begin(e,t){Mt.begin(t,e._handle)},end(){Mt.end()},getDepthTexture:e=>Mt.getTargetDepthTexture(e._handle)};let en=!1;function tn(e){en=e}function nn(){return en}function rn(){return!en}var sn;e=sn=f,console.log(`[ESEngine] Platform: ${sn.name}`);export{$t as App,Ge as AssetPlugin,Xe as AssetServer,Ve as Assets,je as AsyncCache,Pe as BlendMode,I as Camera,B as Canvas,L as Children,Z as Commands,te as CommandsInstance,at as DataType,st as Draw,ee as EntityCommands,Ut as GLDebug,_t as Geometry,p as INVALID_ENTITY,_ as INVALID_TEXTURE,he as Input,de as InputPlugin,ue as InputState,U as LocalTransform,Fe as Material,De as MaterialLoader,K as Mut,$ as Parent,xt as PostProcess,Qt as PreviewPlugin,J as Query,Q as QueryInstance,kt as RenderPipeline,St as RenderStage,Zt as RenderTexture,Mt as Renderer,j as Res,X as ResMut,ne as Schedule,Le as ShaderSources,D as SpineAnimation,z as Sprite,le as SystemRunner,ye as Text,_e as TextAlign,ge as TextOverflow,ve as TextPlugin,we as TextRenderer,me as TextVerticalAlign,Y as Time,xe as UIRect,k as Velocity,Jt as WebAssetProvider,pe as World,F as WorldTransform,ae as addStartupSystem,ie as addSystem,ce as addSystemToSchedule,Ye as assetPlugin,Bt as clearDrawCallbacks,M as clearUserComponents,w as color,Lt as createWebApp,C as defineComponent,N as defineResource,se as defineSystem,T as defineTag,Dt as flushPendingSystems,H as getComponentDefaults,t as getPlatform,r as getPlatformType,b as getUserComponent,et as initDrawAPI,Et as initGLDebugAPI,dt as initGeometryAPI,Ee as initMaterialAPI,gt as initPostProcessAPI,Tt as initRendererAPI,fe as inputPlugin,A as isBuiltinComponent,nn as isEditor,n as isPlatformInitialized,rn as isRuntime,Ce as isTextureRef,s as isWeChat,o as isWeb,Oe as loadComponent,qt as loadRuntimeScene,We as loadSceneData,He as loadSceneWithAssets,i as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,x as quat,zt as registerDrawCallback,$e as registerMaterialCallback,tn as setEditorMode,tt as shutdownDrawAPI,At as shutdownGLDebugAPI,ft as shutdownGeometryAPI,Ae as shutdownMaterialAPI,yt as shutdownPostProcessAPI,bt as shutdownRendererAPI,Se as textPlugin,It as unregisterDrawCallback,Ne as updateCameraAspectRatio,m as vec2,g as vec3,y as vec4};//# sourceMappingURL=index.js.mapdiff --git a/desktop/public/sdk/esm/index.js.map b/desktop/public/sdk/esm/index.js.mapindex b94bb2208..058a7ffc9 100644--- a/desktop/public/sdk/esm/index.js.map+++ b/desktop/public/sdk/esm/index.js.map@@ -1 +1 @@-{"version":3,"file":"index.js","sources":["../src/platform/base.ts","../src/platform/web.ts","../src/types.ts","../src/component.ts","../src/resource.ts","../src/query.ts","../src/commands.ts","../src/system.ts","../src/world.ts","../src/ui/text.ts","../src/ui/TextRenderer.ts","../src/ui/UIRect.ts","../src/ui/TextPlugin.ts","../src/blend.ts","../src/material.ts","../src/draw.ts","../src/geometry.ts","../src/postprocess.ts","../src/renderer.ts","../src/app.ts","../src/asset/AssetServer.ts","../src/asset/AssetPlugin.ts","../src/scene.ts","../src/preview/PreviewPlugin.ts","../src/spine.ts","../src/index.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["module","viewProjectionPtr","getModule"],"mappings":"AAAA;;;AAGG;AAIH;AACA;AACA;AAEA,IAAI,eAAe,GAA2B,IAAI;AAElD;;AAEG;AACG,SAAU,WAAW,CAAC,OAAwB,EAAA;IAChD,eAAe,GAAG,OAAO;IACzB,OAAO,CAAC,GAAG,CAAC,CAAA,qBAAA,EAAwB,OAAO,CAAC,IAAI,CAAA,CAAE,CAAC;AACvD;AAEA;;;AAGG;SACa,WAAW,GAAA;IACvB,IAAI,CAAC,eAAe,EAAE;QAClB,MAAM,IAAI,KAAK,CACX,uCAAuC;AACvC,YAAA,uFAAuF,CAC1F;IACL;AACA,IAAA,OAAO,eAAe;AAC1B;AAEA;;AAEG;SACa,qBAAqB,GAAA;IACjC,OAAO,eAAe,KAAK,IAAI;AACnC;AAEA;;AAEG;SACa,eAAe,GAAA;AAC3B,IAAA,OAAO,eAAe,EAAE,IAAI,IAAI,IAAI;AACxC;AAEA;;AAEG;SACa,QAAQ,GAAA;AACpB,IAAA,OAAO,eAAe,EAAE,IAAI,KAAK,QAAQ;AAC7C;AAEA;;AAEG;SACa,KAAK,GAAA;AACjB,IAAA,OAAO,eAAe,EAAE,IAAI,KAAK,KAAK;AAC1C;AAEA;AACA;AACA;AAEO,eAAe,aAAa,CAC/B,GAAW,EACX,OAAkD,EAAA;IAElD,OAAO,WAAW,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,OAAO,CAAC;AAC5C;AAEO,eAAe,gBAAgB,CAAC,IAAY,EAAA;AAC/C,IAAA,OAAO,WAAW,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC;AACvC;AAEO,eAAe,oBAAoB,CAAC,IAAY,EAAA;AACnD,IAAA,OAAO,WAAW,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC;AAC3C;AAEO,eAAe,kBAAkB,CAAC,IAAY,EAAA;AACjD,IAAA,OAAO,WAAW,EAAE,CAAC,UAAU,CAAC,IAAI,CA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E,SAAS,CAAC,KAAK,IAAI,CAAC;AAC3B,YAAA,SAAS,EAAE,SAAS,CAAC,SAAS,IAAI,IAAI;YACtC,SAAS,EAAE,SAAS,CAAC,SAAS;YAC9B,QAAQ,EAAE,SAAS,CAAC,QAAQ;YAC5B,UAAU,EAAE,SAAS,CAAC,UAAU;YAChC,WAAW,EAAE,SAAS,CAAC,WAAW;SACrC;QAED,MAAM,aAAa,GAAG,eAAe,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC;QACrD,IAAI,aAAa,EAAE;AACf,YAAA,aAAa,CAAC,OAAO,CAAC,QAAQ,IAAG;AAC7B,gBAAA,IAAI;oBACA,QAAQ,CAAC,KAAK,CAAC;gBACnB;gBAAE,OAAO,CAAC,EAAE;AACR,oBAAA,OAAO,CAAC,KAAK,CAAC,gCAAgC,EAAE,CAAC,CAAC;gBACtD;AACJ,YAAA,CAAC,CAAC;QACN;IACJ;AACH;AAED;AACA;AACA;AAEA;;;;AAIG;AACG,SAAU,qBAAqB,CAAC,UAAe,EAAA;AACjD,IAAA,OAAO,IAAI,eAAe,CAAC,UAAU,CAAC;AAC1C;;AC7WA;;;AAGG;AAEH;AAEA,WAAW,CAAC,UAAU,CAAC;;;;"}\ No newline at end of file+{"version":3,"file":"index.js","sources":["../src/platform/base.ts","../src/platform/web.ts","../src/types.ts","../src/component.ts","../src/resource.ts","../src/query.ts","../src/commands.ts","../src/system.ts","../src/input.ts","../src/world.ts","../src/ui/text.ts","../src/ui/TextRenderer.ts","../src/ui/UIRect.ts","../src/ui/TextPlugin.ts","../src/blend.ts","../src/material.ts","../src/asset/MaterialLoader.ts","../src/scene.ts","../src/asset/AsyncCache.ts","../src/asset/AssetServer.ts","../src/asset/AssetPlugin.ts","../src/draw.ts","../src/geometry.ts","../src/postprocess.ts","../src/renderer.ts","../src/glDebug.ts","../src/customDraw.ts","../src/renderPipeline.ts","../src/app.ts","../src/runtimeLoader.ts","../src/preview/WebAssetProvider.ts","../src/preview/PreviewPlugin.ts","../src/renderTexture.ts","../src/env.ts","../src/index.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["currentPlatform","getPlatform","Error","isPlatformInitialized","getPlatformType","name","isWeChat","isWeb","async","platformFetch","url","options","fetch","platformReadFile","path","readFile","platformReadTextFile","readTextFile","platformFileExists","fileExists","platformInstantiateWasm","pathOrBuffer","imports","instantiateWasm","platformCreateCanvas","width","height","createCanvas","platformNow","now","webAdapter","constructor","this","response","globalThis","method","headers","body","forEach","value","key","ok","status","statusText","json","text","arrayBuffer","buffer","result","WebAssembly","instantiate","instance","module","canvas","OffscreenCanvas","document","createElement","performance","bindInputEvents","callbacks","target","el","querySelector","addEventListener","e","onKeyDown","code","onKeyUp","me","onPointerMove","offsetX","offsetY","onPointerDown","button","onPointerUp","touch","touches","rect","getBoundingClientRect","clientX","left","clientY","top","we","onWheel","deltaX","deltaY","INVALID_ENTITY","INVALID_TEXTURE","vec2","x","y","vec3","z","vec4","w","color","r","g","b","a","quat","componentCounter","createComponentDef","defaults","id","_id","Symbol","_name","_default","_builtin","create","data","getComponentRegistry","window","Map","__esengine_componentRegistry","defineComponent","registry","existing","get","def","set","registerToEditor","defineTag","getUserComponent","clearUserComponents","clear","isTag","__esengine_registerComponent","defineBuiltin","_cppName","isBuiltinComponent","comp","LocalTransform","position","rotation","scale","WorldTransform","Sprite","texture","size","uvOffset","uvScale","layer","flipX","flipY","material","Camera","projectionType","fov","orthoSize","nearPlane","farPlane","aspectRatio","isActive","priority","showFrustum","Canvas","designResolution","pixelsPerUnit","scaleMode","matchWidthOrHeight","backgroundColor","Velocity","linear","angular","Parent","entity","Children","entities","SpineAnimation","skeletonPath","atlasPath","skin","animation","timeScale","loop","playing","skeletonScale","builtinComponents","getComponentDefaults","typeName","builtin","userComp","resourceCounter","defineResource","defaultValue","Res","resource","_type","_resource","ResMut","ResMutInstance","setter","value_","setter_","modify","fn","ResourceStorage","resources_","insert","has","remove","delete","getResMut","v","Time","delta","elapsed","frameCount","Mut","component","_component","isMutWrapper","Query","components","withFilters","withoutFilters","mutIndices","i","push","_components","_mutIndices","_with","_without","createQueryDescriptor","QueryInstance","world","descriptor","pendingMutations_","world_","descriptor_","getActualComponent","arg","commitPending","mutation","iterator","actualComponents","map","c","allRequired","getEntitiesWithComponents","prevEntity","prevMutData","mut","excluded","idx","callback","single","isEmpty","count","n","_","toArray","Commands","EntityCommands","commands","components_","commands_","entityRef_","isNew_","queueInsert","queueRemove","finalize","spawnImmediate","CommandsInstance","resources","pending_","spawn","despawn","type","insertResource","entityRef","entry","flush","cmd","executeCommand","Schedule","systemCounter","defineSystem","params","_params","_fn","getPendingSystems","__esengine_pendingSystems","addSystem","system","schedule","Update","addStartupSystem","Startup","addSystemToSchedule","SystemRunner","run","args","param","resolveParam","InputState","keysDown","Set","keysPressed","keysReleased","mouseX","mouseY","mouseButtons","mouseButtonsPressed","mouseButtonsReleased","scrollDeltaX","scrollDeltaY","isKeyDown","isKeyPressed","isKeyReleased","getMousePosition","isMouseButtonDown","isMouseButtonPressed","isMouseButtonReleased","getScrollDelta","Input","InputPlugin","target_","build","app","state","add","undefined","First","inputPlugin","World","cppRegistry_","entities_","tsStorage_","connectCpp","cppRegistry","hasCpp","destroy","storage","values","valid","entityCount","getAllEntities","Array","from","setParent","child","parent","removeParent","insertBuiltin","insertScript","getBuiltin","getScript","hasBuiltin","hasScript","removeBuiltin","removeScript","merged","adder","call","getter","checker","remover","getStorage","length","hasAll","TextAlign","TextVerticalAlign","TextOverflow","Text","content","fontFamily","fontSize","align","Left","verticalAlign","Top","wordWrap","overflow","Visible","lineHeight","dirty","TextRenderer","cache","ctx","getContext","willReadFrequently","renderText","uiRect","font","hasContainer","containerWidth","containerHeight","shouldWrap","lines","wrapText","lineHeightPx","Math","ceil","padding","measuredWidth","measureWidth","measuredHeight","Ellipsis","maxLines","floor","slice","lastLine","truncateWithEllipsis","newWidth","max","nextPowerOf2","newHeight","round","clearRect","textAlign","mapAlign","textBaseline","fillStyle","Clip","save","beginPath","clip","textBlockHeight","startY","Middle","Bottom","line","Center","Right","fillText","restore","imageData","getImageData","pixels","Uint8Array","flipped","flipVertically","rm","getResourceManager","ptr","_malloc","HEAPU8","textureHandle","createTexture","_free","maxWidth","measureText","truncated","renderForEntity","releaseTexture","getCached","release","cached","releaseAll","split","paragraphs","paragraph","currentLine","char","testLine","metrics","actualBoundingBoxLeft","actualBoundingBoxRight","p","rowSize","srcOffset","dstOffset","subarray","UIRect","anchor","pivot","TextPlugin","wasmModule","console","warn","renderer","PreUpdate","flip","sprite","textPlugin","BlendMode","isTextureRef","resourceManager","nextMaterialId","materials","initMaterialAPI","registerMaterialCallback","shutdownMaterialAPI","uniformBuffer","materialCallbackRegistered","Material","createShader","vertexSrc","fragmentSrc","releaseShader","shader","handle","uniforms","blendMode","Normal","depthTest","Object","entries","setUniform","getUniform","setBlendMode","mode","getBlendMode","setDepthTest","enabled","getShader","isValid","createFromAsset","shaderHandle","properties","obj","createInstance","source","sourceData","toAssetData","shaderPath","version","getUniforms","tex","textureId","slot","__textureRef","UNIFORM_BUFFER_SIZE","serializeUniforms","bufferPtr","offset","heap8","heap32","HEAPU32","heapF32","HEAPF32","nameBytes","TextEncoder","encode","nameLen","namePadded","isArray","min","materialDataProvider","materialId","outShaderIdPtr","outBlendModePtr","outUniformBufferPtr","outUniformCountPtr","ShaderSources","SPRITE_VERTEX","SPRITE_FRAGMENT","COLOR_VERTEX","COLOR_FRAGMENT","MaterialLoader","shaderLoader","basePath","cache_","shaderLoader_","basePath_","load","pending","promise","loadInternal","loaded","fullPath","resolvePath","JSON","parse","resolveShaderPath","startsWith","materialPath","dir","substring","lastIndexOf","loadSceneData","sceneData","entityMap","entityData","compData","loadComponent","parentEntity","loadSceneWithAssets","assetServer","texturePathToUrl","texturePath","assetBaseUrl","info","loadTexture","err","loadMaterial","loadSpine","success","error","textureMetadata","metadata","sliceBorder","setTextureMetadataByPath","updateCameraAspectRatio","cameraEntities","camera","AsyncCache","getOrLoad","loader","AssetServer","textureCache_","shaderCache_","jsonCache_","textCache_","binaryCache_","loadedSpines_","virtualFSPaths_","module_","canvas_","ctx_","loadShader","materialLoader_","loadTextureWithFlip","loadTextureRaw","getTexture","textureCacheKey","hasTexture","setTextureMetadata","border","right","bottom","baseUrl","cacheKey","atlasUrl","resolveUrl","atlasResponse","atlasContent","writeToVirtualFS","atlasDir","textureNames","parseAtlasTextures","texName","texPath","texUrl","registerTextureWithPath","skelUrl","skelResponse","skelData","endsWith","String","isSpineLoaded","getMaterial","hasMaterial","loadShaderInternal","loadJson","noCache","fetchJson","loadText","fetchText","loadBinary","fetchBinary","loadScene","loadAll","manifest","bundle","textures","spine","binary","promises","then","mat","desc","skeleton","atlas","Promise","all","loadTextureInternal","img","loadImage","createTextureFromImage","resolve","reject","Image","crossOrigin","onload","createImageBitmap","bitmap","premultiplyAlpha","colorSpaceConversion","onerror","src","gl","getWebGL2Context","createTextureWebGL2","createTextureFallback","glObj","GL","currentContext","GLctx","WebGL2RenderingContext","bindTexture","TEXTURE_2D","pixelStorei","UNPACK_FLIP_Y_WEBGL","UNPACK_PREMULTIPLY_ALPHA_WEBGL","texImage2D","RGBA","UNSIGNED_BYTE","texParameteri","TEXTURE_MIN_FILTER","LINEAR","TEXTURE_MAG_FILTER","TEXTURE_WRAP_S","REPEAT","TEXTURE_WRAP_T","generateMipmap","glTextureId","getNewId","registerExternalTexture","translate","drawImage","unpremultiplyAlpha","vertex","fragment","parseEsShader","vertexMatch","match","fragmentMatch","trim","virtualPath","fs","FS","ensureVirtualDir","writeFile","parts","filter","currentPath","part","analyzePath","exists","mkdir","base","trimmed","includes","Assets","AssetPlugin","assetPlugin","viewProjectionPtr","transformPtr","uniformsPtr","Float32Array","initDrawAPI","UNIFORMS_BUFFER_SIZE","shutdownDrawAPI","getModule","WHITE","Draw","begin","viewProjection","m","draw_begin","end","draw_end","to","thickness","draw_line","filled","draw_rect","rectOutline","draw_rectOutline","circle","center","radius","segments","draw_circle","circleOutline","draw_circleOutline","tint","draw_texture","textureRotated","draw_textureRotated","setLayer","draw_setLayer","setDepth","depth","draw_setDepth","getDrawCallCount","draw_getDrawCallCount","getPrimitiveCount","draw_getPrimitiveCount","draw_setBlendMode","draw_setDepthTest","drawMesh","geometry","transform","draw_mesh","drawMeshWithMaterial","matData","autoTextureSlot","nameId","getUniformNameId","draw_meshWithUniforms","UNIFORM_NAME_MAP","u_time","u_color","u_intensity","u_scale","u_offset","u_param0","u_param1","u_param2","u_param3","u_param4","u_vec0","u_vec1","u_vec2","u_vec3","u_texture0","u_texture1","u_texture2","u_texture3","DataType","vertexPtr","indexPtr","layoutPtr","initGeometryAPI","VERTEX_BUFFER_SIZE","INDEX_BUFFER_SIZE","LAYOUT_BUFFER_SIZE","shutdownGeometryAPI","Geometry","geometry_create","vertexCount","vertices","layoutCount","layout","layoutArray","Int32Array","geometry_init","dynamic","indices","indexCount","Uint16Array","geometry_setIndices16","Uint32Array","geometry_setIndices32","updateVertices","geometry_updateVertices","geometry_release","geometry_isValid","createQuad","hw","hh","Float2","createCircle","angle","PI","cos","sin","u","createPolygon","points","minX","Infinity","minY","maxX","maxY","initPostProcessAPI","shutdownPostProcessAPI","PostProcess","isInitialized","shutdown","init","postprocess_init","postprocess_shutdown","resize","postprocess_resize","addPass","postprocess_addPass","removePass","postprocess_removePass","setEnabled","postprocess_setPassEnabled","isEnabled","postprocess_isPassEnabled","passName","uniform","postprocess_setUniformFloat","setUniformVec4","postprocess_setUniformVec4","postprocess_begin","postprocess_end","getPassCount","postprocess_getPassCount","postprocess_isInitialized","setBypass","bypass","postprocess_setBypass","isBypassed","postprocess_isBypassed","createBlur","POSTPROCESS_VERTEX","createVignette","createGrayscale","createChromaticAberration","RenderStage","initRendererAPI","shutdownRendererAPI","Renderer","renderer_init","renderer_resize","renderer_begin","renderer_flush","renderer_end","submitSprites","renderer_submitSprites","_cpp","submitSpine","renderer_submitSpine","setStage","stage","renderer_setStage","createRenderTarget","flags","renderer_createTarget","releaseRenderTarget","renderer_releaseTarget","getTargetTexture","renderer_getTargetTexture","getTargetDepthTexture","renderer_getTargetDepthTexture","setClearColor","renderer_setClearColor","getStats","drawCalls","renderer_getDrawCalls","triangles","renderer_getTriangles","sprites","renderer_getSprites","renderer_getSpine","meshes","renderer_getMeshes","culled","renderer_getCulled","initGLDebugAPI","shutdownGLDebugAPI","GLDebug","enable","gl_enableErrorCheck","disable","check","context","gl_checkErrors","diagnose","renderer_diagnose","registerDrawCallback","unregisterDrawCallback","clearDrawCallbacks","RenderPipeline","spineRenderer_","setSpineRenderer","render","cbs","failed","App","systems_","runner_","running_","lastTime_","fixedTimestep_","fixedAccumulator_","pipeline_","mainLoop","currentTime","deltaMs","updateTime","runSchedule","FixedPreUpdate","FixedUpdate","FixedPostUpdate","PostUpdate","Last","requestAnimationFrame","s","addPlugin","plugin","getResource","hasResource","quit","systems","time","newTime","createWebApp","new","Registry","glContextHandle","initRendererWithContext","initRenderer","pipeline","startTime","getViewportSize","innerWidth","devicePixelRatio","innerHeight","renderSystem","vp","scanLimit","hasCamera","hasLocalTransform","getCamera","getLocalTransform","aspect","projection","halfH","findCanvasData","computeEffectiveOrthoSize","halfW","ortho","perspective","multiply","invertTranslation","IDENTITY","computeViewProjection","flushPendingSystems","hasCanvas","getCanvas","baseOrthoSize","designAspect","actualAspect","orthoForWidth","orthoForHeight","t","pow","near","far","rl","tb","fovRad","f","tan","nf","j","createTextureFromPixels","ensureFSDir","mod","mkdirTree","test","loadRuntimeScene","provider","spineModule","textureCache","ref","loadPixels","loadTextures","applyTextureMetadata","spineSkeletons","skeletons","skelRef","atlasRef","skelPath","readText","isBinary","readBinary","skelHandle","spine_loadSkeleton","texNames","k","loadPixelsRaw","glId","getTextureGLId","spine_setAtlasPageTexture","loadSpineAssets","materialCache","shaderCache","matRef","vertexSource","fragmentSource","shaderKey","loadMaterials","updateSpriteTextures","updateMaterials","instances","instanceId","spine_createInstance","spine_playAnimation","spine_setSkin","createSpineInstances","lastElapsed","_registry","dt","spine_update","batchCount","spine_getMeshBatchCount","vertCount","spine_getMeshBatchVertexCount","idxCount","spine_getMeshBatchIndexCount","vertBytes","idxBytes","vertPtr","idxPtr","texIdPtr","blendPtr","spine_getMeshBatchData","texId","srcVerts","srcIdx","coreVertPtr","coreIdxPtr","renderer_submitTriangles","setupSpineRenderer","WebAssetProvider","baseUrl_","prefetch","textRefs","binaryRefs","fetches","catch","buf","resp","blob","close","PreviewPlugin","sceneUrl","app_","loadPromise_","sceneUrl_","waitForReady","spinePromise","__spineInitPromise","controller","ensureCamera","hasActiveCamera","canvasEntities","ppu","cameraEntity","transformData","cameraData","RenderTexture","_handle","rt","getDepthTexture","editorMode","setEditorMode","active","isEditor","isRuntime","adapter","log"],"mappings":"AAWA,IAAIA,EAA0C,cAc9BC,IACZ,IAAKD,EACD,MAAM,IAAIE,MACN,8HAIR,OAAOF,CACX,UAKgBG,IACZ,OAA2B,OAApBH,CACX,UAKgBI,IACZ,OAAOJ,GAAiBK,MAAQ,IACpC,UAKgBC,IACZ,MAAiC,WAA1BN,GAAiBK,IAC5B,UAKgBE,IACZ,MAAiC,QAA1BP,GAAiBK,IAC5B,CAMOG,eAAeC,EAClBC,EACAC,GAEA,OAAOV,IAAcW,MAAMF,EAAKC,EACpC,CAEOH,eAAeK,EAAiBC,GACnC,OAAOb,IAAcc,SAASD,EAClC,CAEON,eAAeQ,EAAqBF,GACvC,OAAOb,IAAcgB,aAAaH,EACtC,CAEON,eAAeU,EAAmBJ,GACrC,OAAOb,IAAckB,WAAWL,EACpC,CAEON,eAAeY,EAClBC,EACAC,GAEA,OAAOrB,IAAcsB,gBAAgBF,EAAcC,EACvD,CAEM,SAAUE,EAAqBC,EAAeC,GAChD,OAAOzB,IAAc0B,aAAaF,EAAOC,EAC7C,UAEgBE,IACZ,OAAO3B,IAAc4B,KACzB,CCmDO,MAAMC,EAAa,IArI1B,MAAA,WAAAC,GACaC,KAA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,GAASmB,iBAAiB1a,GAKxCtd,MAAOd,EAAQc,MACfC,OAAQf,EAAQe,OAExB,EAEA,OAAAwa,CAAQ6qB,GACJzO,GAASiB,oBAAoBwN,EAAGD,QACpC,EAEAzQ,OAAM,CAAC0Q,EAAyBtlC,EAAeC,KAC3C42B,GAASiB,oBAAoBwN,EAAGD,SACzBD,GAAc9/B,OAAO,CAAEtF,QAAOC,SAAQgvB,OAAO,KAGxD,KAAA3B,CAAMgY,EAAyB/X,GAC3BsJ,GAASvJ,MAAMC,EAAgB+X,EAAGD,QACtC,EAEA,GAAA3X,GACImJ,GAASnJ,KACb,EAEA6X,gBAAgBD,GACLzO,GAASqB,sBAAsBoN,EAAGD,UCnDjD,IAAIG,IAAa,EAEX,SAAUC,GAAcC,GAC1BF,GAAaE,CACjB,UAEgBC,KACZ,OAAOH,EACX,UAEgBI,KACZ,OAAQJ,EACZ,CjCIM,IAAsBK,GACxBtnC,EADwBsnC,GkCThBxlC,ElCWR0b,QAAQ+pB,IAAI,wBAAwBD,GAAQjnC"}\ No newline at end of filediff --git a/desktop/public/sdk/esm/spine/index.js.map b/desktop/public/sdk/esm/spine/index.js.mapnew file mode 100644index 000000000..696f8c6f3--- /dev/null+++ b/desktop/public/sdk/esm/spine/index.js.map@@ -0,0 +1 @@+{"version":3,"file":"index.js","sources":["../../src/resource.ts","../../src/spine/SpineModuleLoader.ts","../../src/spine/SpineController.ts","../../src/spine/SpinePlugin.ts"],"sourcesContent":[null,null,null,null],"names":["resourceCounter","defineResource","defaultValue","name","id","_id","Symbol","_name","_default","async","loadSpineModule","wasmUrl","factory","moduleFactory","import","default","delta","elapsed","frameCount","SpineModuleController","constructor","spineModule","this","module_","listeners_","Map","module","loadSkeleton","skelPath","atlasText","isBinary","spine_loadSkeleton","length","unloadSkeleton","handle","spine_unloadSkeleton","getAtlasPageCount","spine_getAtlasPageCount","getAtlasPageTextureName","pageIndex","spine_getAtlasPageTextureName","setAtlasPageTexture","textureId","width","height","spine_setAtlasPageTexture","createInstance","skeletonHandle","spine_createInstance","destroyInstance","instanceId","spine_destroyInstance","delete","play","animation","loop","track","spine_playAnimation","addAnimation","delay","spine_addAnimation","setSkin","skinName","spine_setSkin","update","dt","spine_update","getAnimations","json","spine_getAnimations","JSON","parse","getSkins","spine_getSkins","getBonePosition","boneName","xPtr","_malloc","yPtr","spine_getBonePosition","_free","x","HEAPF32","y","getBoneRotation","spine_getBoneRotation","getBounds","ptr","spine_getBounds","f32","base","result","extractMeshBatches","batchCount","spine_getMeshBatchCount","batches","metaPtr","texIdPtr","blendPtr","i","vertexCount","spine_getMeshBatchVertexCount","indexCount","spine_getMeshBatchIndexCount","vertBytes","idxBytes","vertPtr","idxPtr","spine_getMeshBatchData","vertices","Float32Array","buffer","indices","Uint16Array","HEAPU8","push","HEAPU32","blendMode","on","entity","type","callback","has","set","entityListeners","get","Set","add","off","typeListeners","removeAllListeners","SpineResource","SpinePlugin","wasmUrl_","factory_","build","app","coreModule","wasmModule","initPromise","then","controller","insertResource","__spineInitPromise","submitSpineMeshesToCore","transform","transformPtr","batch","byteLength","renderer_submitTriangles"],"mappings":"AAeA,IAAIA,EAAkB,EAEhB,SAAUC,EAAkBC,EAAiBC,GAC/C,MAAMC,IAAOJ,EACb,MAAO,CACHK,IAAKC,OAAO,YAAYF,KAAMD,GAAQ,MACtCI,MAAOJ,GAAQ,YAAYC,IAC3BI,SAAUN,EAElB,CCwBOO,eAAeC,EAClBC,EACAC,GAEA,GAAIA,EACA,OAAOA,IAIX,OAAOC,SADsBC,OAAiCH,IAAUI,UAE5E,CDkEoBd,EAAyB,CACzCe,MAAO,EACPC,QAAS,EACTC,WAAY,GACb,cEzGUC,EAIT,WAAAC,CAAYC,GACRC,KAAKC,QAAUF,EACfC,KAAKE,WAAa,IAAIC,GAC1B,CAEA,UAAIC,GACA,OAAOJ,KAAKC,OAChB,CAMA,YAAAI,CAAaC,EAAkBC,EAAmBC,GAC9C,OAAOR,KAAKC,QAAQQ,mBAAmBH,EAAU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KAAM,yBAEnEmI,EAIT,WAAAhH,CAAYT,EAAiBC,GACzBU,KAAK+G,SAAW1H,EAChBW,KAAKgH,SAAW1H,CACpB,CAEA,KAAA2H,CAAMC,GACF,MAAMC,EAAaD,EAAIE,WAEjBC,EAAcjI,EAAgBY,KAAK+G,SAAU/G,KAAKgH,UAAUM,KAC7DvH,IACG,MAAMwH,EAAa,IAAI1H,EAAsBE,GAE7C,OADAmH,EAAIM,eAAeX,EAAeU,GAC3B,CAAEA,aAAYJ,gBAI7BD,EAAIM,eAAeX,EAAe,MAEjCK,EAAYO,mBAAqBJ,CACtC,EAGE,SAAUK,EACZP,EACAI,EACA3F,EACA+F,GAEA,MAAMlD,EAAU8C,EAAWjD,mBAAmB1C,GAE9C,IAAIgG,EAAe,EACfD,IACAC,EAAeT,EAAW5D,QAAQ,IAClC4D,EAAWvD,QAAQyC,IAAIsB,EAAWC,GAAgB,IAGtD,IAAK,MAAMC,KAASpD,EAAS,CACzB,MAAMS,EAAY2C,EAAMtC,SAASuC,WAC3B3C,EAAW0C,EAAMnC,QAAQoC,WAEzB1C,EAAU+B,EAAW5D,QAAQ2B,GAC7BG,EAAS8B,EAAW5D,QAAQ4B,GAElCgC,EAAWvD,QAAQyC,IAAIwB,EAAMtC,SAAUH,GAAW,GAClD,IAAIO,YAAYwB,EAAWvB,OAAOH,OAAQJ,EAAQwC,EAAMnC,QAAQhF,QAC3D2F,IAAIwB,EAAMnC,SAEfyB,EAAWY,yBACP3C,EAASyC,EAAMtC,SAAS7E,OAAS,EACjC2E,EAAQwC,EAAMnC,QAAQhF,OACtBmH,EAAMzG,UAAWyG,EAAM9B,UACvB6B,GAGJT,EAAWzD,MAAM0B,GACjB+B,EAAWzD,MAAM2B,EACrB,CAEIuC,GACAT,EAAWzD,MAAMkE,EAEzB"}\ No newline at end of filediff --git a/desktop/src-tauri/src/preview_server.rs b/desktop/src-tauri/src/preview_server.rsindex 18ac7c4d3..4313c4a93 100644--- a/desktop/src-tauri/src/preview_server.rs+++ b/desktop/src-tauri/src/preview_server.rs@@ -16,6 +16,12 @@ const SDK_JS: &[u8] = include_bytes!("../../public/sdk/esm/esengine.js");const SDK_JS_MAP: &[u8] = include_bytes!("../../public/sdk/esm/index.js.map");const SDK_WASM_JS: &[u8] = include_bytes!("../../public/sdk/esm/wasm.js");const SDK_WASM_JS_MAP: &[u8] = include_bytes!("../../public/sdk/esm/wasm.js.map");+const SDK_SPINE_JS: &[u8] = include_bytes!("../../public/sdk/esm/spine/index.js");+const SDK_SPINE_JS_MAP: &[u8] = include_bytes!("../../public/sdk/esm/spine/index.js.map");+const SPINE38_JS: &[u8] = include_bytes!("../../public/wasm/spine38.js");+const SPINE38_WASM: &[u8] = include_bytes!("../../public/wasm/spine38.wasm");+const SPINE42_JS: &[u8] = include_bytes!("../../public/wasm/spine42.js");+const SPINE42_WASM: &[u8] = include_bytes!("../../public/wasm/spine42.wasm");// =============================================================================// Preview Server@@ -61,6 +67,12 @@ impl PreviewServer {"sdk/index.js.map" => serve_embedded(SDK_JS_MAP, "application/json"),"sdk/wasm.js" => serve_embedded(SDK_WASM_JS, "application/javascript"),"sdk/wasm.js.map" => serve_embedded(SDK_WASM_JS_MAP, "application/json"),+ "sdk/spine/index.js" => serve_embedded(SDK_SPINE_JS, "application/javascript"),+ "sdk/spine/index.js.map" => serve_embedded(SDK_SPINE_JS_MAP, "application/json"),+ "wasm/spine38.js" => serve_embedded(SPINE38_JS, "application/javascript"),+ "wasm/spine38.wasm" => serve_embedded(SPINE38_WASM, "application/wasm"),+ "wasm/spine42.js" => serve_embedded(SPINE42_JS, "application/javascript"),+ "wasm/spine42.wasm" => serve_embedded(SPINE42_WASM, "application/wasm"),_ => serve_project_file(&project_dir, path),};diff --git a/desktop/src-tauri/src/preview_template.html b/desktop/src-tauri/src/preview_template.htmlindex f7188b6fb..fec23b78a 100644--- a/desktop/src-tauri/src/preview_template.html+++ b/desktop/src-tauri/src/preview_template.html@@ -8,7 +8,8 @@{"imports": {"esengine": "/sdk/index.js",- "esengine/wasm": "/sdk/wasm.js"+ "esengine/wasm": "/sdk/wasm.js",+ "esengine/spine": "/sdk/spine/index.js"}}</script>@@ -73,6 +74,21 @@return { width: canvas.width, height: canvas.height };}+ const SPINE_WASM_MAP = {+ '3.8': '/wasm/spine38.js',+ '4.2': '/wasm/spine42.js',+ };++ function loadUmdScript(url) {+ return new Promise((resolve, reject) => {+ const script = document.createElement('script');+ script.src = url;+ script.onload = () => { resolve(); script.remove(); };+ script.onerror = () => { reject(new Error('Failed to load ' + url)); script.remove(); };+ document.head.appendChild(script);+ });+ }+async function loadPreview() {try {updateLoading('Loading WASM module...');@@ -82,6 +98,23 @@updateLoading('Loading SDK...');const sdk = await import('/sdk/index.js');+ let spinePlugin = null;+ try {+ const configResp = await fetch('/.esengine/preview/config.json');+ if (configResp.ok) {+ const config = await configResp.json();+ const spineUrl = config.spineVersion && SPINE_WASM_MAP[config.spineVersion];+ if (spineUrl) {+ updateLoading('Loading Spine ' + config.spineVersion + '...');+ await loadUmdScript(spineUrl);+ const { SpinePlugin } = await import('esengine/spine');+ spinePlugin = new SpinePlugin(spineUrl, window.ESSpineModule);+ }+ }+ } catch (e) {+ console.warn('Spine module load skipped:', e);+ }+try {await import('/.esengine/preview/user-scripts.js');} catch (e) {@@ -92,13 +125,15 @@setupCanvas();window.addEventListener('resize', () => setupCanvas());- const previewPlugin = new sdk.PreviewPlugin('/.esengine/preview/scene.json');+ const previewPlugin = new sdk.PreviewPlugin('/.esengine/preview/scene.json', '/');const app = sdk.createWebApp(Module, {getViewportSize: getCanvasViewportSize});sdk.flushPendingSystems(app);- app.addPlugin(sdk.assetPlugin);+ if (spinePlugin) {+ app.addPlugin(spinePlugin);+ }app.addPlugin(previewPlugin);await previewPlugin.waitForReady();diff --git a/editor/src/Editor.ts b/editor/src/Editor.tsindex 1208f32bc..d7032d406 100644--- a/editor/src/Editor.ts+++ b/editor/src/Editor.ts@@ -699,7 +699,7 @@ export class Editor {await this.scriptLoader_.compile();}const compiledScript = this.scriptLoader_?.getCompiledCode() ?? undefined;- await this.previewService_.startPreview(this.store_.scene, compiledScript);+ await this.previewService_.startPreview(this.store_.scene, compiledScript, this.spineVersion_);} catch (err) {console.error('Failed to start preview:', err);}diff --git a/editor/src/preview/PreviewService.ts b/editor/src/preview/PreviewService.tsindex f1b009c98..10bb1c191 100644--- a/editor/src/preview/PreviewService.ts+++ b/editor/src/preview/PreviewService.ts@@ -39,7 +39,7 @@ export class PreviewService {this.previewDir_ = `${this.projectDir_}/.esengine/preview`;}- async startPreview(scene: SceneData, compiledScript?: string): Promise<void> {+ async startPreview(scene: SceneData, compiledScript?: string, spineVersion?: string): Promise<void> {const fs = this.getNativeFS();const invoke = this.getTauriInvoke();@@ -49,7 +49,7 @@ export class PreviewService {}console.log('PreviewService: Preparing files in', this.previewDir_);- await this.preparePreviewFiles(fs, scene, compiledScript);+ await this.preparePreviewFiles(fs, scene, compiledScript, spineVersion);console.log('PreviewService: Files prepared');const port = await invoke('start_preview_server', {@@ -70,7 +70,8 @@ export class PreviewService {private async preparePreviewFiles(fs: NativeFS,scene: SceneData,- compiledScript?: string+ compiledScript?: string,+ spineVersion?: string,): Promise<void> {await this.ensureDirectory(fs, this.previewDir_);@@ -86,6 +87,9 @@ export class PreviewService {const scenePath = `${this.previewDir_}/scene.json`;await fs.writeFile(scenePath, JSON.stringify(sceneWithMetadata, null, 2));+ const configPath = `${this.previewDir_}/config.json`;+ await fs.writeFile(configPath, JSON.stringify({ spineVersion: spineVersion || null }));+if (compiledScript) {const scriptPath = `${this.previewDir_}/user-scripts.js`;await fs.writeFile(scriptPath, compiledScript);diff --git a/sdk/src/app.ts b/sdk/src/app.tsindex d12f3b084..09c88b7ef 100644--- a/sdk/src/app.ts+++ b/sdk/src/app.ts@@ -9,6 +9,7 @@ import { ResourceStorage, Time, TimeData, type ResourceDef } from './resource';import type { ESEngineModule, CppRegistry } from './wasm';import { textPlugin } from './ui/TextPlugin';import { inputPlugin } from './input';+import { assetPlugin } from './asset';import { initDrawAPI, shutdownDrawAPI } from './draw';import { initMaterialAPI, shutdownMaterialAPI } from './material';import { initGeometryAPI, shutdownGeometryAPI } from './geometry';@@ -282,6 +283,7 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): Aapp.addSystemToSchedule(Schedule.Last, renderSystem);+ app.addPlugin(assetPlugin);app.addPlugin(inputPlugin);app.addPlugin(textPlugin);diff --git a/sdk/src/core.ts b/sdk/src/core.tsindex 6e5ccdbd2..df1e734c2 100644--- a/sdk/src/core.ts+++ b/sdk/src/core.ts@@ -220,7 +220,7 @@ export {// Preview// =============================================================================-export { PreviewPlugin } from './preview';+export { PreviewPlugin, WebAssetProvider } from './preview';// =============================================================================// Platform (base functions only)diff --git a/sdk/src/preview/PreviewPlugin.ts b/sdk/src/preview/PreviewPlugin.tsindex 3362356e9..1d05b1e65 100644--- a/sdk/src/preview/PreviewPlugin.ts+++ b/sdk/src/preview/PreviewPlugin.ts@@ -4,10 +4,11 @@*/import type { App, Plugin } from '../app';-import { Assets, assetPlugin } from '../asset';import type { SceneData } from '../scene';+import { loadRuntimeScene } from '../runtimeLoader';import { LocalTransform, Camera, Canvas, type LocalTransformData, type CameraData, type CanvasData } from '../component';import { platformFetch } from '../platform';+import { WebAssetProvider } from './WebAssetProvider';// =============================================================================// PreviewPlugin@@ -15,20 +16,18 @@ import { platformFetch } from '../platform';export class PreviewPlugin implements Plugin {private sceneUrl_: string;+ private baseUrl_: string;private app_: App | null = null;private loadPromise_: Promise<void> | null = null;- constructor(sceneUrl: string) {+ constructor(sceneUrl: string, baseUrl?: string) {this.sceneUrl_ = sceneUrl;+ this.baseUrl_ = baseUrl ?? '';}build(app: App): void {this.app_ = app;- if (!app.hasResource(Assets)) {- app.addPlugin(assetPlugin);- }-this.loadPromise_ = this.loadScene();}@@ -51,9 +50,17 @@ export class PreviewPlugin implements Plugin {}const sceneData = await response.json<SceneData>();- const assets = this.app_.getResource(Assets);- await assets.loadScene(this.app_.world, sceneData);+ const provider = new WebAssetProvider(this.baseUrl_);+ await provider.prefetch(sceneData);++ let spineModule = null;+ const spinePromise = (this.app_ as any).__spineInitPromise;+ if (spinePromise) {+ const result = await spinePromise;+ spineModule = result.controller.module;+ }+ await loadRuntimeScene(this.app_, this.app_.wasmModule!, sceneData, provider, spineModule);this.ensureCamera();} catch (err) {console.error('[PreviewPlugin] Failed to load scene:', err);diff --git a/sdk/src/preview/WebAssetProvider.ts b/sdk/src/preview/WebAssetProvider.tsnew file mode 100644index 000000000..d31dd973e--- /dev/null+++ b/sdk/src/preview/WebAssetProvider.ts@@ -0,0 +1,105 @@+/**+ * @file WebAssetProvider.ts+ * @brief RuntimeAssetProvider for browser-based preview+ */++import type { RuntimeAssetProvider } from '../runtimeLoader';+import type { SceneData } from '../scene';++export class WebAssetProvider implements RuntimeAssetProvider {+ private textCache_ = new Map<string, string>();+ private binaryCache_ = new Map<string, Uint8Array>();+ private baseUrl_: string;++ constructor(baseUrl: string) {+ this.baseUrl_ = baseUrl.endsWith('/') ? baseUrl : baseUrl + '/';+ }++ async prefetch(sceneData: SceneData): Promise<void> {+ const textRefs = new Set<string>();+ const binaryRefs = new Set<string>();++ for (const entity of sceneData.entities) {+ for (const comp of entity.components) {+ if (!comp.data) continue;+ if (comp.type === 'SpineAnimation') {+ const skelPath = comp.data.skeletonPath as string;+ const atlasPath = comp.data.atlasPath as string;+ if (skelPath) {+ if (skelPath.endsWith('.skel')) {+ binaryRefs.add(skelPath);+ } else {+ textRefs.add(skelPath);+ }+ }+ if (atlasPath) textRefs.add(atlasPath);+ }+ if (typeof comp.data.material === 'string' && comp.data.material) {+ textRefs.add(comp.data.material);+ }+ }+ }++ const fetches: Promise<void>[] = [];++ for (const ref of textRefs) {+ fetches.push(+ fetch(this.resolveUrl(ref))+ .then(r => r.text())+ .then(text => { this.textCache_.set(ref, text); })+ .catch(() => {})+ );+ }++ for (const ref of binaryRefs) {+ fetches.push(+ fetch(this.resolveUrl(ref))+ .then(r => r.arrayBuffer())+ .then(buf => { this.binaryCache_.set(ref, new Uint8Array(buf)); })+ .catch(() => {})+ );+ }++ await Promise.all(fetches);+ }++ readText(ref: string): string {+ const cached = this.textCache_.get(ref);+ if (cached !== undefined) return cached;+ throw new Error('Asset not prefetched: ' + ref);+ }++ readBinary(ref: string): Uint8Array {+ const cached = this.binaryCache_.get(ref);+ if (cached !== undefined) return cached;+ throw new Error('Asset not prefetched: ' + ref);+ }++ async loadPixels(ref: string): Promise<{ width: number; height: number; pixels: Uint8Array }> {+ const url = this.resolveUrl(ref);+ const resp = await fetch(url);+ const blob = await resp.blob();+ const bitmap = await createImageBitmap(blob);+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);+ const ctx = canvas.getContext('2d')!;+ ctx.drawImage(bitmap, 0, 0);+ const imageData = ctx.getImageData(0, 0, bitmap.width, bitmap.height);+ bitmap.close();+ return {+ width: imageData.width,+ height: imageData.height,+ pixels: new Uint8Array(imageData.data.buffer),+ };+ }++ resolvePath(ref: string): string {+ return ref;+ }++ private resolveUrl(ref: string): string {+ if (ref.startsWith('http://') || ref.startsWith('https://') || ref.startsWith('/')) {+ return ref;+ }+ return this.baseUrl_ + ref;+ }+}diff --git a/sdk/src/preview/index.ts b/sdk/src/preview/index.tsindex b52383443..e19188560 100644--- a/sdk/src/preview/index.ts+++ b/sdk/src/preview/index.ts@@ -4,3 +4,4 @@*/export { PreviewPlugin } from './PreviewPlugin';+export { WebAssetProvider } from './WebAssetProvider';diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.tsindex 3a758546c..bae4954f2 100644--- a/sdk/src/runtimeLoader.ts+++ b/sdk/src/runtimeLoader.ts@@ -161,8 +161,9 @@ async function loadSpineAssets(for (let k = 0; k < texNames.length; k++) {const texPath = atlasDir + '/' + texNames[k];try {- const loadFn = provider.loadPixelsRaw ?? provider.loadPixels;- const result = await loadFn(texPath);+ const result = provider.loadPixelsRaw+ ? await provider.loadPixelsRaw(texPath)+ : await provider.loadPixels(texPath);const handle = createTextureFromPixels(module, result);const rm = module.getResourceManager();const glId = rm.getTextureGLId(handle);@@ -214,8 +215,6 @@ function setupSpineRenderer(spineModule: SpineWasmModule,instances: Record<number, number>,): void {- if (Object.keys(instances).length === 0) return;-let lastElapsed = 0;app.setSpineRenderer((_registry: unknown, elapsed: number) => {let dt = elapsed - lastElapsed;