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
feat: refactor builder to emitter pattern, add UI interaction system and importer pipeline
esenginee76b1aa0160f
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.jsindex 18b410013..bedf5e202 100644--- a/desktop/public/sdk/cjs/esengine.wechat.js+++ b/desktop/public/sdk/cjs/esengine.wechat.js@@ -1,2 +1,2 @@-"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function r(e,r){return t().fetch(e,r)}async function s(e){return t().readFile(e)}async function n(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,r){return t().createCanvas(e,r)}function a(){return t().now()}function l(e,t){return new Promise((r,s)=>{const n=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===n?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];r({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,r="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(r).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function c(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const r=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(r,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${r}": ${t}`)}}let u=null;function h(){return u||(u=wx.getFileSystemManager()),u}function d(e){return new Promise((t,r)=>{h().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function p(e,t="utf-8"){return new Promise((r,s)=>{h().readFile({filePath:e,encoding:t,success:e=>{r(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function f(e){return new Promise(t=>{h().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}let m=null,_=null;function g(e){return new Promise((t,r)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>r(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function x(e){const{width:t,height:r}=e,{ctx:s}=function(e,t){return m||(m=wx.createCanvas(),m.width=e,m.height=t,_=m.getContext("2d")),(m.width<e||m.height<t)&&(m.width=Math.max(m.width,e),m.height=Math.max(m.height,t)),{canvas:m,ctx:_}}(t,r);s.clearRect(0,0,t,r),s.drawImage(e,0,0);const n=s.getImageData(0,0,t,r);return{width:t,height:r,pixels:new Uint8Array(n.data.buffer)}}let y=!1;const w=new class{constructor(){this.name="wechat"}async fetch(e,t){return l(e,t)}async readFile(e){return d(e)}async readTextFile(e){return p(e)}async fileExists(e){return f(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return c(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const r=wx.createCanvas();return r.width=e,r.height=t,r}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{const r=t.touches[0];r&&e.onPointerDown(0,r.clientX,r.clientY)}),wx.onTouchMove(t=>{const r=t.touches[0];r&&e.onPointerMove(r.clientX,r.clientY)}),wx.onTouchEnd(()=>{e.onPointerUp(0)})}},v=4294967295;function b(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const P=b("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),S=b("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),C=b("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),T=b("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),A={Static:0,Kinematic:1,Dynamic:2};let E=0;function M(e,t){const r=++E;return{_id:Symbol(`Component_${r}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function R(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function F(e,t){const r=R(),s=r.get(e);if(s)return s;const n=M(e,t);return r.set(e,n),U(e,t,!1),n}function B(e){return R().get(e)}function U(e,t,r){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,r)}function I(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function D(e){return!0===e._builtin}const k=I("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),W=I("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),z=I("Sprite",{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),$=I("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),L=I("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),H=I("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),O=I("Parent",{entity:0}),N=I("Children",{entities:[]}),V=I("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:0}),j=I("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),G={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},X={LocalTransform:k,WorldTransform:W,Sprite:z,Camera:$,Canvas:L,Velocity:H,Parent:O,Children:N,BitmapText:V,SpineAnimation:j,RigidBody:P,BoxCollider:S,CircleCollider:C,CapsuleCollider:T};let Y=0;function q(e,t){const r=++Y;return{_id:Symbol(`Resource_${r}_${t??""}`),_name:t??`Resource_${r}`,_default:e}}function K(e){return{_type:"res",_resource:e}}class J{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}}class Q{constructor(){this.resources_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id)}getResMut(e){return new J(this.get(e),t=>this.set(e,t))}}const Z=q({delta:0,elapsed:0,frameCount:0},"Time");function ee(e){return"object"==typeof e&&null!==e&&"mut"===e._type}class te{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>ee(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with)}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,r=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),n=r.length,o=e.length>0,i=t.length>0,a=new Array(n+1);let l=null,c=[];try{for(const u of s){if(null!==l&&o){for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}c.length=0}if(i){let e=!1;for(let r=0;r<t.length;r++)if(this.world_.has(u,t[r])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<n;e++)a[e+1]=this.world_.get(u,r[e]);if(o){for(let t=0;t<e.length;t++){const s=e[t];c.push({component:r[s],data:a[s+1]})}l=u}yield a}}finally{if(null!==l&&o)for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}}}forEach(e){for(const[t,...r]of this)e(t,...r)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class re{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let r;return r=D(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:r}):this.commands_.queueInsert(this.entityRef_.entity,e,r),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class se{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new re(this,null);return this.spawned_.push(e),e}entity(e){return new re(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,r){this.pending_.push({type:"insert",entity:e,component:t,data:r})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const r=this.world_.spawn();t.entity=r;for(const t of e)this.world_.insert(r,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const r of e.components)this.world_.insert(t,r.component,r.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var ne;exports.Schedule=void 0,(ne=exports.Schedule||(exports.Schedule={}))[ne.Startup=0]="Startup",ne[ne.First=1]="First",ne[ne.PreUpdate=2]="PreUpdate",ne[ne.Update=3]="Update",ne[ne.PostUpdate=4]="PostUpdate",ne[ne.Last=5]="Last",ne[ne.FixedPreUpdate=10]="FixedPreUpdate",ne[ne.FixedUpdate=11]="FixedUpdate",ne[ne.FixedPostUpdate=12]="FixedPostUpdate";let oe=0;function ie(e,t,r){const s=++oe;return{_id:Symbol(`System_${s}_${r?.name??""}`),_params:e,_fn:t,_name:r?.name??`System_${s}`}}function ae(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class le{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let r=0;r<e._params.length;r++)t[r]=this.resolveParam(e._params[r]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof se&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new te(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new se(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class ce{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const ue=q(new ce,"Input");class he{constructor(e){this.target_=e??null}build(e){const r=new ce;e.insertResource(ue,r),t().bindInputEvents({onKeyDown(e){r.keysDown.has(e)||r.keysPressed.add(e),r.keysDown.add(e)},onKeyUp(e){r.keysDown.delete(e),r.keysReleased.add(e)},onPointerMove(e,t){r.mouseX=e,r.mouseY=t},onPointerDown(e,t,s){r.mouseX=t,r.mouseY=s,r.mouseButtons.add(e),r.mouseButtonsPressed.add(e)},onPointerUp(e){r.mouseButtons.delete(e),r.mouseButtonsReleased.add(e)},onWheel(e,t){r.scrollDeltaX+=e,r.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.First,ie([],()=>{r.keysPressed.clear(),r.keysReleased.clear(),r.mouseButtonsPressed.clear(),r.mouseButtonsReleased.clear(),r.scrollDeltaX=0,r.scrollDeltaY=0},{name:"InputClearSystem"}))}}const de=new he;function pe(e){if(null==e||"object"!=typeof e||Array.isArray(e))return e;const t=e;if("r"in t&&"g"in t&&"b"in t&&"a"in t&&!("x"in t))return{x:t.r,y:t.g,z:t.b,w:t.a};const r={};for(const e of Object.keys(t)){const s=t[e];r[e]=null==s||"object"!=typeof s||Array.isArray(s)?s:pe(s)}return r}class fe{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,r){return D(t)?this.insertBuiltin(e,t,r):this.insertScript(e,t,r)}get(e,t){return D(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return D(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){D(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,r){const s={...t._default,...r};if(this.cppRegistry_){const r=`add${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e,pe(s))}return s}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const r=`get${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const r=`has${t._cppName}`;return this.cppRegistry_[r].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const r=`remove${t._cppName}`;this.cppRegistry_[r].call(this.cppRegistry_,e)}insertScript(e,t,r){const s=t.create(r);return this.getStorage(t).set(e,s),s}getScript(e,t){const r=this.tsStorage_.get(t._id);if(!r)throw new Error(`Component not found: ${t._name}`);return r.get(e)}hasScript(e,t){const r=this.tsStorage_.get(t._id);return r?.has(e)??!1}removeScript(e,t){const r=this.tsStorage_.get(t._id);r?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();let t=null,r=1/0;for(const s of e)if(!D(s)){const e=this.tsStorage_.get(s._id),n=e?e.size:0;n<r&&(r=n,t=e??null)}const s=[],n=t?t.keys():this.entities_;for(const t of n){let r=!0;for(const s of e)if(!this.has(t,s)){r=!1;break}r&&s.push(t)}return s}}var me,_e,ge;exports.TextAlign=void 0,(me=exports.TextAlign||(exports.TextAlign={}))[me.Left=0]="Left",me[me.Center=1]="Center",me[me.Right=2]="Right",exports.TextVerticalAlign=void 0,(_e=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[_e.Top=0]="Top",_e[_e.Middle=1]="Middle",_e[_e.Bottom=2]="Bottom",exports.TextOverflow=void 0,(ge=exports.TextOverflow||(exports.TextOverflow={}))[ge.Visible=0]="Visible",ge[ge.Clip=1]="Clip",ge[ge.Ellipsis=2]="Ellipsis";const xe=F("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2,dirty:!0});class ye{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const r=this.ctx,s=this.canvas;r.font=`${e.fontSize}px ${e.fontFamily}`;const n=t&&t.size.x>0&&t.size.y>0,o=n?t.size.x:0,i=n?t.size.y:0,a=e.wordWrap&&n;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),p=n?Math.ceil(o):h+2*u,f=n?Math.ceil(i):d+2*u;if(n&&e.overflow===exports.TextOverflow.Ellipsis&&d>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<p||s.height<f){const e=Math.max(s.width,this.nextPowerOf2(p)),t=Math.max(s.height,this.nextPowerOf2(f));s.width=e,s.height=t}const m=Math.round(255*e.color.r),_=Math.round(255*e.color.g),g=Math.round(255*e.color.b),x=e.color.a;r.clearRect(0,0,s.width,s.height),r.font=`${e.fontSize}px ${e.fontFamily}`,r.textAlign=this.mapAlign(e.align),r.textBaseline="top",r.fillStyle=`rgba(${m}, ${_}, ${g}, ${x})`,n&&e.overflow===exports.TextOverflow.Clip&&(r.save(),r.beginPath(),r.rect(0,0,p,f),r.clip());const y=l.length*c;let w;if(n)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-y)/2;break;case exports.TextVerticalAlign.Bottom:w=f-y-u;break;default:w=u}else w=u;let v=w;for(const t of l){let s;switch(e.align){case exports.TextAlign.Left:s=u;break;case exports.TextAlign.Center:s=p/2;break;case exports.TextAlign.Right:s=p-u;break;default:s=u}r.fillText(t,s,v),v+=c}n&&e.overflow===exports.TextOverflow.Clip&&r.restore();const b=r.getImageData(0,0,p,f),P=new Uint8Array(b.data.buffer),S=this.module.getResourceManager(),C=this.module._malloc(P.length);this.module.HEAPU8.set(P,C);const T=S.createTexture(p,f,C,P.length,1,!0);return this.module._free(C),{textureHandle:T,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let r=e;for(;r.length>0&&this.ctx.measureText(r+"...").width>t;)r=r.slice(0,-1);return r+"..."}renderForEntity(e,t,r){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const n=this.renderText(t,r);return this.cache.set(e,n),n}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[r,s]of this.cache)e(r)||(t.releaseTexture(s.textureHandle),this.cache.delete(r))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const r=e.split("\n"),s=[];for(const e of r){if(!e){s.push("");continue}let r="";for(const n of e){const e=r+n;this.ctx.measureText(e).width>t&&r?(s.push(r),r=n):r=e}r&&s.push(r)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const r of e){const e=this.ctx.measureText(r),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const we=F("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class ve{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const r=new ye(t),s=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,ie([],()=>{r.cleanupOrphaned(e=>s.valid(e)&&s.has(e,xe));const e=s.getEntitiesWithComponents([xe]);for(const t of e){const e=s.get(t,xe);if(!e.dirty)continue;s.has(t,z)||s.insert(t,z,{texture:v,size:{x:0,y:0},color:{r:1,g:1,b:1,a:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const n=s.has(t,we)?s.get(t,we):null,o=r.renderForEntity(t,e,n),i=s.get(t,z);i.texture=o.textureHandle,i.size.x=o.width,i.size.y=o.height,i.uvOffset.x=0,i.uvOffset.y=0,i.uvScale.x=1,i.uvScale.y=1,s.insert(t,z,i),e.dirty=!1}}))}}const be=new ve,Pe=F("UIMask",{enabled:!0});function Se(e,t){const r=Math.max(e.x,t.x),s=Math.max(e.y,t.y),n=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:r,y:s,w:Math.max(0,n-r),h:Math.max(0,o-s)}}function Ce(e,t,r,s,n,o,i){if(!e.has(t,we)||!e.has(t,W))return null;const a=e.get(t,we),l=e.get(t,W),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return function(e,t,r,s,n,o,i,a,l,c,u){const h=e-r*n,d=e+r*(1-n),p=t-s*o,f=t+s*(1-o);function m(e,t){const r=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],n=i[3]*e+i[7]*t+i[15];return[a+(r/n*.5+.5)*c,l+(s/n*.5+.5)*u]}const[_,g]=m(h,p),[x,y]=m(d,f),w=Math.min(_,x),v=Math.max(_,x),b=Math.min(g,y),P=Math.max(g,y);return{x:Math.round(w),y:Math.round(b),w:Math.round(v-w),h:Math.round(P-b)}}(l.position.x,l.position.y,c,u,.5,.5,r,s,n,o,i)}function Te(e,t){return(r,s,n,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Pe]);if(0!==l.length)try{!function(e,t,r,s,n,o,i,a,l){const c=new Set;for(const e of s){t.get(e,Pe).enabled&&c.add(e)}const u=[];for(const e of s){if(!c.has(e))continue;let r=!0,s=e;for(;t.has(s,O);){const e=t.get(s,O);if(c.has(e.entity)){r=!1;break}s=e.entity}r&&u.push(e)}function h(s,u){const d=e.getChildEntities(r,s);for(const r of d){let s=u;if(c.has(r)){const e=Ce(t,r,n,o,i,a,l);e&&(s=Se(u,e))}e.renderer_setEntityClipRect(r,s.x,s.y,s.w,s.h),h(r,s)}}for(const e of u){const r=Ce(t,e,n,o,i,a,l);r&&h(e,r)}}(e,t,r,l,s,n,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class Ae{build(e){if(!e.wasmModule)return;const t=e.pipeline_;t&&t.setMaskProcessor(Te(e.wasmModule,e.world))}}const Ee=new Ae;var Me;function Re(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(Me=exports.BlendMode||(exports.BlendMode={}))[Me.Normal=0]="Normal",Me[Me.Additive=1]="Additive",Me[Me.Multiply=2]="Multiply",Me[Me.Screen=3]="Screen",Me[Me.PremultipliedAlpha=4]="PremultipliedAlpha";let Fe=null,Be=null,Ue=1;const Ie=new Map;function De(e){Fe=e,Be=e.getResourceManager(),je()}function ke(){0!==Le&&Fe&&(Fe._free(Le),Le=0),Ie.clear(),Ue=1,$e=!1,Be=null,Fe=null}function We(){if(!Be)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Be}const ze={createShader:(e,t)=>We().createShader(e,t),releaseShader(e){e>0&&We().releaseShader(e)},create(e){const t=Ue++,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 Ie.set(t,r),t},get:e=>Ie.get(e),setUniform(e,t,r){const s=Ie.get(e);s&&s.uniforms.set(t,r)},getUniform(e,t){const r=Ie.get(e);return r?.uniforms.get(t)},setBlendMode(e,t){const r=Ie.get(e);r&&(r.blendMode=t)},getBlendMode(e){const t=Ie.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const r=Ie.get(e);r&&(r.depthTest=t)},getShader(e){const t=Ie.get(e);return t?.shader??0},release(e){Ie.delete(e)},isValid:e=>Ie.has(e),createFromAsset(e,t){const r={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)r[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?r[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?r[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(r[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:r,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ie.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const r=Ue++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Ie.set(r,s),r},toAssetData(e,t){const r=Ie.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=Ie.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let $e=!1,Le=0;const He=4096,Oe=new Map;let Ne=null;function Ve(e){const t=(0===Le&&Fe&&(Le=Fe._malloc(He)),Le);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,l]of e){if(r+128>He)break;let e=Oe.get(a);e||(Ne||(Ne=new TextEncoder),e=Ne.encode(a),Oe.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+r>>2]=c,r+=4,n.set(e,t+r),r+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+r>>2]=h,r+=4;for(let e=0;e<4;e++)i[t+r>>2]=d[e],r+=4;s++}return{ptr:t,count:s}}function je(){if(!Fe||$e)return;Fe.materialDataProvider=(e,t,r,s,n)=>{const o=Ie.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}=Ve(o.uniforms);Fe.HEAPU32[s>>2]=i,Fe.HEAPU32[n>>2]=a},$e=!0}const Ge={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class Xe{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const 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&&(ze.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())ze.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await o(t))throw new Error(`Material file not found: ${t}`);const r=await n(t);if(!r)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(r);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),a=await this.shaderLoader_.load(i);return{handle:ze.createFromAsset(s,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const r=e.substring(0,e.lastIndexOf("/"));return r?`${r}/${t}`:t}}function Ye(e,t){const r=new Map;for(const s of t.entities){const t=e.spawn();r.set(s.id,t),e.insert(t,G,{value:s.name});for(const r of s.components)Ke(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 qe(e,t,r){const s=new Map,n=r?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();s.set(i.id,t),e.insert(t,G,{value:i.name});for(const s of i.components){if("Sprite"===s.type&&n){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:r?.assetBaseUrl?`${r.assetBaseUrl}/${t}`:`/${t}`;try{const r=await n.loadTexture(s);e.texture=r.handle,o.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("BitmapText"===s.type&&n){const e=s.data;if("string"==typeof e.font&&e.font)try{const t=await n.loadBitmapFont(e.font,r?.assetBaseUrl);e.font=t}catch(t){console.warn(`Failed to load bitmap font: ${e.font}`,t),e.font=0}}if("SpineAnimation"===s.type&&n){const e=s.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await n.loadSpine(t,o,r?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,r?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Ke(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 Ke(e,t,r){const s=r.data;switch(r.type){case"LocalTransform":e.insert(t,k,s);break;case"Sprite":e.insert(t,z,s);break;case"Camera":e.insert(t,$,s);break;case"Canvas":e.insert(t,L,s);break;case"Text":e.insert(t,xe,s);break;case"BitmapText":e.insert(t,V,s);break;case"SpineAnimation":e.insert(t,j,s);break;case"UIRect":e.insert(t,we,s);break;case"UIMask":e.insert(t,Pe,s);break;case"RigidBody":e.insert(t,P,s);break;case"BoxCollider":e.insert(t,S,s);break;case"CircleCollider":e.insert(t,C,s);break;case"CapsuleCollider":e.insert(t,T,s);break;default:{const n=B(r.type);n?e.insert(t,n,s):console.warn(`Unknown component type: ${r.type}`);break}}}class Je{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const r=this.cache_.get(e);if(void 0!==r)return r;const s=this.pending_.get(e);if(s)return s;const n=t();this.pending_.set(e,n);try{const t=await n;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class Qe{constructor(e){this.textureCache_=new Je,this.shaderCache_=new Je,this.jsonCache_=new Je,this.textCache_=new Je,this.binaryCache_=new Je,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Je,this.embedded_=new Map,this.module_=e,this.canvas_=i(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Xe(t)}registerEmbeddedAssets(e){for(const[t,r]of Object.entries(e))this.embedded_.set(t,r)}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const r of[!0,!1]){const s=this.textureCacheKey(e,r),n=this.textureCache_.get(s);n&&(t.releaseTexture(n.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);this.textureCache_.clear(),this.fontCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const r=this.textureCache_.get(this.textureCacheKey(e,!0));return!!r&&(this.setTextureMetadata(r.handle,t),!0)}async loadSpine(e,t,r){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const n=this.resolveUrl(t,r),o=await this.fetchText(n);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o);for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,r);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,r),c=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);return this.writeToVirtualFS(e,c)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const r=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(r,async()=>e.endsWith(".bmfont")?this.loadBmfontAsset(r):this.loadFntFile(r))}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),r=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const n=r?`${r}/${s}`:s;return this.loadFntFile(n)}async loadFntFile(e){const t=await this.fetchText(e),r=t.match(/file="([^"]+)"/);if(!r)throw new Error(`No page texture found in .fnt file: ${e}`);const s=r[1],n=e.substring(0,e.lastIndexOf("/")),o=n?`${n}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(r):this.jsonCache_.getOrLoad(r,()=>this.fetchJson(r))}async loadText(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(r):this.textCache_.getOrLoad(r,()=>this.fetchText(r))}async loadBinary(e,t){const r=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(r):this.binaryCache_.getOrLoad(r,()=>this.fetchBinary(r))}async loadScene(e,t){return qe(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},r=[];if(e.textures)for(const s of e.textures)r.push(this.loadTexture(s).then(e=>{t.textures.set(s,e)}));if(e.materials)for(const s of e.materials)r.push(this.loadMaterial(s).then(e=>{t.materials.set(s,e)}));if(e.spine)for(const s of e.spine){const e=`${s.skeleton}:${s.atlas}`;r.push(this.loadSpine(s.skeleton,s.atlas,s.baseUrl).then(r=>{t.spine.set(e,r)}))}if(e.json)for(const s of e.json)r.push(this.loadJson(s).then(e=>{t.json.set(s,e)}));if(e.text)for(const s of e.text)r.push(this.loadText(s).then(e=>{t.text.set(s,e)}));if(e.binary)for(const s of e.binary)r.push(this.loadBinary(s).then(e=>{t.binary.set(s,e)}));return await Promise.all(r),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const r=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(r,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const r=await this.loadImage(e);return this.createTextureFromImage(r,t)}async loadImage(e){const r=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(r)??r;return new Promise((r,n)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void r(e)}catch{}r(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=s})}createTextureFromImage(e,t){const{width:r,height:s}=e,n=this.getWebGL2Context();return n?this.createTextureWebGL2(n,e,r,s,t):this.createTextureFallback(e,r,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,r,s,n){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,n?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,r,s),width:r,height:s}}createTextureFallback(e,t,r,s){(this.canvas_.width<t||this.canvas_.height<r)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(r))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const n=this.ctx_.getImageData(0,0,t,r),o=new Uint8Array(n.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,r,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:r}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const r=e[t+3];if(r>0&&r<255){const s=255/r;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e;if(!await o(t))throw new Error(`Shader file not found: ${e}`);const r=await n(t);if(!r)throw new Error(`Failed to read shader file: ${e}`);const{vertex:s,fragment:i}=this.parseEsShader(r);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return ze.createShader(s,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),r=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:r?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const r=await n(t);return JSON.parse(r)}const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):n(t)}const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):s(t)}const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const r=this.module_.FS;if(!r)return!1;try{return this.ensureVirtualDir(e),r.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const r=e.substring(0,e.lastIndexOf("/"));if(!r)return;const s=r.split("/").filter(e=>e);let n="";for(const e of s){n=n?`${n}/${e}`:e;try{t.analyzePath(n).exists||t.mkdir(n)}catch{try{t.mkdir(n)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const r=t??this.baseUrl;return r?`${r}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Ze=q(null,"Assets");class et{build(e){const t=e.wasmModule;t?e.insertResource(Ze,new Qe(t)):console.warn("AssetPlugin: No WASM module available")}}const tt=new et;let rt=null,st=0,nt=0,ot=0;const it=new Float32Array(256);function at(e){rt=e,st=rt._malloc(64),nt=rt._malloc(64),ot=rt._malloc(1024)}function lt(){rt&&(st&&(rt._free(st),st=0),nt&&(rt._free(nt),nt=0),ot&&(rt._free(ot),ot=0)),rt=null}function ct(){if(!rt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return rt}const ut={r:1,g:1,b:1,a:1},ht={begin(e){const t=ct();t.HEAPF32.set(e,st/4),t.draw_begin(st)},end(){ct().draw_end()},line(e,t,r,s=1){ct().draw_line(e.x,e.y,t.x,t.y,r.r,r.g,r.b,r.a,s)},rect(e,t,r,s=!0){ct().draw_rect(e.x,e.y,t.x,t.y,r.r,r.g,r.b,r.a,s)},rectOutline(e,t,r,s=1){ct().draw_rectOutline(e.x,e.y,t.x,t.y,r.r,r.g,r.b,r.a,s)},circle(e,t,r,s=!0,n=32){ct().draw_circle(e.x,e.y,t,r.r,r.g,r.b,r.a,s,n)},circleOutline(e,t,r,s=1,n=32){ct().draw_circleOutline(e.x,e.y,t,r.r,r.g,r.b,r.a,s,n)},texture(e,t,r,s=ut){ct().draw_texture(e.x,e.y,t.x,t.y,r,s.r,s.g,s.b,s.a)},textureRotated(e,t,r,s,n=ut){ct().draw_textureRotated(e.x,e.y,t.x,t.y,r,s,n.r,n.g,n.b,n.a)},setLayer(e){ct().draw_setLayer(e)},setDepth(e){ct().draw_setDepth(e)},getDrawCallCount:()=>rt?rt.draw_getDrawCallCount():0,getPrimitiveCount:()=>rt?rt.draw_getPrimitiveCount():0,setBlendMode(e){ct().draw_setBlendMode(e)},setDepthTest(e){ct().draw_setDepthTest(e)},drawMesh(e,t,r){const s=ct();s.HEAPF32.set(r,nt/4),s.draw_mesh(e,t,nt)},drawMeshWithMaterial(e,t,r){const s=ct(),n=ze.get(t);if(!n)return;if(ht.setBlendMode(n.blendMode),ht.setDepthTest(n.depthTest),0===n.uniforms.size)return void ht.drawMesh(e,n.shader,r);s.HEAPF32.set(r,nt/4);let o=0,i=0;for(const[e,t]of n.uniforms){const r=pt(e);if(!(r<0)){if(Re(t))it[o++]=10,it[o++]=r,it[o++]=t.slot??i++,it[o++]=t.textureId;else if("number"==typeof t)it[o++]=1,it[o++]=r,it[o++]=t;else if(Array.isArray(t)){it[o++]=t.length,it[o++]=r;for(let e=0;e<t.length;e++)it[o++]=t[e]}else"w"in t?(it[o++]=4,it[o++]=r,it[o++]=t.x,it[o++]=t.y,it[o++]=t.z,it[o++]=t.w):"z"in t?(it[o++]=3,it[o++]=r,it[o++]=t.x,it[o++]=t.y,it[o++]=t.z):(it[o++]=2,it[o++]=r,it[o++]=t.x,it[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(it.subarray(0,o),ot/4),s.draw_meshWithUniforms(e,n.shader,nt,ot,o)):s.draw_mesh(e,n.shader,nt)}},dt={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function pt(e){return dt[e]??-1}var ft;exports.DataType=void 0,(ft=exports.DataType||(exports.DataType={}))[ft.Float=1]="Float",ft[ft.Float2=2]="Float2",ft[ft.Float3=3]="Float3",ft[ft.Float4=4]="Float4",ft[ft.Int=5]="Int",ft[ft.Int2=6]="Int2",ft[ft.Int3=7]="Int3",ft[ft.Int4=8]="Int4";let mt=null,_t=0,gt=0,xt=0;function yt(e){mt=e,_t=mt._malloc(262144),gt=mt._malloc(65536),xt=mt._malloc(256)}function wt(){mt&&(_t&&mt._free(_t),gt&&mt._free(gt),xt&&mt._free(xt),_t=0,gt=0,xt=0),mt=null}function vt(){if(!mt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return mt}const bt={create(e){const t=vt(),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,_t/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,xt,n).set(o),t.geometry_init(r,_t,s,xt,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,gt,s).set(e.indices),t.geometry_setIndices16(r,gt,s)}else{new Uint32Array(t.HEAPU8.buffer,gt,s).set(e.indices),t.geometry_setIndices32(r,gt,s)}}return r},updateVertices(e,t,r=0){const s=vt(),n=t.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);s.HEAPF32.set(t,_t/4),s.geometry_updateVertices(e,_t,n,r)},release(e){e>0&&vt().geometry_release(e)},isValid:e=>!(!mt||e<=0)&&mt.geometry_isValid(e),createQuad(e=1,t=1){const r=e/2,s=t/2;return bt.create({vertices:new Float32Array([-r,-s,0,0,r,-s,1,0,r,s,1,1,-r,s,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const r=[],s=[];r.push(0,0,.5,.5);for(let s=0;s<=t;s++){const n=s/t*Math.PI*2,o=Math.cos(n)*e,i=Math.sin(n)*e,a=(Math.cos(n)+1)/2,l=(Math.sin(n)+1)/2;r.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return bt.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 bt.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 Pt=null;function St(e){Pt=e}function Ct(){Pt&&At.isInitialized()&&At.shutdown(),Pt=null}function Tt(){if(!Pt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Pt}const At={init:(e,t)=>Tt().postprocess_init(e,t),shutdown(){Tt().postprocess_shutdown()},resize(e,t){Tt().postprocess_resize(e,t)},addPass:(e,t)=>Tt().postprocess_addPass(e,t),removePass(e){Tt().postprocess_removePass(e)},setEnabled(e,t){Tt().postprocess_setPassEnabled(e,t)},isEnabled:e=>Tt().postprocess_isPassEnabled(e),setUniform(e,t,r){Tt().postprocess_setUniformFloat(e,t,r)},setUniformVec4(e,t,r){Tt().postprocess_setUniformVec4(e,t,r.x,r.y,r.z,r.w)},begin(){Tt().postprocess_begin()},end(){Tt().postprocess_end()},getPassCount:()=>Tt().postprocess_getPassCount(),isInitialized:()=>!!Pt&&Pt.postprocess_isInitialized(),setBypass(e){Tt().postprocess_setBypass(e)},isBypassed:()=>!Pt||Pt.postprocess_isBypassed(),createBlur:()=>ze.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:()=>ze.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:()=>ze.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:()=>ze.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 Mt;exports.RenderStage=void 0,(Mt=exports.RenderStage||(exports.RenderStage={}))[Mt.Background=0]="Background",Mt[Mt.Opaque=1]="Opaque",Mt[Mt.Transparent=2]="Transparent",Mt[Mt.Overlay=3]="Overlay";let Rt=null,Ft=0;function Bt(e){Rt=e,Ft=Rt._malloc(64)}function Ut(){Rt&&Ft&&(Rt._free(Ft),Ft=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&&Ft&&(Rt.HEAPF32.set(e,Ft/4),Rt.renderer_begin(Ft,t??0))},flush(){Rt?.renderer_flush()},end(){Rt?.renderer_end()},submitSprites(e){Rt&&Rt.renderer_submitSprites(e._cpp)},submitBitmapText(e){Rt&&Rt.renderer_submitBitmapText(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,s){Rt?.renderer_setClearColor?.(e,t,r,s)},setViewport(e,t,r,s){Rt?.renderer_setViewport(e,t,r,s)},setScissor(e,t,r,s,n){Rt?.renderer_setScissor(e,t,r,s,n)},clearBuffers(e){Rt?.renderer_clearBuffers(e)},getStats:()=>Rt?{drawCalls:Rt.renderer_getDrawCalls(),triangles:Rt.renderer_getTriangles(),sprites:Rt.renderer_getSprites(),text:Rt.renderer_getText(),spine:Rt.renderer_getSpine?.()??0,meshes:Rt.renderer_getMeshes(),culled:Rt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Dt=null;function kt(e){Dt=e}function Wt(){Dt=null}const zt={enable(){Dt?.gl_enableErrorCheck(!0)},disable(){Dt?.gl_enableErrorCheck(!1)},check:e=>Dt?.gl_checkErrors(e)??0,diagnose(){Dt?.renderer_diagnose()}},$t=new Map;function Lt(e){$t.delete(e)}class Ht{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}setSpineRenderer(e){this.spineRenderer_=e}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:r,width:s,height:n,elapsed:o}=e;s===this.lastWidth_&&n===this.lastHeight_||(It.resize(s,n),At.isInitialized()&&At.getPassCount()>0&&At.resize(s,n),this.lastWidth_=s,this.lastHeight_=n),It.setViewport(0,0,s,n),It.clearBuffers(3),It.begin(r),this.maskProcessor_&&this.maskProcessor_(t._cpp,r,0,0,s,n),It.submitSprites(t),It.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):It.submitSpine(t),It.flush(),this.executeDrawCallbacks(r,o),It.end()}renderCamera(e){const{registry:t,viewProjection:r,viewportPixels:s,clearFlags:n,elapsed:o}=e;It.setViewport(s.x,s.y,s.w,s.h),It.setScissor(s.x,s.y,s.w,s.h,!0),It.clearBuffers(n),It.setScissor(0,0,0,0,!1),It.begin(r),this.maskProcessor_&&this.maskProcessor_(t._cpp,r,s.x,s.y,s.w,s.h),It.submitSprites(t),It.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):It.submitSpine(t),It.flush(),this.executeDrawCallbacks(r,o),It.end()}executeDrawCallbacks(e,t){const r=$t;if(r.size>0){ht.begin(e);const s=[];for(const[e,n]of r.entries())try{n(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}ht.end();for(const e of s)Lt(e)}}}class Ot{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=a(),t=e-this.lastTime_;this.lastTime_=e;const r=t/1e3;for(this.updateTime(r),this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=r;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate);this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),requestAnimationFrame(this.mainLoop)},this.world_=new fe,this.resources_=new Q;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Ot}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new le(this.world_,this.resources_),this.resources_.insert(Z,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1,Wt(),Ut(),Ct(),wt(),ke(),lt()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(Z);t.delta=e,t.elapsed+=e,t.frameCount++}}const Nt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Vt(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)}}}const jt=new Float32Array(16);function Gt(e,t,r,s,n,o){const i=jt;i.fill(0);const a=t-e,l=s-r,c=o-n;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+r)/l,i[14]=-(o+n)/c,i[15]=1,i}const Xt=new Float32Array(16);function Yt(e,t,r,s){const n=Xt;n.fill(0);const o=1/Math.tan(e/2),i=r-s;return n[0]=o/t,n[5]=o,n[10]=(s+r)/i,n[11]=-1,n[14]=2*s*r/i,n}const qt=new Float32Array(16);function Kt(e,t,r){const s=qt;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-r,s[15]=1,s}function Jt(e,t){const r=new Float32Array(16);for(let s=0;s<4;s++)for(let n=0;n<4;n++)r[4*n+s]=e[0+s]*t[4*n+0]+e[4+s]*t[4*n+1]+e[8+s]*t[4*n+2]+e[12+s]*t[4*n+3];return r}async function Qt(e,t){if(t)return t();return(0,(await import(e)).default)()}const Zt=q({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),er=q(null,"PhysicsAPI");function tr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function rr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class sr{constructor(e,t={},r){this.wasmUrl_=e,this.factory_=r,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Zt,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,r=new Map,s=Qt(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const n=function(e){const t=e.world.getEntitiesWithComponents([L]);for(const r of t){const t=e.world.get(r,L);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/n,i=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,ie([K(Z)],a=>{const l=i.getEntitiesWithComponents([P,k,W]),c=new Set;for(const n of l){c.add(n);const a=i.get(n,P),l=i.get(n,W);if(t.has(n)){const e=r.get(n);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(n,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=tr(l.rotation);s._physics_createBody(n,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),nr(e,s,n),t.add(n),r.set(n,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===A.Kinematic){const e=tr(l.rotation);s._physics_setBodyTransform(n,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),r.delete(e));s._physics_step(a.delta),function(e,t,r){const s=t._physics_getDynamicBodyCount();if(0===s)return;const n=t._physics_getDynamicBodyTransforms(),o=n>>2;for(let n=0;n<s;n++){const s=o+4*n,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*r,l=t.HEAPF32[s+2]*r,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,k);if(!u)continue;let h=a,d=l,p=c;if(e.world.has(i,O)){const t=e.world.get(i,O);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,W)){const r=e.world.get(t.entity,W),s=tr(r.rotation),n=a-r.position.x,o=l-r.position.y,i=Math.cos(-s),u=Math.sin(-s);h=(n*i-o*u)/(0!==r.scale.x?r.scale.x:1),d=(n*u+o*i)/(0!==r.scale.y?r.scale.y:1),p=c-s}}u.position.x=h,u.position.y=d;const f=rr(p);u.rotation.w=f.w,u.rotation.x=f.x,u.rotation.y=f.y,u.rotation.z=f.z,e.world.insert(i,k,u)}}(e,s,n),function(e,t,r){t._physics_collectEvents();const s=[],n=t._physics_getCollisionEnterCount();if(n>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<n;o++){const n=e+6*o;s.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1],normalX:t.HEAPF32[n+2],normalY:t.HEAPF32[n+3],contactX:t.HEAPF32[n+4]*r,contactY:t.HEAPF32[n+5]*r})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let r=0;r<i;r++){const s=e+2*r;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let r=0;r<l;r++){const s=e+2*r;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let r=0;r<u;r++){const s=e+2*r;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Zt,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,n)},{name:"PhysicsSystem"})),e.__physicsModule=s,e.insertResource(er,or._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=s}}function nr(e,t,r){const s=e.world;if(s.has(r,S)){const e=s.get(r,S);return void t._physics_addBoxShape(r,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(r,C)){const e=s.get(r,C);return void t._physics_addCircleShape(r,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(r,T)){const e=s.get(r,T);t._physics_addCapsuleShape(r,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class or{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(or.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function ir(e,t,r=!0){const s=e.getResourceManager(),n=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,n);const o=s.createTexture(t.width,t.height,n,t.pixels.length,1,r);return e._free(n),o}function ar(e){const t=[];for(const r of e.split("\n")){const e=r.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function lr(e,t,r,s){const n=e.scale.x*t*(r?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,h=a+a,d=l+l,p=c+c,f=a*h,m=a*d,_=a*p,g=l*d,x=l*p,y=c*p,w=u*h,v=u*d,b=u*p;return new Float32Array([(1-(g+y))*n,(m+b)*n,(_-v)*n,0,(m-b)*o,(1-(f+y))*o,(x+w)*o,0,(_+v)*i,(x-w)*i,(1-(f+g))*i,0,e.position.x,e.position.y,e.position.z,1])}async function cr(e,t,r,s,n,o,i){const a=await async function(e,t,r){const s={};for(const n of t.entities)for(const t of n.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const n=t.data.texture;if(void 0!==s[n])continue;try{s[n]=ir(e,await r.loadPixels(n))}catch{s[n]=0}}return s}(t,r,s);!function(e,t,r){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const n=r[e];if(n&&n>0){const r=t.textureMetadata[e];if(r?.sliceBorder){const e=r.sliceBorder;s.setTextureMetadata(n,e.left,e.right,e.top,e.bottom)}}}}(t,r,a);let l={},c=null;if(n&&(c=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(n),l=await async function(e,t,r,s,n){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=n.resolvePath(i),c=n.resolvePath(a);try{const s=n.readText(a),u=l.endsWith(".skel");let h,d;if(u){const e=n.readBinary(i);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=n.readText(i),r=(new TextEncoder).encode(e);d=r.length,h=t._malloc(d+1),t.HEAPU8.set(r,h),t.HEAPU8[h+d]=0}const p=r.loadSkeleton(h,d,s,s.length,u);if(t._free(h),p<0)continue;o[i]=p;const f=ar(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const s=m+"/"+f[t];try{const o=n.loadPixelsRaw?await n.loadPixelsRaw(s):await n.loadPixels(s),i=ir(e,o,!1),a=e.getResourceManager().getTextureGLId(i);r.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,n,c,r,s)),o){new sr("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const u=function(e,t){const r={},s={};for(const n of e.entities)for(const e of n.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const n=e.data.material;if(void 0===r[n])try{const e=JSON.parse(t.readText(n));if(!e.vertexSource||!e.fragmentSource){r[n]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=ze.createShader(e.vertexSource,e.fragmentSource),s[o]=i),r[n]=ze.createFromAsset(e,i)}catch{r[n]=0}}return r}(r,s),h=Ye(e.world,r);if(function(e,t,r,s){for(const n of t.entities){const t=s.get(n.id);if(void 0!==t)for(const s of n.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const n=e.get(t,z);n&&(n.texture=r[s.data.texture]||0,e.insert(t,z,n))}}}(e.world,r,a,h),function(e,t,r,s){for(const n of t.entities){const t=s.get(n.id);if(void 0!==t)for(const s of n.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const n=r[s.data.material]||0;if(n)if("Sprite"===s.type){const r=e.get(t,z);r&&(r.material=n,e.insert(t,z,r))}else if("SpineAnimation"===s.type){const r=e.get(t,j);r&&(r.material=n,e.insert(t,j,r))}}}}(e.world,r,u,h),n&&c){const s=function(e,t,r,s){const n={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=r[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(n[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return n}(c,r,l,h);!function(e,t,r,s,n){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in n){const o=Number(e),i=n[e],a=c.has(o,j)?c.get(o,j):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&s.update(i,l*h);let d=0;if(c.has(o,W)){const e=lr(c.get(o,W),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const p=s.getMeshBatchCount(i);for(let e=0;e<p;e++){const n=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!n||!o)continue;const a=8*n*4,l=2*o,c=r._malloc(a),u=r._malloc(l),h=r._malloc(4),p=r._malloc(4);s.getMeshBatchData(i,e,c,u,h,p);const f=r.HEAPU32[h>>2],m=r.HEAPU32[p>>2],_=new Float32Array(r.HEAPF32.buffer,c,8*n),g=new Uint16Array(r.HEAPU8.buffer,u,o),x=t._malloc(a),y=t._malloc(l);t.HEAPF32.set(_,x>>2),new Uint16Array(t.HEAPU8.buffer,y,o).set(g),t.renderer_submitTriangles(x,n,y,o,f,m,d),t._free(x),t._free(y),r._free(c),r._free(u),r._free(h),r._free(p)}d&&t._free(d)}})}(e,t,n,c,s)}}class ur{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 hr={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),hr.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 dr=!1;y||(y=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const r="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},n=await l(r,s);return{ok:n.ok,status:n.status,statusText:n.statusText,headers:new Headers(n.headers),json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:r}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return c(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),r=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);n<128?r[s++]=n:n<2048?(r[s++]=192|n>>6,r[s++]=128|63&n):n>=55296&&n<=56319?(n=e.charCodeAt(++t)-56320+(n-55296<<10)+65536,r[s++]=240|n>>18,r[s++]=128|n>>12&63,r[s++]=128|n>>6&63,r[s++]=128|63&n):(r[s++]=224|n>>12,r[s++]=128|n>>6&63,r[s++]=128|63&n)}return r.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let r="";for(let e=0;e<t.length;){const s=t[e];if(s<128)r+=String.fromCharCode(s),e++;else if(192==(224&s))r+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))r+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const n=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;r+=String.fromCharCode(55296+(n>>10),56320+(1023&n)),e+=4}}return r}})}(),console.log("[ESEngine] WeChat platform initialized")),e=w,exports.App=Ot,exports.AssetPlugin=et,exports.AssetServer=Qe,exports.Assets=Ze,exports.AsyncCache=Je,exports.BitmapText=V,exports.BodyType=A,exports.BoxCollider=S,exports.Camera=$,exports.Canvas=L,exports.CapsuleCollider=T,exports.Children=N,exports.CircleCollider=C,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=se,exports.Draw=ht,exports.EntityCommands=re,exports.GLDebug=zt,exports.Geometry=bt,exports.INVALID_ENTITY=0,exports.INVALID_FONT=0,exports.INVALID_TEXTURE=v,exports.Input=ue,exports.InputPlugin=he,exports.InputState=ce,exports.LocalTransform=k,exports.Material=ze,exports.MaterialLoader=Xe,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=G,exports.Parent=O,exports.Physics=or,exports.PhysicsEvents=Zt,exports.PhysicsPlugin=sr,exports.PostProcess=At,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 ur(this.baseUrl_);await s.prefetch(t);let n=null;const o=this.app_.__spineInitPromise;if(o){n=(await o).controller.raw}await cr(this.app_,this.app_.wasmModule,t,s,n),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const r=e.getEntitiesWithComponents([$]);for(const s of r){if(e.get(s,$).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,r=1920/1080;const s=e.getEntitiesWithComponents([L]);for(const n of s){const s=e.get(n,L);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,r=s.designResolution.x/s.designResolution.y;break}}const n=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(n,k,o);const i={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:r,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3};e.insert(n,$,i)}}},exports.Query=function(...e){return function(e,t=[],r=[]){const s=[];return e.forEach((e,t)=>{ee(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:r}}(e)},exports.QueryInstance=te,exports.RenderPipeline=Ht,exports.RenderTexture=hr,exports.Renderer=It,exports.Res=K,exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.RigidBody=P,exports.ShaderSources=Ge,exports.SpineAnimation=j,exports.Sprite=z,exports.SystemRunner=le,exports.Text=xe,exports.TextPlugin=ve,exports.TextRenderer=ye,exports.Time=Z,exports.UIMask=Pe,exports.UIMaskPlugin=Ae,exports.UIRect=we,exports.Velocity=H,exports.WebAssetProvider=ur,exports.World=fe,exports.WorldTransform=W,exports.addStartupSystem=function(e){ae().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){ae().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){ae().push({schedule:e,system:t})},exports.assetPlugin=tt,exports.clearDrawCallbacks=function(){$t.clear()},exports.clearUserComponents=function(){R().clear()},exports.color=(e=1,t=1,r=1,s=1)=>({r:e,g:t,b:r,a:s}),exports.createMaskProcessor=Te,exports.createWebApp=function(e,t){const r=Ot.new(),s=new e.Registry;r.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),at(e),De(e),yt(e),St(e),Bt(e),kt(e);const n=new Ht;r.pipeline_=n;let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),l={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:r}=i(),l=e.registry_getCanvasEntity(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;It.setClearColor(e.r,e.g,e.b,e.a)}const c=(a()-o)/1e3;It.resize(t,r),At.isInitialized()&&At.getPassCount()>0&&!At.isBypassed()&&At.resize(t,r);const u=function(e,t,r,s){const n=e.registry_getCameraEntities(t);if(0===n.length)return[];const o=function(e,t){const r=e.registry_getCanvasEntity(t);return r<0?null:t.getCanvas(r)}(e,t),i=[];for(const e of n){const n=t.getCamera(e),a=t.getLocalTransform(e),l={x:n.viewportX,y:n.viewportY,w:n.viewportW,h:n.viewportH},c=l.w*r/(l.h*s);let u;if(1===n.projectionType){let e=n.orthoSize;if(o){e=Vt(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}const t=e*c;u=Gt(-t,t,-e,e,-n.farPlane,n.farPlane)}else u=Yt(n.fov*Math.PI/180,c,n.nearPlane,n.farPlane);const h=Kt(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:Jt(u,h),viewportRect:l,clearFlags:n.clearFlags,priority:n.priority})}return i.sort((e,t)=>e.priority-t.priority),i}(e,s,t,r);if(0===u.length)n.render({registry:{_cpp:s},viewProjection:Nt,width:t,height:r,elapsed:c});else{for(const e of u){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*r),l=Math.round(o.w*t),u=Math.round(o.h*r);n.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}It.setViewport(0,0,t,r)}}};return r.addSystemToSchedule(exports.Schedule.Last,l),r.addPlugin(tt),r.addPlugin(de),r.addPlugin(be),r.addPlugin(Ee),r},exports.defineComponent=F,exports.defineResource=q,exports.defineSystem=ie,exports.defineTag=function(e){const t=R(),r=t.get(e);if(r)return r;const s=M(e,{});return t.set(e,s),U(e,{},!0),s},exports.findEntityByName=function(e,t){const r=e.getEntitiesWithComponents([G]);for(const s of r){const r=e.get(s,G);if(r&&r.value===t)return s}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const r of t)e.addSystemToSchedule(r.schedule,r.system);t.length=0}},exports.getComponentDefaults=function(e){const t=X[e];if(t)return{...t._default};const r=B(e);return r?{...r._default}:null},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=B,exports.initDrawAPI=at,exports.initGLDebugAPI=kt,exports.initGeometryAPI=yt,exports.initMaterialAPI=De,exports.initPostProcessAPI=St,exports.initRendererAPI=Bt,exports.inputPlugin=de,exports.isBuiltinComponent=D,exports.isEditor=function(){return dr},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!dr},exports.isTextureRef=Re,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=Ke,exports.loadPhysicsModule=Qt,exports.loadRuntimeScene=cr,exports.loadSceneData=Ye,exports.loadSceneWithAssets=qe,exports.platformFetch=r,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,r){return t().instantiateWasm(e,r)},exports.platformReadFile=s,exports.platformReadTextFile=n,exports.quat=(e=1,t=0,r=0,s=0)=>({w:e,x:t,y:r,z:s}),exports.registerDrawCallback=function(e,t){$t.set(e,t)},exports.registerEmbeddedAssets=function(e,t){const r=e.getResource(Ze);r&&r.registerEmbeddedAssets(t)},exports.registerMaterialCallback=je,exports.setEditorMode=function(e){dr=e},exports.shutdownDrawAPI=lt,exports.shutdownGLDebugAPI=Wt,exports.shutdownGeometryAPI=wt,exports.shutdownMaterialAPI=ke,exports.shutdownPostProcessAPI=Ct,exports.shutdownRendererAPI=Ut,exports.textPlugin=be,exports.uiMaskPlugin=Ee,exports.unregisterDrawCallback=Lt,exports.updateCameraAspectRatio=function(e,t){const r=e.getEntitiesWithComponents([$]);for(const s of r){const r=e.get(s,$);r&&(r.aspectRatio=t,e.insert(s,$,r))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,r=0)=>({x:e,y:t,z:r}),exports.vec4=(e=0,t=0,r=0,s=1)=>({x:e,y:t,z:r,w:s}),exports.wxFileExists=f,exports.wxFileExistsSync=function(e){const t=h();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=x,exports.wxLoadImage=g,exports.wxLoadImagePixels=async function(e){return x(await g(e))},exports.wxReadFile=d,exports.wxReadTextFile=p,exports.wxWriteFile=function(e,t){return new Promise((r,s)=>{h().writeFile({filePath:e,data:t,success:()=>r(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};+"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function s(e,s){return t().fetch(e,s)}async function r(e){return t().readFile(e)}async function n(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,s){return t().createCanvas(e,s)}function a(){return t().now()}function l(e,t){return new Promise((s,r)=>{const n=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===n?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,r={};if(e.header)for(const t of Object.keys(e.header))r[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:r,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{r(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function c(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const s=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(s,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${s}": ${t}`)}}let u=null;function h(){return u||(u=wx.getFileSystemManager()),u}function d(e){return new Promise((t,s)=>{h().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function p(e,t="utf-8"){return new Promise((s,r)=>{h().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function f(e){return new Promise(t=>{h().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}let m=null,x=null;function g(e){return new Promise((t,s)=>{const r=wx.createImage();r.onload=()=>t(r),r.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),r.src=e})}function _(e){const{width:t,height:s}=e,{ctx:r}=function(e,t){return m||(m=wx.createCanvas(),m.width=e,m.height=t,x=m.getContext("2d")),(m.width<e||m.height<t)&&(m.width=Math.max(m.width,e),m.height=Math.max(m.height,t)),{canvas:m,ctx:x}}(t,s);r.clearRect(0,0,t,s),r.drawImage(e,0,0);const n=r.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(n.data.buffer)}}let y=!1;const w=new class{constructor(){this.name="wechat"}async fetch(e,t){return l(e,t)}async readFile(e){return d(e)}async readTextFile(e){return p(e)}async fileExists(e){return f(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return c(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const s=wx.createCanvas();return s.width=e,s.height=t,s}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{const s=t.touches[0];s&&e.onPointerDown(0,s.clientX,s.clientY)}),wx.onTouchMove(t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX,s.clientY)}),wx.onTouchEnd(()=>{e.onPointerUp(0)})}},v=4294967295;function b(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const S=b("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),P=b("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),C=b("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),T=b("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),A={Static:0,Kinematic:1,Dynamic:2};let M=0;function E(e,t){const s=++M;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function R(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function B(e,t){const s=R(),r=s.get(e);if(r)return r;const n=E(e,t);return s.set(e,n),U(e,t,!1),n}function F(e){const t=R(),s=t.get(e);if(s)return s;const r=E(e,{});return t.set(e,r),U(e,{},!0),r}function I(e){return R().get(e)}function U(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function W(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function k(e){return!0===e._builtin}const D=W("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),z=W("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),L=W("Sprite",{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),H=W("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),$=W("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),O=W("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),j=W("Parent",{entity:0}),N=W("Children",{entities:[]}),V=W("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:0}),X=W("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),G={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},Y={LocalTransform:D,WorldTransform:z,Sprite:L,Camera:H,Canvas:$,Velocity:O,Parent:j,Children:N,BitmapText:V,SpineAnimation:X,RigidBody:S,BoxCollider:P,CircleCollider:C,CapsuleCollider:T};let q=0;function K(e,t){const s=++q;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function J(e){return{_type:"res",_resource:e}}class Q{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}}class Z{constructor(){this.resources_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id)}getResMut(e){return new Q(this.get(e),t=>this.set(e,t))}}const ee=K({delta:0,elapsed:0,frameCount:0},"Time");function te(e){return"object"==typeof e&&null!==e&&"mut"===e._type}class se{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>te(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with)}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,r=this.world_.getEntitiesWithComponents(this.allRequired_),n=s.length,o=e.length>0,i=t.length>0,a=new Array(n+1);let l=null,c=[];try{for(const u of r){if(null!==l&&o){for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}c.length=0}if(i){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(u,t[s])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<n;e++)a[e+1]=this.world_.get(u,s[e]);if(o){for(let t=0;t<e.length;t++){const r=e[t];c.push({component:s[r],data:a[r+1]})}l=u}yield a}}finally{if(null!==l&&o)for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class re{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let s;return s=k(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class ne{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new re(this,null);return this.spawned_.push(e),e}entity(e){return new re(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var oe;exports.Schedule=void 0,(oe=exports.Schedule||(exports.Schedule={}))[oe.Startup=0]="Startup",oe[oe.First=1]="First",oe[oe.PreUpdate=2]="PreUpdate",oe[oe.Update=3]="Update",oe[oe.PostUpdate=4]="PostUpdate",oe[oe.Last=5]="Last",oe[oe.FixedPreUpdate=10]="FixedPreUpdate",oe[oe.FixedUpdate=11]="FixedUpdate",oe[oe.FixedPostUpdate=12]="FixedPostUpdate";let ie=0;function ae(e,t,s){const r=++ie;return{_id:Symbol(`System_${r}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${r}`}}function le(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class ce{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof ne&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new se(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new ne(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=K(new ue,"Input");class de{constructor(e){this.target_=e??null}build(e){const s=new ue;e.insertResource(he,s),t().bindInputEvents({onKeyDown(e){s.keysDown.has(e)||s.keysPressed.add(e),s.keysDown.add(e)},onKeyUp(e){s.keysDown.delete(e),s.keysReleased.add(e)},onPointerMove(e,t){s.mouseX=e,s.mouseY=t},onPointerDown(e,t,r){s.mouseX=t,s.mouseY=r,s.mouseButtons.add(e),s.mouseButtonsPressed.add(e)},onPointerUp(e){s.mouseButtons.delete(e),s.mouseButtonsReleased.add(e)},onWheel(e,t){s.scrollDeltaX+=e,s.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.First,ae([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const pe=new de;function fe(e){if(null==e||"object"!=typeof e||Array.isArray(e))return e;const t=e;if("r"in t&&"g"in t&&"b"in t&&"a"in t&&!("x"in t))return{x:t.r,y:t.g,z:t.b,w:t.a};const s={};for(const e of Object.keys(t)){const r=t[e];s[e]=null==r||"object"!=typeof r||Array.isArray(r)?r:fe(r)}return s}class me{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,s){return k(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return k(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return k(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){k(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,s){const r={...t._default,...s};if(this.cppRegistry_){const s=`add${t._cppName}`;this.cppRegistry_[s].call(this.cppRegistry_,e,fe(r))}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const s=`get${t._cppName}`;return this.cppRegistry_[s].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const s=`has${t._cppName}`;return this.cppRegistry_[s].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const s=`remove${t._cppName}`;this.cppRegistry_[s].call(this.cppRegistry_,e)}insertScript(e,t,s){const r=t.create(s);return this.getStorage(t).set(e,r),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();let t=null,s=1/0;for(const r of e)if(!k(r)){const e=this.tsStorage_.get(r._id),n=e?e.size:0;n<s&&(s=n,t=e??null)}const r=[],n=t?t.keys():this.entities_;for(const t of n){let s=!0;for(const r of e)if(!this.has(t,r)){s=!1;break}s&&r.push(t)}return r}}var xe,ge,_e;exports.TextAlign=void 0,(xe=exports.TextAlign||(exports.TextAlign={}))[xe.Left=0]="Left",xe[xe.Center=1]="Center",xe[xe.Right=2]="Right",exports.TextVerticalAlign=void 0,(ge=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[ge.Top=0]="Top",ge[ge.Middle=1]="Middle",ge[ge.Bottom=2]="Bottom",exports.TextOverflow=void 0,(_e=exports.TextOverflow||(exports.TextOverflow={}))[_e.Visible=0]="Visible",_e[_e.Clip=1]="Clip",_e[_e.Ellipsis=2]="Ellipsis";const ye=B("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2,dirty:!0});class we{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,r=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const n=t&&t.size.x>0&&t.size.y>0,o=n?t.size.x:0,i=n?t.size.y:0,a=e.wordWrap&&n;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),p=n?Math.ceil(o):h+2*u,f=n?Math.ceil(i):d+2*u;if(n&&e.overflow===exports.TextOverflow.Ellipsis&&d>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(r.width<p||r.height<f){const e=Math.max(r.width,this.nextPowerOf2(p)),t=Math.max(r.height,this.nextPowerOf2(f));r.width=e,r.height=t}const m=Math.round(255*e.color.r),x=Math.round(255*e.color.g),g=Math.round(255*e.color.b),_=e.color.a;s.clearRect(0,0,r.width,r.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${m}, ${x}, ${g}, ${_})`,n&&e.overflow===exports.TextOverflow.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const y=l.length*c;let w;if(n)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-y)/2;break;case exports.TextVerticalAlign.Bottom:w=f-y-u;break;default:w=u}else w=u;let v=w;for(const t of l){let r;switch(e.align){case exports.TextAlign.Left:r=u;break;case exports.TextAlign.Center:r=p/2;break;case exports.TextAlign.Right:r=p-u;break;default:r=u}s.fillText(t,r,v),v+=c}n&&e.overflow===exports.TextOverflow.Clip&&s.restore();const b=s.getImageData(0,0,p,f),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const T=P.createTexture(p,f,C,S.length,1,!0);return this.module._free(C),{textureHandle:T,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const r=this.cache.get(e);if(r){this.module.getResourceManager().releaseTexture(r.textureHandle)}const n=this.renderText(t,s);return this.cache.set(e,n),n}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,r]of this.cache)e(s)||(t.releaseTexture(r.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),r=[];for(const e of s){if(!e){r.push("");continue}let s="";for(const n of e){const e=s+n;this.ctx.measureText(e).width>t&&s?(r.push(s),s=n):s=e}s&&r.push(s)}return r.length>0?r:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),r=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,r)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const ve=B("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class be{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new we(t),r=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,ae([],()=>{s.cleanupOrphaned(e=>r.valid(e)&&r.has(e,ye));const e=r.getEntitiesWithComponents([ye]);for(const t of e){const e=r.get(t,ye);if(!e.dirty)continue;r.has(t,L)||r.insert(t,L,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const n=r.has(t,ve)?r.get(t,ve):null,o=s.renderForEntity(t,e,n),i=r.get(t,L);i.texture=o.textureHandle,i.size.x=o.width,i.size.y=o.height,i.uvOffset.x=0,i.uvOffset.y=0,i.uvScale.x=1,i.uvScale.y=1,r.insert(t,L,i),e.dirty=!1}}))}}const Se=new be,Pe=B("UIMask",{enabled:!0});function Ce(e,t){const s=Math.max(e.x,t.x),r=Math.max(e.y,t.y),n=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:r,w:Math.max(0,n-s),h:Math.max(0,o-r)}}function Te(e,t,s,r,n,o,i,a,l,c,u){const h=e-s*n,d=e+s*(1-n),p=t-r*o,f=t+r*(1-o);function m(e,t){const s=i[0]*e+i[4]*t+i[12],r=i[1]*e+i[5]*t+i[13],n=i[3]*e+i[7]*t+i[15];return[a+(.5*(s/n)+.5)*c,l+(.5*(r/n)+.5)*u]}const[x,g]=m(h,p),[_,y]=m(d,f),w=Math.min(x,_),v=Math.max(x,_),b=Math.min(g,y),S=Math.max(g,y);return{x:Math.round(w),y:Math.round(b),w:Math.round(v-w),h:Math.round(S-b)}}function Ae(e,t){const s=t??new Float32Array(16),r=e[0],n=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],h=e[8],d=e[9],p=e[10],f=e[11],m=e[12],x=e[13],g=e[14],_=e[15],y=r*l-n*a,w=r*c-o*a,v=r*u-i*a,b=n*c-o*l,S=n*u-i*l,P=o*u-i*c,C=h*x-d*m,T=h*g-p*m,A=h*_-f*m,M=d*g-p*x,E=d*_-f*x,R=p*_-f*g;let B=y*R-w*E+v*M+b*A-S*T+P*C;return Math.abs(B)<1e-8||(B=1/B,s[0]=(l*R-c*E+u*M)*B,s[1]=(o*E-n*R-i*M)*B,s[2]=(x*P-g*S+_*b)*B,s[3]=(p*S-d*P-f*b)*B,s[4]=(c*A-a*R-u*T)*B,s[5]=(r*R-o*A+i*T)*B,s[6]=(g*v-m*P-_*w)*B,s[7]=(h*P-p*v+f*w)*B,s[8]=(a*E-l*A+u*C)*B,s[9]=(n*A-r*E-i*C)*B,s[10]=(m*S-x*v+_*y)*B,s[11]=(d*v-h*S-f*y)*B,s[12]=(l*T-a*M-c*C)*B,s[13]=(r*M-n*T+o*C)*B,s[14]=(x*w-m*b-g*y)*B,s[15]=(h*b-d*w+p*y)*B),s}function Me(e,t,s,r,n,o,i){const a=(e-r)/o*2-1,l=(t-n)/i*2-1,c=s[0]*a+s[4]*l+s[12],u=s[1]*a+s[5]*l+s[13],h=s[3]*a+s[7]*l+s[15];return{x:c/h,y:u/h}}function Ee(e,t,s,r,n,o,i,a){return e>=s-n*i&&e<=s+n*(1-i)&&t>=r-o*a&&t<=r+o*(1-a)}function Re(e,t,s,r,n,o,i){if(!e.has(t,ve)||!e.has(t,z))return null;const a=e.get(t,ve),l=e.get(t,z),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return Te(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,s,r,n,o,i)}function Be(e,t){return(s,r,n,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Pe]);if(0!==l.length)try{!function(e,t,s,r,n,o,i,a,l){const c=new Set;for(const e of r){t.get(e,Pe).enabled&&c.add(e)}const u=[];for(const e of r){if(!c.has(e))continue;let s=!0,r=e;for(;t.has(r,j);){const e=t.get(r,j);if(c.has(e.entity)){s=!1;break}r=e.entity}s&&u.push(e)}function h(r,u){const d=e.getChildEntities(s,r);for(const s of d){let r=u;if(c.has(s)){const e=Re(t,s,n,o,i,a,l);e&&(r=Ce(u,e))}e.renderer_setEntityClipRect(s,r.x,r.y,r.w,r.h),h(s,r)}}for(const e of u){const s=Re(t,e,n,o,i,a,l);s&&h(e,s)}}(e,t,s,l,r,n,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class Fe{build(e){if(!e.wasmModule)return;const t=e.pipeline_;t&&t.setMaskProcessor(Be(e.wasmModule,e.world))}}const Ie=new Fe,Ue=B("Interactable",{enabled:!0}),We=B("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var ke;exports.ButtonState=void 0,(ke=exports.ButtonState||(exports.ButtonState={}))[ke.Normal=0]="Normal",ke[ke.Hovered=1]="Hovered",ke[ke.Pressed=2]="Pressed",ke[ke.Disabled=3]="Disabled";const De=B("Button",{state:exports.ButtonState.Normal,transition:null});class ze{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const Le=K(new ze,"UIEvents"),He=K({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo"),$e=new Float32Array(16);class Oe{build(e){const t=e.world,s=new ze;e.insertResource(Le,s);let r=null,n=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,ae([J(he),J(He)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([We]);for(const e of i){const s=t.get(e,We);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a="undefined"!=typeof window&&window.devicePixelRatio||1,l=e.mouseX*a,c=o.screenH-e.mouseY*a;Ae(o.viewProjection,$e);const u=Me(l,c,$e,o.vpX,o.vpY,o.vpW,o.vpH),h=t.getEntitiesWithComponents([Ue,ve,z]);let d=null,p=-1/0;for(const e of h){t.has(e,We)||t.insert(e,We);if(!t.get(e,Ue).enabled)continue;const s=t.get(e,z),r=t.get(e,ve),n=r.size.x*s.scale.x,o=r.size.y*s.scale.y;if(Ee(u.x,u.y,s.position.x,s.position.y,n,o,r.pivot.x,r.pivot.y)){let s=0;t.has(e,L)&&(s=t.get(e,L).layer),s>=p&&(p=s,d=e)}}if(r!==d){if(null!==r&&t.valid(r)&&t.has(r,We)){t.get(r,We).hovered=!1,s.emit(r,"hover_exit")}if(null!==d){t.get(d,We).hovered=!0,s.emit(d,"hover_enter")}r=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,We);e.pressed=!0,e.justPressed=!0,n=d,s.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==n){if(t.valid(n)&&t.has(n,We)){const e=t.get(n,We);e.pressed=!1,e.justReleased=!0,s.emit(n,"release"),n===r&&s.emit(n,"click")}n=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(exports.Schedule.Update,ae([],()=>{const e=t.getEntitiesWithComponents([De]);for(const s of e){if(t.has(s,Ue)||t.insert(s,Ue,{enabled:!0}),!t.has(s,We))continue;const e=t.get(s,We),r=t.get(s,De),n=t.get(s,Ue),o=r.state;if(n.enabled?e.pressed?r.state=exports.ButtonState.Pressed:e.hovered?r.state=exports.ButtonState.Hovered:r.state=exports.ButtonState.Normal:r.state=exports.ButtonState.Disabled,o!==r.state&&r.transition&&t.has(s,L)){const e=t.get(s,L),n=r.transition;switch(r.state){case exports.ButtonState.Normal:e.color={...n.normalColor};break;case exports.ButtonState.Hovered:e.color={...n.hoveredColor};break;case exports.ButtonState.Pressed:e.color={...n.pressedColor};break;case exports.ButtonState.Disabled:e.color={...n.disabledColor}}t.insert(s,L,e)}}},{name:"ButtonSystem"}))}}const je=new Oe,Ne=F("ScreenSpace");function Ve(e,t,s,r,n,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,h=o.bottom+t.y*a;let d,p,f,m;if(l===c&&u===h){const e=l+s.x,t=u+s.y,r=.5*n.x,o=.5*n.y;d=e-r,p=t-o,f=e+r,m=t+o}else d=l+s.x,p=u+s.y,f=c+r.x,m=h+r.y;return{centerX:.5*(d+f),centerY:.5*(p+m),width:f-d,height:m-p,rect:{left:d,bottom:p,right:f,top:m}}}function Xe(e,t,s,r,n,o){if(!e.has(t,ve))return;const i=e.get(t,ve),a=Ve(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,s);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,D);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-r,l.position.y=a.centerY-n),e.insert(t,D,l),!e.has(t,N))return;const c=e.get(t,N);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&Xe(e,t,a.rect,a.centerX,a.centerY,!1)}class Ge{build(e){const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,ae([J(He)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},r=.5*(s.left+s.right),n=.5*(s.bottom+s.top),o=t.getEntitiesWithComponents([Ne,ve,D]);for(const e of o)Xe(t,e,s,r,n,!0)},{name:"UILayoutSystem"}))}}const Ye=new Ge;var qe;function Ke(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(qe=exports.BlendMode||(exports.BlendMode={}))[qe.Normal=0]="Normal",qe[qe.Additive=1]="Additive",qe[qe.Multiply=2]="Multiply",qe[qe.Screen=3]="Screen",qe[qe.PremultipliedAlpha=4]="PremultipliedAlpha";let Je=null,Qe=null,Ze=1;const et=new Map;function tt(e){Je=e,Qe=e.getResourceManager(),ht()}function st(){0!==it&&Je&&(Je._free(it),it=0),et.clear(),Ze=1,ot=!1,Qe=null,Je=null}function rt(){if(!Qe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Qe}const nt={createShader:(e,t)=>rt().createShader(e,t),releaseShader(e){e>0&&rt().releaseShader(e)},create(e){const t=Ze++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,r]of Object.entries(e.uniforms))s.uniforms.set(t,r);return et.set(t,s),t},get:e=>et.get(e),setUniform(e,t,s){const r=et.get(e);r&&r.uniforms.set(t,s)},getUniform(e,t){const s=et.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=et.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=et.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=et.get(e);s&&(s.depthTest=t)},getShader(e){const t=et.get(e);return t?.shader??0},release(e){et.delete(e)},isValid:e=>et.has(e),createFromAsset(e,t){const s={};for(const[t,r]of Object.entries(e.properties))if("number"==typeof r)s[t]=r;else if("object"==typeof r&&null!==r){const e=r;"a"in e?s[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(s[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:s,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=et.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Ze++,r={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return et.set(s,r),s},toAssetData(e,t){const s=et.get(e);if(!s)return null;const r={};for(const[e,t]of s.uniforms)r[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:s.blendMode,depthTest:s.depthTest,properties:r}},getUniforms(e){const t=et.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let ot=!1,it=0;const at=4096,lt=new Map;let ct=null;function ut(e){const t=(0===it&&Je&&(it=Je._malloc(at)),it);if(0===t||!Je)return{ptr:0,count:0};let s=0,r=0;const n=Je.HEAPU8,o=Je.HEAPU32,i=Je.HEAPF32;for(const[a,l]of e){if(s+128>at)break;let e=lt.get(a);e||(ct||(ct=new TextEncoder),e=ct.encode(a),lt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+s>>2]=c,s+=4,n.set(e,t+s),s+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+s>>2]=h,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=d[e],s+=4;r++}return{ptr:t,count:r}}function ht(){if(!Je||ot)return;Je.materialDataProvider=(e,t,s,r,n)=>{const o=et.get(e);if(!o)return Je.HEAPU32[t>>2]=0,Je.HEAPU32[s>>2]=0,Je.HEAPU32[r>>2]=0,void(Je.HEAPU32[n>>2]=0);Je.HEAPU32[t>>2]=o.shader,Je.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=ut(o.uniforms);Je.HEAPU32[r>>2]=i,Je.HEAPU32[n>>2]=a},ot=!0}const dt={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 pt{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const s=this.pending_.get(e);if(s)return s;const r=this.loadInternal(e);this.pending_.set(e,r);try{const t=await r;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(nt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())nt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await o(t))throw new Error(`Material file not found: ${t}`);const s=await n(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const r=JSON.parse(s);if("material"!==r.type)throw new Error(`Invalid material file type: ${r.type}`);const i=this.resolveShaderPath(e,r.shader),a=await this.shaderLoader_.load(i);return{handle:nt.createFromAsset(r,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}function ft(e,t){const s=new Map;for(const r of t.entities){const t=e.spawn();s.set(r.id,t),e.insert(t,G,{value:r.name});for(const s of r.components)xt(e,t,s)}for(const r of t.entities)if(null!==r.parent){const t=s.get(r.id),n=s.get(r.parent);void 0!==t&&void 0!==n&&e.setParent(t,n)}return s}async function mt(e,t,s){const r=new Map,n=s?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();r.set(i.id,t),e.insert(t,G,{value:i.name});for(const r of i.components){if("Sprite"===r.type&&n){const e=r.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,r=t.startsWith("data:")?t:s?.assetBaseUrl?`${s.assetBaseUrl}/${t}`:`/${t}`;try{const s=await n.loadTexture(r);e.texture=s.handle,o.set(t,r)}catch(t){console.warn(`Failed to load texture: ${r}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,s?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("BitmapText"===r.type&&n){const e=r.data;if("string"==typeof e.font&&e.font)try{const t=await n.loadBitmapFont(e.font,s?.assetBaseUrl);e.font=t}catch(t){console.warn(`Failed to load bitmap font: ${e.font}`,t),e.font=0}}if("SpineAnimation"===r.type&&n){const e=r.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await n.loadSpine(t,o,s?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,s?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}xt(e,t,r)}}for(const s of t.entities)if(null!==s.parent){const t=r.get(s.id),n=r.get(s.parent);void 0!==t&&void 0!==n&&e.setParent(t,n)}if(n&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&n.setTextureMetadataByPath(t,s.sliceBorder)}return r}function xt(e,t,s){const r=s.data;switch(s.type){case"LocalTransform":e.insert(t,D,r);break;case"Sprite":e.insert(t,L,r);break;case"Camera":e.insert(t,H,r);break;case"Canvas":e.insert(t,$,r);break;case"Text":e.insert(t,ye,r);break;case"BitmapText":e.insert(t,V,r);break;case"SpineAnimation":e.insert(t,X,r);break;case"UIRect":{const s=r;s.anchor&&!s.anchorMin&&(s.anchorMin={...s.anchor},s.anchorMax={...s.anchor},delete s.anchor),e.insert(t,ve,s);break}case"UIMask":e.insert(t,Pe,r);break;case"RigidBody":e.insert(t,S,r);break;case"BoxCollider":e.insert(t,P,r);break;case"CircleCollider":e.insert(t,C,r);break;case"CapsuleCollider":e.insert(t,T,r);break;default:{const n=I(s.type);n?e.insert(t,n,r):console.warn(`Unknown component type: ${s.type}`);break}}}class gt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const s=this.cache_.get(e);if(void 0!==s)return s;const r=this.pending_.get(e);if(r)return r;const n=t();this.pending_.set(e,n);try{const t=await n;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class _t{constructor(e){this.textureCache_=new gt,this.shaderCache_=new gt,this.jsonCache_=new gt,this.textCache_=new gt,this.binaryCache_=new gt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new gt,this.embedded_=new Map,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.module_=e,this.canvas_=i(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new pt(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s)}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const r=this.textureCacheKey(e,s),n=this.textureCache_.get(r);n&&(t.releaseTexture(n.handle),this.textureCache_.delete(r))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);this.textureCache_.clear(),this.fontCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}async loadSpine(e,t,s){const r=`${e}:${t}`;if(this.loadedSpines_.has(r))return{success:!0};try{const n=this.resolveUrl(t,s),o=await this.fetchText(n);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o);for(const e of a){const t=i?`${i}/${e}`:e,r=this.resolveUrl(t,s);try{const e=await this.loadTextureRaw(r);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,s),c=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);return this.writeToVirtualFS(e,c)?(this.loadedSpines_.add(r),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>e.endsWith(".bmfont")?this.loadBmfontAsset(s):this.loadFntFile(s))}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),r="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!r)throw new Error("Invalid bmfont asset: no fnt file specified");const n=s?`${s}/${r}`:r;return this.loadFntFile(n)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const r=s[1],n=e.substring(0,e.lastIndexOf("/")),o=n?`${n}/${r}`:r,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return mt(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},s=[];if(e.textures)for(const r of e.textures)s.push(this.loadTexture(r).then(e=>{t.textures.set(r,e)}));if(e.materials)for(const r of e.materials)s.push(this.loadMaterial(r).then(e=>{t.materials.set(r,e)}));if(e.spine)for(const r of e.spine){const e=`${r.skeleton}:${r.atlas}`;s.push(this.loadSpine(r.skeleton,r.atlas,r.baseUrl).then(s=>{t.spine.set(e,s)}))}if(e.json)for(const r of e.json)s.push(this.loadJson(r).then(e=>{t.json.set(r,e)}));if(e.text)for(const r of e.text)s.push(this.loadText(r).then(e=>{t.text.set(r,e)}));if(e.binary)for(const r of e.binary)s.push(this.loadBinary(r).then(e=>{t.binary.set(r,e)}));return await Promise.all(s),t}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups)){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}async loadByAddress(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path);default:return this.loadBinary(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const r of e)switch(r.type){case"texture":s.push(this.loadTexture(r.path).then(e=>{t.textures.set(r.path,e)}));break;case"material":s.push(this.loadMaterial(r.path).then(e=>{t.materials.set(r.path,e)}));break;case"json":s.push(this.loadJson(r.path).then(e=>{t.json.set(r.path,e)}));break;case"text":s.push(this.loadText(r.path).then(e=>{t.text.set(r.path,e)}));break;default:s.push(this.loadBinary(r.path).then(e=>{t.binary.set(r.path,e)}))}return await Promise.all(s),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,r=this.embedded_.get(s)??s;return new Promise((s,n)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:s,height:r}=e,n=this.getWebGL2Context();return n?this.createTextureWebGL2(n,e,s,r,t):this.createTextureFallback(e,s,r,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,r,n){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,n?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,r),width:s,height:r}}createTextureFallback(e,t,s,r){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const n=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(n.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,s,a,o.length,1,r);return this.module_._free(a),{handle:l,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const r=255/s;e[t]=Math.min(255,Math.round(e[t]*r)),e[t+1]=Math.min(255,Math.round(e[t+1]*r)),e[t+2]=Math.min(255,Math.round(e[t+2]*r))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e;if(!await o(t))throw new Error(`Shader file not found: ${e}`);const s=await n(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:i}=this.parseEsShader(s);if(!r||!i)throw new Error(`Invalid shader format: ${e}`);return nt.createShader(r,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const s=await n(t);return JSON.parse(s)}const r=await s(e);if(!r.ok)throw new Error(`Failed to fetch JSON: ${e} (${r.status})`);return r.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):n(t)}const r=await s(e);if(!r.ok)throw new Error(`Failed to fetch text: ${e} (${r.status})`);return r.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):r(t)}const n=await s(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const r=s.split("/").filter(e=>e);let n="";for(const e of r){n=n?`${n}/${e}`:e;try{t.analyzePath(n).exists||t.mkdir(n)}catch{try{t.mkdir(n)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const yt=K(null,"Assets");class wt{build(e){const t=e.wasmModule;t?e.insertResource(yt,new _t(t)):console.warn("AssetPlugin: No WASM module available")}}const vt=new wt;let bt=null,St=0,Pt=0,Ct=0;const Tt=new Float32Array(256);function At(e){bt=e,St=bt._malloc(64),Pt=bt._malloc(64),Ct=bt._malloc(1024)}function Mt(){bt&&(St&&(bt._free(St),St=0),Pt&&(bt._free(Pt),Pt=0),Ct&&(bt._free(Ct),Ct=0)),bt=null}function Et(){if(!bt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return bt}const Rt={r:1,g:1,b:1,a:1},Bt={begin(e){const t=Et();t.HEAPF32.set(e,St/4),t.draw_begin(St)},end(){Et().draw_end()},line(e,t,s,r=1){Et().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,r)},rect(e,t,s,r=!0){Et().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,r)},rectOutline(e,t,s,r=1){Et().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,r)},circle(e,t,s,r=!0,n=32){Et().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,r,n)},circleOutline(e,t,s,r=1,n=32){Et().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,r,n)},texture(e,t,s,r=Rt){Et().draw_texture(e.x,e.y,t.x,t.y,s,r.r,r.g,r.b,r.a)},textureRotated(e,t,s,r,n=Rt){Et().draw_textureRotated(e.x,e.y,t.x,t.y,s,r,n.r,n.g,n.b,n.a)},setLayer(e){Et().draw_setLayer(e)},setDepth(e){Et().draw_setDepth(e)},getDrawCallCount:()=>bt?bt.draw_getDrawCallCount():0,getPrimitiveCount:()=>bt?bt.draw_getPrimitiveCount():0,setBlendMode(e){Et().draw_setBlendMode(e)},setDepthTest(e){Et().draw_setDepthTest(e)},drawMesh(e,t,s){const r=Et();r.HEAPF32.set(s,Pt/4),r.draw_mesh(e,t,Pt)},drawMeshWithMaterial(e,t,s){const r=Et(),n=nt.get(t);if(!n)return;if(Bt.setBlendMode(n.blendMode),Bt.setDepthTest(n.depthTest),0===n.uniforms.size)return void Bt.drawMesh(e,n.shader,s);r.HEAPF32.set(s,Pt/4);let o=0,i=0;for(const[e,t]of n.uniforms){const s=It(e);if(!(s<0)){if(Ke(t))Tt[o++]=10,Tt[o++]=s,Tt[o++]=t.slot??i++,Tt[o++]=t.textureId;else if("number"==typeof t)Tt[o++]=1,Tt[o++]=s,Tt[o++]=t;else if(Array.isArray(t)){Tt[o++]=t.length,Tt[o++]=s;for(let e=0;e<t.length;e++)Tt[o++]=t[e]}else"w"in t?(Tt[o++]=4,Tt[o++]=s,Tt[o++]=t.x,Tt[o++]=t.y,Tt[o++]=t.z,Tt[o++]=t.w):"z"in t?(Tt[o++]=3,Tt[o++]=s,Tt[o++]=t.x,Tt[o++]=t.y,Tt[o++]=t.z):(Tt[o++]=2,Tt[o++]=s,Tt[o++]=t.x,Tt[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(r.HEAPF32.set(Tt.subarray(0,o),Ct/4),r.draw_meshWithUniforms(e,n.shader,Pt,Ct,o)):r.draw_mesh(e,n.shader,Pt)}},Ft={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function It(e){return Ft[e]??-1}var Ut;exports.DataType=void 0,(Ut=exports.DataType||(exports.DataType={}))[Ut.Float=1]="Float",Ut[Ut.Float2=2]="Float2",Ut[Ut.Float3=3]="Float3",Ut[Ut.Float4=4]="Float4",Ut[Ut.Int=5]="Int",Ut[Ut.Int2=6]="Int2",Ut[Ut.Int3=7]="Int3",Ut[Ut.Int4=8]="Int4";let Wt=null,kt=0,Dt=0,zt=0;function Lt(e){Wt=e,kt=Wt._malloc(262144),Dt=Wt._malloc(65536),zt=Wt._malloc(256)}function Ht(){Wt&&(kt&&Wt._free(kt),Dt&&Wt._free(Dt),zt&&Wt._free(zt),kt=0,Dt=0,zt=0),Wt=null}function $t(){if(!Wt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Wt}const Ot={create(e){const t=$t(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const r=e.vertices.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);t.HEAPF32.set(e.vertices,kt/4);const n=e.layout.length,o=new Int32Array(n);for(let t=0;t<n;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,zt,n).set(o),t.geometry_init(s,kt,r,zt,n,e.dynamic??!1),e.indices){const r=e.indices.length;if(4*r>65536)throw new Error(`Index data too large: ${r} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Dt,r).set(e.indices),t.geometry_setIndices16(s,Dt,r)}else{new Uint32Array(t.HEAPU8.buffer,Dt,r).set(e.indices),t.geometry_setIndices32(s,Dt,r)}}return s},updateVertices(e,t,s=0){const r=$t(),n=t.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);r.HEAPF32.set(t,kt/4),r.geometry_updateVertices(e,kt,n,s)},release(e){e>0&&$t().geometry_release(e)},isValid:e=>!(!Wt||e<=0)&&Wt.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,r=t/2;return Ot.create({vertices:new Float32Array([-s,-r,0,0,s,-r,1,0,s,r,1,1,-s,r,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],r=[];s.push(0,0,.5,.5);for(let r=0;r<=t;r++){const n=r/t*Math.PI*2,o=Math.cos(n)*e,i=Math.sin(n)*e,a=(Math.cos(n)+1)/2,l=(Math.sin(n)+1)/2;s.push(o,i,a,l)}for(let e=1;e<=t;e++)r.push(0,e,e+1);return Ot.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(r)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,r=-1/0,n=-1/0;for(const o of e)t=Math.min(t,o.x),s=Math.min(s,o.y),r=Math.max(r,o.x),n=Math.max(n,o.y);const o=[];for(const i of e){const e=(i.x-t)/(r-t),a=(i.y-s)/(n-s);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return Ot.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 jt=null;function Nt(e){jt=e}function Vt(){jt&&Gt.isInitialized()&&Gt.shutdown(),jt=null}function Xt(){if(!jt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return jt}const Gt={init:(e,t)=>Xt().postprocess_init(e,t),shutdown(){Xt().postprocess_shutdown()},resize(e,t){Xt().postprocess_resize(e,t)},addPass:(e,t)=>Xt().postprocess_addPass(e,t),removePass(e){Xt().postprocess_removePass(e)},setEnabled(e,t){Xt().postprocess_setPassEnabled(e,t)},isEnabled:e=>Xt().postprocess_isPassEnabled(e),setUniform(e,t,s){Xt().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){Xt().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){Xt().postprocess_begin()},end(){Xt().postprocess_end()},getPassCount:()=>Xt().postprocess_getPassCount(),isInitialized:()=>!!jt&&jt.postprocess_isInitialized(),setBypass(e){Xt().postprocess_setBypass(e)},isBypassed:()=>!jt||jt.postprocess_isBypassed(),createBlur:()=>nt.createShader(Yt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>nt.createShader(Yt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>nt.createShader(Yt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>nt.createShader(Yt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},Yt="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var qt;exports.RenderStage=void 0,(qt=exports.RenderStage||(exports.RenderStage={}))[qt.Background=0]="Background",qt[qt.Opaque=1]="Opaque",qt[qt.Transparent=2]="Transparent",qt[qt.Overlay=3]="Overlay";let Kt=null,Jt=0;function Qt(e){Kt=e,Jt=Kt._malloc(64)}function Zt(){Kt&&Jt&&(Kt._free(Jt),Jt=0),Kt=null}const es={init(e,t){Kt?.renderer_init(e,t)},resize(e,t){Kt?.renderer_resize(e,t)},begin(e,t){Kt&&Jt&&(Kt.HEAPF32.set(e,Jt/4),Kt.renderer_begin(Jt,t??0))},flush(){Kt?.renderer_flush()},end(){Kt?.renderer_end()},submitSprites(e){Kt&&Kt.renderer_submitSprites(e._cpp)},submitBitmapText(e){Kt&&Kt.renderer_submitBitmapText(e._cpp)},submitSpine(e){Kt&&Kt.renderer_submitSpine?.(e._cpp)},setStage(e){Kt?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Kt?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Kt?.renderer_releaseTarget(e)},getTargetTexture:e=>Kt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Kt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,r){Kt?.renderer_setClearColor?.(e,t,s,r)},setViewport(e,t,s,r){Kt?.renderer_setViewport(e,t,s,r)},setScissor(e,t,s,r,n){Kt?.renderer_setScissor(e,t,s,r,n)},clearBuffers(e){Kt?.renderer_clearBuffers(e)},getStats:()=>Kt?{drawCalls:Kt.renderer_getDrawCalls(),triangles:Kt.renderer_getTriangles(),sprites:Kt.renderer_getSprites(),text:Kt.renderer_getText(),spine:Kt.renderer_getSpine?.()??0,meshes:Kt.renderer_getMeshes(),culled:Kt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let ts=null;function ss(e){ts=e}function rs(){ts=null}const ns={enable(){ts?.gl_enableErrorCheck(!0)},disable(){ts?.gl_enableErrorCheck(!1)},check:e=>ts?.gl_checkErrors(e)??0,diagnose(){ts?.renderer_diagnose()}},os=new Map;function is(e){os.delete(e)}class as{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}setSpineRenderer(e){this.spineRenderer_=e}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:s,width:r,height:n,elapsed:o}=e;r===this.lastWidth_&&n===this.lastHeight_||(es.resize(r,n),Gt.isInitialized()&&Gt.getPassCount()>0&&Gt.resize(r,n),this.lastWidth_=r,this.lastHeight_=n),es.setViewport(0,0,r,n),es.clearBuffers(3),es.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,r,n),es.submitSprites(t),es.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):es.submitSpine(t),es.flush(),this.executeDrawCallbacks(s,o),es.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:r,clearFlags:n,elapsed:o}=e;es.setViewport(r.x,r.y,r.w,r.h),es.setScissor(r.x,r.y,r.w,r.h,!0),es.clearBuffers(n),es.setScissor(0,0,0,0,!1),es.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,r.x,r.y,r.w,r.h),es.submitSprites(t),es.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):es.submitSpine(t),es.flush(),this.executeDrawCallbacks(s,o),es.end()}executeDrawCallbacks(e,t){const s=os;if(s.size>0){Bt.begin(e);const r=[];for(const[e,n]of s.entries())try{n(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),r.push(e)}Bt.end();for(const e of r)is(e)}}}class ls{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=a(),t=e-this.lastTime_;this.lastTime_=e;const s=t/1e3;for(this.updateTime(s),this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate);this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),requestAnimationFrame(this.mainLoop)},this.world_=new me,this.resources_=new Z;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new ls}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new ce(this.world_,this.resources_),this.resources_.insert(ee,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1,rs(),Zt(),Vt(),Ht(),st(),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(ee);t.delta=e,t.elapsed+=e,t.frameCount++}}const cs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function us(e,t,s,r,n){const o=e*t/s,i=e;switch(r){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=n;return Math.pow(o,1-e)*Math.pow(i,e)}}}const hs=new Float32Array(16);function ds(e,t,s,r,n,o){const i=hs;i.fill(0);const a=t-e,l=r-s,c=o-n;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(r+s)/l,i[14]=-(o+n)/c,i[15]=1,i}const ps=new Float32Array(16);function fs(e,t,s,r){const n=ps;n.fill(0);const o=1/Math.tan(e/2),i=s-r;return n[0]=o/t,n[5]=o,n[10]=(r+s)/i,n[11]=-1,n[14]=2*r*s/i,n}const ms=new Float32Array(16);function xs(e,t,s){const r=ms;return r[0]=1,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=1,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=1,r[11]=0,r[12]=-e,r[13]=-t,r[14]=-s,r[15]=1,r}function gs(e,t){const s=new Float32Array(16);for(let r=0;r<4;r++)for(let n=0;n<4;n++)s[4*n+r]=e[0+r]*t[4*n+0]+e[4+r]*t[4*n+1]+e[8+r]*t[4*n+2]+e[12+r]*t[4*n+3];return s}async function _s(e,t){if(t)return t();return(0,(await import(e)).default)()}const ys=K({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),ws=K(null,"PhysicsAPI");function vs(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function bs(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Ss{constructor(e,t={},s){this.wasmUrl_=e,this.factory_=s,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(ys,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,r=_s(this.wasmUrl_,this.factory_).then(r=>{r._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const n=function(e){const t=e.world.getEntitiesWithComponents([$]);for(const s of t){const t=e.world.get(s,$);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/n,i=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,ae([J(ee)],a=>{const l=i.getEntitiesWithComponents([S,D,z]),c=new Set;for(const n of l){c.add(n);const a=i.get(n,S),l=i.get(n,z);if(t.has(n)){const e=s.get(n);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(r._physics_updateBodyProperties(n,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=vs(l.rotation);r._physics_createBody(n,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Ps(e,r,n),t.add(n),s.set(n,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===A.Kinematic){const e=vs(l.rotation);r._physics_setBodyTransform(n,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(r._physics_destroyBody(e),t.delete(e),s.delete(e));r._physics_step(a.delta),function(e,t,s){const r=t._physics_getDynamicBodyCount();if(0===r)return;const n=t._physics_getDynamicBodyTransforms(),o=n>>2;for(let n=0;n<r;n++){const r=o+4*n,i=t.HEAPU32[r],a=t.HEAPF32[r+1]*s,l=t.HEAPF32[r+2]*s,c=t.HEAPF32[r+3];if(!e.world.valid(i))continue;const u=e.world.get(i,D);if(!u)continue;let h=a,d=l,p=c;if(e.world.has(i,j)){const t=e.world.get(i,j);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,z)){const s=e.world.get(t.entity,z),r=vs(s.rotation),n=a-s.position.x,o=l-s.position.y,i=Math.cos(-r),u=Math.sin(-r);h=(n*i-o*u)/(0!==s.scale.x?s.scale.x:1),d=(n*u+o*i)/(0!==s.scale.y?s.scale.y:1),p=c-r}}u.position.x=h,u.position.y=d;const f=bs(p);u.rotation.w=f.w,u.rotation.x=f.x,u.rotation.y=f.y,u.rotation.z=f.z,e.world.insert(i,D,u)}}(e,r,n),function(e,t,s){t._physics_collectEvents();const r=[],n=t._physics_getCollisionEnterCount();if(n>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<n;o++){const n=e+6*o;r.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1],normalX:t.HEAPF32[n+2],normalY:t.HEAPF32[n+3],contactX:t.HEAPF32[n+4]*s,contactY:t.HEAPF32[n+5]*s})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<i;s++){const r=e+2*s;o.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const r=e+2*s;a.push({sensorEntity:t.HEAPU32[r],visitorEntity:t.HEAPU32[r+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const r=e+2*s;c.push({sensorEntity:t.HEAPU32[r],visitorEntity:t.HEAPU32[r+1]})}}e.insertResource(ys,{collisionEnters:r,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,r,n)},{name:"PhysicsSystem"})),e.__physicsModule=r,e.insertResource(ws,Cs._fromModule(r)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=r}}function Ps(e,t,s){const r=e.world;if(r.has(s,P)){const e=r.get(s,P);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(r.has(s,C)){const e=r.get(s,C);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(r.has(s,T)){const e=r.get(s,T);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Cs{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(Cs.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function Ts(e,t,s=!0){const r=e.getResourceManager(),n=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,n);const o=r.createTexture(t.width,t.height,n,t.pixels.length,1,s);return e._free(n),o}function As(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function Ms(e,t,s,r){const n=e.scale.x*t*(s?-1:1),o=e.scale.y*t*(r?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,h=a+a,d=l+l,p=c+c,f=a*h,m=a*d,x=a*p,g=l*d,_=l*p,y=c*p,w=u*h,v=u*d,b=u*p;return new Float32Array([(1-(g+y))*n,(m+b)*n,(x-v)*n,0,(m-b)*o,(1-(f+y))*o,(_+w)*o,0,(x+v)*i,(_-w)*i,(1-(f+g))*i,0,e.position.x,e.position.y,e.position.z,1])}async function Es(e,t,s,r,n,o,i){const a=await async function(e,t,s){const r={};for(const n of t.entities)for(const t of n.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const n=t.data.texture;if(void 0!==r[n])continue;try{r[n]=Ts(e,await s.loadPixels(n))}catch{r[n]=0}}return r}(t,s,r);!function(e,t,s){if(!t.textureMetadata)return;const r=e.getResourceManager();for(const e in t.textureMetadata){const n=s[e];if(n&&n>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;r.setTextureMetadata(n,e.left,e.right,e.top,e.bottom)}}}}(t,s,a);let l={},c=null;if(n&&(c=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(n),l=await async function(e,t,s,r,n){const o={};for(const i of r.entities)for(const r of i.components){if("SpineAnimation"!==r.type||!r.data)continue;const i=r.data.skeletonPath,a=r.data.atlasPath;if(!i||!a)continue;const l=n.resolvePath(i),c=n.resolvePath(a);try{const r=n.readText(a),u=l.endsWith(".skel");let h,d;if(u){const e=n.readBinary(i);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=n.readText(i),s=(new TextEncoder).encode(e);d=s.length,h=t._malloc(d+1),t.HEAPU8.set(s,h),t.HEAPU8[h+d]=0}const p=s.loadSkeleton(h,d,r,r.length,u);if(t._free(h),p<0)continue;o[i]=p;const f=As(r),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const r=m+"/"+f[t];try{const o=n.loadPixelsRaw?await n.loadPixelsRaw(r):await n.loadPixels(r),i=Ts(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,n,c,s,r)),o){new Ss("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const u=function(e,t){const s={},r={};for(const n of e.entities)for(const e of n.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const n=e.data.material;if(void 0===s[n])try{const e=JSON.parse(t.readText(n));if(!e.vertexSource||!e.fragmentSource){s[n]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=r[o];i||(i=nt.createShader(e.vertexSource,e.fragmentSource),r[o]=i),s[n]=nt.createFromAsset(e,i)}catch{s[n]=0}}return s}(s,r),h=ft(e.world,s);if(function(e,t,s,r){for(const n of t.entities){const t=r.get(n.id);if(void 0!==t)for(const r of n.components)if("Sprite"===r.type&&r.data.texture&&"string"==typeof r.data.texture){const n=e.get(t,L);n&&(n.texture=s[r.data.texture]||0,e.insert(t,L,n))}}}(e.world,s,a,h),function(e,t,s,r){for(const n of t.entities){const t=r.get(n.id);if(void 0!==t)for(const r of n.components){if(!r.data||"string"!=typeof r.data.material||!r.data.material)continue;const n=s[r.data.material]||0;if(n)if("Sprite"===r.type){const s=e.get(t,L);s&&(s.material=n,e.insert(t,L,s))}else if("SpineAnimation"===r.type){const s=e.get(t,X);s&&(s.material=n,e.insert(t,X,s))}}}}(e.world,s,u,h),n&&c){const r=function(e,t,s,r){const n={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=s[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=r.get(o.id);void 0!==l&&(n[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return n}(c,s,l,h);!function(e,t,s,r,n){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in n){const o=Number(e),i=n[e],a=c.has(o,X)?c.get(o,X):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&r.update(i,l*h);let d=0;if(c.has(o,z)){const e=Ms(c.get(o,z),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const p=r.getMeshBatchCount(i);for(let e=0;e<p;e++){const n=r.getMeshBatchVertexCount(i,e),o=r.getMeshBatchIndexCount(i,e);if(!n||!o)continue;const a=8*n*4,l=2*o,c=s._malloc(a),u=s._malloc(l),h=s._malloc(4),p=s._malloc(4);r.getMeshBatchData(i,e,c,u,h,p);const f=s.HEAPU32[h>>2],m=s.HEAPU32[p>>2],x=new Float32Array(s.HEAPF32.buffer,c,8*n),g=new Uint16Array(s.HEAPU8.buffer,u,o),_=t._malloc(a),y=t._malloc(l);t.HEAPF32.set(x,_>>2),new Uint16Array(t.HEAPU8.buffer,y,o).set(g),t.renderer_submitTriangles(_,n,y,o,f,m,d),t._free(_),t._free(y),s._free(c),s._free(u),s._free(h),s._free(p)}d&&t._free(d)}})}(e,t,n,c,r)}}class Rs{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const r=e.data.skeletonPath,n=e.data.atlasPath;r&&(r.endsWith(".skel")?s.add(r):t.add(r)),n&&t.add(n)}"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(r)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),r=await s.blob(),n=await createImageBitmap(r),o=new OffscreenCanvas(n.width,n.height).getContext("2d");o.drawImage(n,0,0);const i=o.getImageData(0,0,n.width,n.height);return n.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Bs={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=es.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:es.getTargetTexture(s),width:e.width,height:e.height}},release(e){es.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(es.releaseRenderTarget(e._handle),Bs.create({width:t,height:s,depth:!0})),begin(e,t){es.begin(t,e._handle)},end(){es.end()},getDepthTexture:e=>es.getTargetDepthTexture(e._handle)};let Fs=!1;y||(y=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),r={method:t?.method??"GET",headers:t?.headers,body:t?.body},n=await l(s,r);return{ok:n.ok,status:n.status,statusText:n.statusText,headers:new Headers(n.headers),json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return c(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let r=0;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);n<128?s[r++]=n:n<2048?(s[r++]=192|n>>6,s[r++]=128|63&n):n>=55296&&n<=56319?(n=e.charCodeAt(++t)-56320+(n-55296<<10)+65536,s[r++]=240|n>>18,s[r++]=128|n>>12&63,s[r++]=128|n>>6&63,s[r++]=128|63&n):(s[r++]=224|n>>12,s[r++]=128|n>>6&63,s[r++]=128|63&n)}return s.subarray(0,r)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const r=t[e];if(r<128)s+=String.fromCharCode(r),e++;else if(192==(224&r))s+=String.fromCharCode((31&r)<<6|63&t[e+1]),e+=2;else if(224==(240&r))s+=String.fromCharCode((15&r)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const n=((7&r)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(n>>10),56320+(1023&n)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=w,exports.App=ls,exports.AssetPlugin=wt,exports.AssetServer=_t,exports.Assets=yt,exports.AsyncCache=gt,exports.BitmapText=V,exports.BodyType=A,exports.BoxCollider=P,exports.Button=De,exports.Camera=H,exports.Canvas=$,exports.CapsuleCollider=T,exports.Children=N,exports.CircleCollider=C,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=ne,exports.Draw=Bt,exports.EntityCommands=re,exports.GLDebug=ns,exports.Geometry=Ot,exports.INVALID_ENTITY=0,exports.INVALID_FONT=0,exports.INVALID_TEXTURE=v,exports.Input=he,exports.InputPlugin=de,exports.InputState=ue,exports.Interactable=Ue,exports.LocalTransform=D,exports.Material=nt,exports.MaterialLoader=pt,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=G,exports.Parent=j,exports.Physics=Cs,exports.PhysicsEvents=ys,exports.PhysicsPlugin=Ss,exports.PostProcess=Gt,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await s(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),r=new Rs(this.baseUrl_);await r.prefetch(t);let n=null;const o=this.app_.__spineInitPromise;if(o){n=(await o).controller.raw}await Es(this.app_,this.app_.wasmModule,t,r,n),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([H]);for(const r of s){if(e.get(r,H).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1920/1080;const r=e.getEntitiesWithComponents([$]);for(const n of r){const r=e.get(n,$);if(r.designResolution){const e=r.pixelsPerUnit||100;t=r.designResolution.y/2/e,s=r.designResolution.x/r.designResolution.y;break}}const n=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(n,D,o);const i={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3};e.insert(n,H,i)}}},exports.Query=function(...e){return function(e,t=[],s=[]){const r=[];return e.forEach((e,t)=>{te(e)&&r.push(t)}),{_type:"query",_components:e,_mutIndices:r,_with:t,_without:s}}(e)},exports.QueryInstance=se,exports.RenderPipeline=as,exports.RenderTexture=Bs,exports.Renderer=es,exports.Res=J,exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.RigidBody=S,exports.ScreenSpace=Ne,exports.ShaderSources=dt,exports.SpineAnimation=X,exports.Sprite=L,exports.SystemRunner=ce,exports.Text=ye,exports.TextPlugin=be,exports.TextRenderer=we,exports.Time=ee,exports.UICameraInfo=He,exports.UIEventQueue=ze,exports.UIEvents=Le,exports.UIInteraction=We,exports.UIInteractionPlugin=Oe,exports.UILayoutPlugin=Ge,exports.UIMask=Pe,exports.UIMaskPlugin=Fe,exports.UIRect=ve,exports.Velocity=O,exports.WebAssetProvider=Rs,exports.World=me,exports.WorldTransform=z,exports.addStartupSystem=function(e){le().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){le().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){le().push({schedule:e,system:t})},exports.assetPlugin=vt,exports.clearDrawCallbacks=function(){os.clear()},exports.clearUserComponents=function(){R().clear()},exports.color=(e=1,t=1,s=1,r=1)=>({r:e,g:t,b:s,a:r}),exports.computeUIRectLayout=Ve,exports.createMaskProcessor=Be,exports.createWebApp=function(e,t){const s=ls.new(),r=new e.Registry;s.connectCpp(r,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),At(e),tt(e),Lt(e),Nt(e),Qt(e),ss(e);const n=new as;s.pipeline_=n;let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));s.insertResource(He,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=i(),c=e.registry_getCanvasEntity(r);if(c>=0){const e=r.getCanvas(c).backgroundColor;es.setClearColor(e.r,e.g,e.b,e.a)}const u=(a()-o)/1e3;es.resize(t,l),Gt.isInitialized()&&Gt.getPassCount()>0&&!Gt.isBypassed()&&Gt.resize(t,l);const h=function(e,t,s,r){const n=e.registry_getCameraEntities(t);if(0===n.length)return[];const o=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),i=[];for(const e of n){const n=t.getCamera(e),a=t.getLocalTransform(e),l={x:n.viewportX,y:n.viewportY,w:n.viewportW,h:n.viewportH},c=l.w*s/(l.h*r);let u,h=0,d=0;if(1===n.projectionType){if(d=n.orthoSize,o){d=us(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}h=d*c,u=ds(-h,h,-d,d,-n.farPlane,n.farPlane)}else u=fs(n.fov*Math.PI/180,c,n.nearPlane,n.farPlane);const p=xs(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:gs(u,p),viewportRect:l,clearFlags:n.clearFlags,priority:n.priority,halfW:h,halfH:d,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}(e,r,t,l),d=s.getResource(He);if(h.length>0){const e=h[0],s=e.viewportRect;d.viewProjection.set(e.viewProjection),d.vpX=Math.round(s.x*t),d.vpY=Math.round((1-s.y-s.h)*l),d.vpW=Math.round(s.w*t),d.vpH=Math.round(s.h*l),d.screenW=t,d.screenH=l,d.worldLeft=e.cameraX-e.halfW,d.worldRight=e.cameraX+e.halfW,d.worldBottom=e.cameraY-e.halfH,d.worldTop=e.cameraY+e.halfH,d.valid=!0}else d.valid=!1;if(0===h.length)n.render({registry:{_cpp:r},viewProjection:cs,width:t,height:l,elapsed:u});else{for(const e of h){const s=e.viewportRect,o=Math.round(s.x*t),i=Math.round((1-s.y-s.h)*l),a=Math.round(s.w*t),c=Math.round(s.h*l);n.renderCamera({registry:{_cpp:r},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:c},clearFlags:e.clearFlags,elapsed:u})}es.setViewport(0,0,t,l)}}};return s.addSystemToSchedule(exports.Schedule.Last,l),s.addPlugin(vt),s.addPlugin(pe),s.addPlugin(Se),s.addPlugin(Ie),s.addPlugin(Ye),s.addPlugin(je),s},exports.defineComponent=B,exports.defineResource=K,exports.defineSystem=ae,exports.defineTag=F,exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([G]);for(const r of s){const s=e.get(r,G);if(s&&s.value===t)return r}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}},exports.getComponentDefaults=function(e){const t=Y[e];if(t)return{...t._default};const s=I(e);return s?{...s._default}:null},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=I,exports.initDrawAPI=At,exports.initGLDebugAPI=ss,exports.initGeometryAPI=Lt,exports.initMaterialAPI=tt,exports.initPostProcessAPI=Nt,exports.initRendererAPI=Qt,exports.inputPlugin=pe,exports.intersectRects=Ce,exports.invertMatrix4=Ae,exports.isBuiltinComponent=k,exports.isEditor=function(){return Fs},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!Fs},exports.isTextureRef=Ke,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=xt,exports.loadPhysicsModule=_s,exports.loadRuntimeScene=Es,exports.loadSceneData=ft,exports.loadSceneWithAssets=mt,exports.platformFetch=s,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,s){return t().instantiateWasm(e,s)},exports.platformReadFile=r,exports.platformReadTextFile=n,exports.pointInWorldRect=Ee,exports.quat=(e=1,t=0,s=0,r=0)=>({w:e,x:t,y:s,z:r}),exports.registerDrawCallback=function(e,t){os.set(e,t)},exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(yt);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=ht,exports.screenToWorld=Me,exports.setEditorMode=function(e){Fs=e},exports.shutdownDrawAPI=Mt,exports.shutdownGLDebugAPI=rs,exports.shutdownGeometryAPI=Ht,exports.shutdownMaterialAPI=st,exports.shutdownPostProcessAPI=Vt,exports.shutdownRendererAPI=Zt,exports.textPlugin=Se,exports.uiInteractionPlugin=je,exports.uiLayoutPlugin=Ye,exports.uiMaskPlugin=Ie,exports.unregisterDrawCallback=is,exports.updateCameraAspectRatio=function(e,t){const s=e.getEntitiesWithComponents([H]);for(const r of s){const s=e.get(r,H);s&&(s.aspectRatio=t,e.insert(r,H,s))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),exports.vec4=(e=0,t=0,s=0,r=1)=>({x:e,y:t,z:s,w:r}),exports.worldRectToScreen=Te,exports.wxFileExists=f,exports.wxFileExistsSync=function(e){const t=h();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=_,exports.wxLoadImage=g,exports.wxLoadImagePixels=async function(e){return _(await g(e))},exports.wxReadFile=d,exports.wxReadTextFile=p,exports.wxWriteFile=function(e,t){return new Promise((s,r)=>{h().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{r(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};//# sourceMappingURL=index.wechat.cjs.js.mapdiff --git a/desktop/public/sdk/cjs/index.wechat.js b/desktop/public/sdk/cjs/index.wechat.jsindex 40cc8dfa1..ee4758e39 100644--- a/desktop/public/sdk/cjs/index.wechat.js+++ b/desktop/public/sdk/cjs/index.wechat.js@@ -1,2 +1,2 @@-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function r(){return e?.name??null}function s(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}function f(e,t){return new Promise((n,r)=>{const s=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===s?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,r={};if(e.header)for(const t of Object.keys(e.header))r[t.toLowerCase()]=e.header[t];n({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:r,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,n="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(n).buffer)}})},fail:e=>{r(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function p(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const n=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(n,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${n}": ${t}`)}}let _=null;function m(){return _||(_=wx.getFileSystemManager()),_}function g(e){return new Promise((t,n)=>{m().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function y(e,t="utf-8"){return new Promise((n,r)=>{m().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function w(e){return new Promise(t=>{m().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function x(e){const t=m();try{return t.accessSync(e),!0}catch{return!1}}function b(e,t){return new Promise((n,r)=>{m().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{r(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}let v=null,P=null;function S(e){return new Promise((t,n)=>{const r=wx.createImage();r.onload=()=>t(r),r.onerror=t=>n(new Error(`Failed to load image: ${e}, ${t}`)),r.src=e})}function C(e){const{width:t,height:n}=e,{ctx:r}=function(e,t){return v||(v=wx.createCanvas(),v.width=e,v.height=t,P=v.getContext("2d")),(v.width<e||v.height<t)&&(v.width=Math.max(v.width,e),v.height=Math.max(v.height,t)),{canvas:v,ctx:P}}(t,n);r.clearRect(0,0,t,n),r.drawImage(e,0,0);const s=r.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(s.data.buffer)}}async function E(e){return C(await S(e))}let T=!1;const A=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return g(e)}async readTextFile(e){return y(e)}async fileExists(e){return w(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return p(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const n=wx.createCanvas();return n.width=e,n.height=t,n}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{const n=t.touches[0];n&&e.onPointerDown(0,n.clientX,n.clientY)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX,n.clientY)}),wx.onTouchEnd(()=>{e.onPointerUp(0)})}},M=0,R=4294967295,F=0,U=(e=0,t=0)=>({x:e,y:t}),B=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),I=(e=0,t=0,n=0,r=1)=>({x:e,y:t,z:n,w:r}),k=(e=1,t=1,n=1,r=1)=>({r:e,g:t,b:n,a:r}),W=(e=1,t=0,n=0,r=0)=>({w:e,x:t,y:n,z:r});function z(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const D=z("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),$=z("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),H=z("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),L=z("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),O={Static:0,Kinematic:1,Dynamic:2};let N=0;function j(e,t){const n=++N;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function V(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function X(e,t){const n=V(),r=n.get(e);if(r)return r;const s=j(e,t);return n.set(e,s),K(e,t,!1),s}function G(e){const t=V(),n=t.get(e);if(n)return n;const r=j(e,{});return t.set(e,r),K(e,{},!0),r}function Y(e){return V().get(e)}function q(){V().clear()}function K(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function J(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function Q(e){return!0===e._builtin}const Z=J("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),ee=J("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),te=J("Sprite",{texture:R,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),ne=J("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),re=J("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),se=J("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),ie=J("Parent",{entity:0}),oe=J("Children",{entities:[]}),ae=J("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:0}),ce=J("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),le={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},ue={LocalTransform:Z,WorldTransform:ee,Sprite:te,Camera:ne,Canvas:re,Velocity:se,Parent:ie,Children:oe,BitmapText:ae,SpineAnimation:ce,RigidBody:D,BoxCollider:$,CircleCollider:H,CapsuleCollider:L};function he(e){const t=ue[e];if(t)return{...t._default};const n=Y(e);return n?{...n._default}:null}let de=0;function fe(e,t){const n=++de;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function pe(e){return{_type:"res",_resource:e}}function _e(e){return{_type:"res_mut",_resource:e}}class me{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}}class ge{constructor(){this.resources_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id)}getResMut(e){return new me(this.get(e),t=>this.set(e,t))}}const ye=fe({delta:0,elapsed:0,frameCount:0},"Time");function we(e){return{_type:"mut",_component:e}}function xe(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function be(...e){return function(e,t=[],n=[]){const r=[];return e.forEach((e,t)=>{xe(e)&&r.push(t)}),{_type:"query",_components:e,_mutIndices:r,_with:t,_without:n}}(e)}class ve{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>xe(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with)}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,r=this.world_.getEntitiesWithComponents(this.allRequired_),s=n.length,i=e.length>0,o=t.length>0,a=new Array(s+1);let c=null,l=[];try{for(const u of r){if(null!==c&&i){for(let e=0;e<l.length;e++){const t=l[e];this.world_.insert(c,t.component,t.data)}l.length=0}if(o){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(u,t[n])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<s;e++)a[e+1]=this.world_.get(u,n[e]);if(i){for(let t=0;t<e.length;t++){const r=e[t];l.push({component:n[r],data:a[r+1]})}c=u}yield a}}finally{if(null!==c&&i)for(let e=0;e<l.length;e++){const t=l[e];this.world_.insert(c,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function Pe(){return{_type:"commands"}}class Se{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=Q(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Ce{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Se(this,null);return this.spawned_.push(e),e}entity(e){return new Se(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Ee;!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(Ee||(Ee={}));let Te=0;function Ae(e,t,n){const r=++Te;return{_id:Symbol(`System_${r}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${r}`}}function Me(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Re(e){Me().push({schedule:Ee.Update,system:e})}function Fe(e){Me().push({schedule:Ee.Startup,system:e})}function Ue(e,t){Me().push({schedule:e,system:t})}class Be{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Ce&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new ve(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Ce(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ie{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const ke=fe(new Ie,"Input");class We{constructor(e){this.target_=e??null}build(e){const n=new Ie;e.insertResource(ke,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,r){n.mouseX=t,n.mouseY=r,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(Ee.First,Ae([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ze=new We;function De(e){if(null==e||"object"!=typeof e||Array.isArray(e))return e;const t=e;if("r"in t&&"g"in t&&"b"in t&&"a"in t&&!("x"in t))return{x:t.r,y:t.g,z:t.b,w:t.a};const n={};for(const e of Object.keys(t)){const r=t[e];n[e]=null==r||"object"!=typeof r||Array.isArray(r)?r:De(r)}return n}class $e{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return Q(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return Q(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return Q(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){Q(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const r={...t._default,...n};if(this.cppRegistry_){const n=`add${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e,De(r))}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const n=`get${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const n=`has${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const n=`remove${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e)}insertScript(e,t,n){const r=t.create(n);return this.getStorage(t).set(e,r),r}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();let t=null,n=1/0;for(const r of e)if(!Q(r)){const e=this.tsStorage_.get(r._id),s=e?e.size:0;s<n&&(n=s,t=e??null)}const r=[],s=t?t.keys():this.entities_;for(const t of s){let n=!0;for(const r of e)if(!this.has(t,r)){n=!1;break}n&&r.push(t)}return r}}var He,Le,Oe;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(He||(He={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Le||(Le={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Oe||(Oe={}));const Ne=X("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:He.Left,verticalAlign:Le.Top,wordWrap:!0,overflow:Oe.Visible,lineHeight:1.2,dirty:!0});class je{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,r=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const s=t&&t.size.x>0&&t.size.y>0,i=s?t.size.x:0,o=s?t.size.y:0,a=e.wordWrap&&s;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=s?Math.ceil(i):h+2*u,p=s?Math.ceil(o):d+2*u;if(s&&e.overflow===Oe.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}if(r.width<f||r.height<p){const e=Math.max(r.width,this.nextPowerOf2(f)),t=Math.max(r.height,this.nextPowerOf2(p));r.width=e,r.height=t}const _=Math.round(255*e.color.r),m=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,r.width,r.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${_}, ${m}, ${g}, ${y})`,s&&e.overflow===Oe.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=c.length*l;let x;if(s)switch(e.verticalAlign){case Le.Top:x=u;break;case Le.Middle:x=(p-w)/2;break;case Le.Bottom:x=p-w-u;break;default:x=u}else x=u;let b=x;for(const t of c){let r;switch(e.align){case He.Left:r=u;break;case He.Center:r=f/2;break;case He.Right:r=f-u;break;default:r=u}n.fillText(t,r,b),b+=l}s&&e.overflow===Oe.Clip&&n.restore();const v=n.getImageData(0,0,f,p),P=new Uint8Array(v.data.buffer),S=this.module.getResourceManager(),C=this.module._malloc(P.length);this.module.HEAPU8.set(P,C);const E=S.createTexture(f,p,C,P.length,1,!0);return this.module._free(C),{textureHandle:E,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const r=this.cache.get(e);if(r){this.module.getResourceManager().releaseTexture(r.textureHandle)}const s=this.renderText(t,n);return this.cache.set(e,s),s}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,r]of this.cache)e(n)||(t.releaseTexture(r.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),r=[];for(const e of n){if(!e){r.push("");continue}let n="";for(const s of e){const e=n+s;this.ctx.measureText(e).width>t&&n?(r.push(n),n=s):n=e}n&&r.push(n)}return r.length>0?r:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),r=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,r)}return t}mapAlign(e){switch(e){case He.Left:return"left";case He.Center:return"center";case He.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const Ve=X("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class Xe{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new je(t),r=e.world;e.addSystemToSchedule(Ee.PreUpdate,Ae([],()=>{n.cleanupOrphaned(e=>r.valid(e)&&r.has(e,Ne));const e=r.getEntitiesWithComponents([Ne]);for(const t of e){const e=r.get(t,Ne);if(!e.dirty)continue;r.has(t,te)||r.insert(t,te,{texture:R,size:{x:0,y:0},color:{r:1,g:1,b:1,a:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const s=r.has(t,Ve)?r.get(t,Ve):null,i=n.renderForEntity(t,e,s),o=r.get(t,te);o.texture=i.textureHandle,o.size.x=i.width,o.size.y=i.height,o.uvOffset.x=0,o.uvOffset.y=0,o.uvScale.x=1,o.uvScale.y=1,r.insert(t,te,o),e.dirty=!1}}))}}const Ge=new Xe,Ye=X("UIMask",{enabled:!0});function qe(e,t){const n=Math.max(e.x,t.x),r=Math.max(e.y,t.y),s=Math.min(e.x+e.w,t.x+t.w),i=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:r,w:Math.max(0,s-n),h:Math.max(0,i-r)}}function Ke(e,t,n,r,s,i,o){if(!e.has(t,Ve)||!e.has(t,ee))return null;const a=e.get(t,Ve),c=e.get(t,ee),l=a.size.x*c.scale.x,u=a.size.y*c.scale.y;return function(e,t,n,r,s,i,o,a,c,l,u){const h=e-n*s,d=e+n*(1-s),f=t-r*i,p=t+r*(1-i);function _(e,t){const n=o[0]*e+o[4]*t+o[12],r=o[1]*e+o[5]*t+o[13],s=o[3]*e+o[7]*t+o[15];return[a+(n/s*.5+.5)*l,c+(r/s*.5+.5)*u]}const[m,g]=_(h,f),[y,w]=_(d,p),x=Math.min(m,y),b=Math.max(m,y),v=Math.min(g,w),P=Math.max(g,w);return{x:Math.round(x),y:Math.round(v),w:Math.round(b-x),h:Math.round(P-v)}}(c.position.x,c.position.y,l,u,.5,.5,n,r,s,i,o)}function Je(e,t){return(n,r,s,i,o,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([Ye]);if(0!==c.length)try{!function(e,t,n,r,s,i,o,a,c){const l=new Set;for(const e of r){t.get(e,Ye).enabled&&l.add(e)}const u=[];for(const e of r){if(!l.has(e))continue;let n=!0,r=e;for(;t.has(r,ie);){const e=t.get(r,ie);if(l.has(e.entity)){n=!1;break}r=e.entity}n&&u.push(e)}function h(r,u){const d=e.getChildEntities(n,r);for(const n of d){let r=u;if(l.has(n)){const e=Ke(t,n,s,i,o,a,c);e&&(r=qe(u,e))}e.renderer_setEntityClipRect(n,r.x,r.y,r.w,r.h),h(n,r)}}for(const e of u){const n=Ke(t,e,s,i,o,a,c);n&&h(e,n)}}(e,t,n,c,r,s,i,o,a)}catch(t){e.renderer_clearAllClipRects()}}}class Qe{build(e){if(!e.wasmModule)return;const t=e.pipeline_;t&&t.setMaskProcessor(Je(e.wasmModule,e.world))}}const Ze=new Qe;var et;function tt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}!function(e){e[e.Normal=0]="Normal",e[e.Additive=1]="Additive",e[e.Multiply=2]="Multiply",e[e.Screen=3]="Screen",e[e.PremultipliedAlpha=4]="PremultipliedAlpha"}(et||(et={}));let nt=null,rt=null,st=1;const it=new Map;function ot(e){nt=e,rt=e.getResourceManager(),mt()}function at(){0!==ht&&nt&&(nt._free(ht),ht=0),it.clear(),st=1,ut=!1,rt=null,nt=null}function ct(){if(!rt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return rt}const lt={createShader:(e,t)=>ct().createShader(e,t),releaseShader(e){e>0&&ct().releaseShader(e)},create(e){const t=st++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??et.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,r]of Object.entries(e.uniforms))n.uniforms.set(t,r);return it.set(t,n),t},get:e=>it.get(e),setUniform(e,t,n){const r=it.get(e);r&&r.uniforms.set(t,n)},getUniform(e,t){const n=it.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=it.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=it.get(e);return t?.blendMode??et.Normal},setDepthTest(e,t){const n=it.get(e);n&&(n.depthTest=t)},getShader(e){const t=it.get(e);return t?.shader??0},release(e){it.delete(e)},isValid:e=>it.has(e),createFromAsset(e,t){const n={};for(const[t,r]of Object.entries(e.properties))if("number"==typeof r)n[t]=r;else if("object"==typeof r&&null!==r){const e=r;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??et.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=it.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=st++,r={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return it.set(n,r),n},toAssetData(e,t){const n=it.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=it.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let ut=!1,ht=0;const dt=4096,ft=new Map;let pt=null;function _t(e){const t=(0===ht&&nt&&(ht=nt._malloc(dt)),ht);if(0===t||!nt)return{ptr:0,count:0};let n=0,r=0;const s=nt.HEAPU8,i=nt.HEAPU32,o=nt.HEAPF32;for(const[a,c]of e){if(n+128>dt)break;let e=ft.get(a);e||(pt||(pt=new TextEncoder),e=pt.encode(a),ft.set(a,e));const l=e.length,u=4*Math.ceil(l/4);i[t+n>>2]=l,n+=4,s.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof c)h=0,d[0]=c;else if(Array.isArray(c)){h=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(h=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(h=2,d=[c.x,c.y,c.z,0]):"y"in c&&(h=1,d=[c.x,c.y,0,0]);i[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=d[e],n+=4;r++}return{ptr:t,count:r}}function mt(){if(!nt||ut)return;nt.materialDataProvider=(e,t,n,r,s)=>{const i=it.get(e);if(!i)return nt.HEAPU32[t>>2]=0,nt.HEAPU32[n>>2]=0,nt.HEAPU32[r>>2]=0,void(nt.HEAPU32[s>>2]=0);nt.HEAPU32[t>>2]=i.shader,nt.HEAPU32[n>>2]=i.blendMode;const{ptr:o,count:a}=_t(i.uniforms);nt.HEAPU32[r>>2]=o,nt.HEAPU32[s>>2]=a},ut=!0}const gt={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 yt{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&&(lt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())lt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const n=await c(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const r=JSON.parse(n);if("material"!==r.type)throw new Error(`Invalid material file type: ${r.type}`);const s=this.resolveShaderPath(e,r.shader),i=await this.shaderLoader_.load(s);return{handle:lt.createFromAsset(r,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function wt(e,t){const n=new Map;for(const r of t.entities){const t=e.spawn();n.set(r.id,t),e.insert(t,le,{value:r.name});for(const n of r.components)bt(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 xt(e,t,n){const r=new Map,s=n?.assetServer,i=new Map;for(const o of t.entities){const t=e.spawn();r.set(o.id,t),e.insert(t,le,{value:o.name});for(const r of o.components){if("Sprite"===r.type&&s){const e=r.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,r=t.startsWith("data:")?t:n?.assetBaseUrl?`${n.assetBaseUrl}/${t}`:`/${t}`;try{const n=await s.loadTexture(r);e.texture=n.handle,i.set(t,r)}catch(t){console.warn(`Failed to load texture: ${r}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("BitmapText"===r.type&&s){const e=r.data;if("string"==typeof e.font&&e.font)try{const t=await s.loadBitmapFont(e.font,n?.assetBaseUrl);e.font=t}catch(t){console.warn(`Failed to load bitmap font: ${e.font}`,t),e.font=0}}if("SpineAnimation"===r.type&&s){const e=r.data,t=e.skeletonPath,i=e.atlasPath;if(t&&i){const e=await s.loadSpine(t,i,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await s.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}bt(e,t,r)}}for(const n of t.entities)if(null!==n.parent){const t=r.get(n.id),s=r.get(n.parent);void 0!==t&&void 0!==s&&e.setParent(t,s)}if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}function bt(e,t,n){const r=n.data;switch(n.type){case"LocalTransform":e.insert(t,Z,r);break;case"Sprite":e.insert(t,te,r);break;case"Camera":e.insert(t,ne,r);break;case"Canvas":e.insert(t,re,r);break;case"Text":e.insert(t,Ne,r);break;case"BitmapText":e.insert(t,ae,r);break;case"SpineAnimation":e.insert(t,ce,r);break;case"UIRect":e.insert(t,Ve,r);break;case"UIMask":e.insert(t,Ye,r);break;case"RigidBody":e.insert(t,D,r);break;case"BoxCollider":e.insert(t,$,r);break;case"CircleCollider":e.insert(t,H,r);break;case"CapsuleCollider":e.insert(t,L,r);break;default:{const s=Y(n.type);s?e.insert(t,s,r):console.warn(`Unknown component type: ${n.type}`);break}}}function vt(e,t){const n=e.getEntitiesWithComponents([ne]);for(const r of n){const n=e.get(r,ne);n&&(n.aspectRatio=t,e.insert(r,ne,n))}}function Pt(e,t){const n=e.getEntitiesWithComponents([le]);for(const r of n){const n=e.get(r,le);if(n&&n.value===t)return r}return null}class St{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const n=this.cache_.get(e);if(void 0!==n)return n;const 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 Ct{constructor(e){this.textureCache_=new St,this.shaderCache_=new St,this.jsonCache_=new St,this.textCache_=new St,this.binaryCache_=new St,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new St,this.embedded_=new Map,this.module_=e,this.canvas_=h(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new yt(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n)}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const r=this.textureCacheKey(e,n),s=this.textureCache_.get(r);s&&(t.releaseTexture(s.handle),this.textureCache_.delete(r))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);this.textureCache_.clear(),this.fontCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}async loadSpine(e,t,n){const r=`${e}:${t}`;if(this.loadedSpines_.has(r))return{success:!0};try{const s=this.resolveUrl(t,n),i=await this.fetchText(s);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i);for(const e of a){const t=o?`${o}/${e}`:e,r=this.resolveUrl(t,n);try{const e=await this.loadTextureRaw(r);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),l=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);return this.writeToVirtualFS(e,l)?(this.loadedSpines_.add(r),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>e.endsWith(".bmfont")?this.loadBmfontAsset(n):this.loadFntFile(n))}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),r="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!r)throw new Error("Invalid bmfont asset: no fnt file specified");const s=n?`${n}/${r}`:r;return this.loadFntFile(s)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const r=n[1],s=e.substring(0,e.lastIndexOf("/")),i=s?`${s}/${r}`:r,o=await this.loadTextureRaw(i);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return xt(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];if(e.textures)for(const r of e.textures)n.push(this.loadTexture(r).then(e=>{t.textures.set(r,e)}));if(e.materials)for(const r of e.materials)n.push(this.loadMaterial(r).then(e=>{t.materials.set(r,e)}));if(e.spine)for(const r of e.spine){const e=`${r.skeleton}:${r.atlas}`;n.push(this.loadSpine(r.skeleton,r.atlas,r.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const r of e.json)n.push(this.loadJson(r).then(e=>{t.json.set(r,e)}));if(e.text)for(const r of e.text)n.push(this.loadText(r).then(e=>{t.text.set(r,e)}));if(e.binary)for(const r of e.binary)n.push(this.loadBinary(r).then(e=>{t.binary.set(r,e)}));return await Promise.all(n),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,r=this.embedded_.get(n)??n;return new Promise((n,s)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(i)},i.onerror=()=>s(new Error(`Failed to load image: ${e}`)),i.src=r})}createTextureFromImage(e,t){const{width:n,height:r}=e,s=this.getWebGL2Context();return s?this.createTextureWebGL2(s,e,n,r,t):this.createTextureFallback(e,n,r,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,r,s){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,s?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,r),width:n,height:r}}createTextureFallback(e,t,n,r){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const s=this.ctx_.getImageData(0,0,t,n),i=new Uint8Array(s.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,n,a,i.length,1,r);return this.module_._free(a),{handle:c,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const r=255/n;e[t]=Math.min(255,Math.round(e[t]*r)),e[t+1]=Math.min(255,Math.round(e[t+1]*r)),e[t+2]=Math.min(255,Math.round(e[t+2]*r))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e;if(!await l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:s}=this.parseEsShader(n);if(!r||!s)throw new Error(`Invalid shader format: ${e}`);return lt.createShader(r,s)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const n=await c(t);return JSON.parse(n)}const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):c(t)}const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):a(t)}const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const r=n.split("/").filter(e=>e);let s="";for(const e of r){s=s?`${s}/${e}`:e;try{t.analyzePath(s).exists||t.mkdir(s)}catch{try{t.mkdir(s)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Et=fe(null,"Assets");class Tt{build(e){const t=e.wasmModule;t?e.insertResource(Et,new Ct(t)):console.warn("AssetPlugin: No WASM module available")}}const At=new Tt;function Mt(e,t){const n=e.getResource(Et);n&&n.registerEmbeddedAssets(t)}let Rt=null,Ft=0,Ut=0,Bt=0;const It=new Float32Array(256);function kt(e){Rt=e,Ft=Rt._malloc(64),Ut=Rt._malloc(64),Bt=Rt._malloc(1024)}function Wt(){Rt&&(Ft&&(Rt._free(Ft),Ft=0),Ut&&(Rt._free(Ut),Ut=0),Bt&&(Rt._free(Bt),Bt=0)),Rt=null}function zt(){if(!Rt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Rt}const Dt={r:1,g:1,b:1,a:1},$t={begin(e){const t=zt();t.HEAPF32.set(e,Ft/4),t.draw_begin(Ft)},end(){zt().draw_end()},line(e,t,n,r=1){zt().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,r)},rect(e,t,n,r=!0){zt().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,r)},rectOutline(e,t,n,r=1){zt().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,r)},circle(e,t,n,r=!0,s=32){zt().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,r,s)},circleOutline(e,t,n,r=1,s=32){zt().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,r,s)},texture(e,t,n,r=Dt){zt().draw_texture(e.x,e.y,t.x,t.y,n,r.r,r.g,r.b,r.a)},textureRotated(e,t,n,r,s=Dt){zt().draw_textureRotated(e.x,e.y,t.x,t.y,n,r,s.r,s.g,s.b,s.a)},setLayer(e){zt().draw_setLayer(e)},setDepth(e){zt().draw_setDepth(e)},getDrawCallCount:()=>Rt?Rt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Rt?Rt.draw_getPrimitiveCount():0,setBlendMode(e){zt().draw_setBlendMode(e)},setDepthTest(e){zt().draw_setDepthTest(e)},drawMesh(e,t,n){const r=zt();r.HEAPF32.set(n,Ut/4),r.draw_mesh(e,t,Ut)},drawMeshWithMaterial(e,t,n){const r=zt(),s=lt.get(t);if(!s)return;if($t.setBlendMode(s.blendMode),$t.setDepthTest(s.depthTest),0===s.uniforms.size)return void $t.drawMesh(e,s.shader,n);r.HEAPF32.set(n,Ut/4);let i=0,o=0;for(const[e,t]of s.uniforms){const n=Lt(e);if(!(n<0)){if(tt(t))It[i++]=10,It[i++]=n,It[i++]=t.slot??o++,It[i++]=t.textureId;else if("number"==typeof t)It[i++]=1,It[i++]=n,It[i++]=t;else if(Array.isArray(t)){It[i++]=t.length,It[i++]=n;for(let e=0;e<t.length;e++)It[i++]=t[e]}else"w"in t?(It[i++]=4,It[i++]=n,It[i++]=t.x,It[i++]=t.y,It[i++]=t.z,It[i++]=t.w):"z"in t?(It[i++]=3,It[i++]=n,It[i++]=t.x,It[i++]=t.y,It[i++]=t.z):(It[i++]=2,It[i++]=n,It[i++]=t.x,It[i++]=t.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==i?(r.HEAPF32.set(It.subarray(0,i),Bt/4),r.draw_meshWithUniforms(e,s.shader,Ut,Bt,i)):r.draw_mesh(e,s.shader,Ut)}},Ht={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function Lt(e){return Ht[e]??-1}var Ot;!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"}(Ot||(Ot={}));let Nt=null,jt=0,Vt=0,Xt=0;function Gt(e){Nt=e,jt=Nt._malloc(262144),Vt=Nt._malloc(65536),Xt=Nt._malloc(256)}function Yt(){Nt&&(jt&&Nt._free(jt),Vt&&Nt._free(Vt),Xt&&Nt._free(Xt),jt=0,Vt=0,Xt=0),Nt=null}function qt(){if(!Nt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Nt}const Kt={create(e){const t=qt(),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,jt/4);const s=e.layout.length,i=new Int32Array(s);for(let t=0;t<s;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Xt,s).set(i),t.geometry_init(n,jt,r,Xt,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,Vt,r).set(e.indices),t.geometry_setIndices16(n,Vt,r)}else{new Uint32Array(t.HEAPU8.buffer,Vt,r).set(e.indices),t.geometry_setIndices32(n,Vt,r)}}return n},updateVertices(e,t,n=0){const r=qt(),s=t.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);r.HEAPF32.set(t,jt/4),r.geometry_updateVertices(e,jt,s,n)},release(e){e>0&&qt().geometry_release(e)},isValid:e=>!(!Nt||e<=0)&&Nt.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,r=t/2;return Kt.create({vertices:new Float32Array([-n,-r,0,0,n,-r,1,0,n,r,1,1,-n,r,0,1]),layout:[{name:"a_position",type:Ot.Float2},{name:"a_texCoord",type:Ot.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],r=[];n.push(0,0,.5,.5);for(let r=0;r<=t;r++){const s=r/t*Math.PI*2,i=Math.cos(s)*e,o=Math.sin(s)*e,a=(Math.cos(s)+1)/2,c=(Math.sin(s)+1)/2;n.push(i,o,a,c)}for(let e=1;e<=t;e++)r.push(0,e,e+1);return Kt.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Ot.Float2},{name:"a_texCoord",type:Ot.Float2}],indices:new Uint16Array(r)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,r=-1/0,s=-1/0;for(const i of e)t=Math.min(t,i.x),n=Math.min(n,i.y),r=Math.max(r,i.x),s=Math.max(s,i.y);const i=[];for(const o of e){const e=(o.x-t)/(r-t),a=(o.y-n)/(s-n);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return Kt.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:Ot.Float2},{name:"a_texCoord",type:Ot.Float2}],indices:new Uint16Array(o)})}};let Jt=null;function Qt(e){Jt=e}function Zt(){Jt&&tn.isInitialized()&&tn.shutdown(),Jt=null}function en(){if(!Jt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Jt}const tn={init:(e,t)=>en().postprocess_init(e,t),shutdown(){en().postprocess_shutdown()},resize(e,t){en().postprocess_resize(e,t)},addPass:(e,t)=>en().postprocess_addPass(e,t),removePass(e){en().postprocess_removePass(e)},setEnabled(e,t){en().postprocess_setPassEnabled(e,t)},isEnabled:e=>en().postprocess_isPassEnabled(e),setUniform(e,t,n){en().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){en().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){en().postprocess_begin()},end(){en().postprocess_end()},getPassCount:()=>en().postprocess_getPassCount(),isInitialized:()=>!!Jt&&Jt.postprocess_isInitialized(),setBypass(e){en().postprocess_setBypass(e)},isBypassed:()=>!Jt||Jt.postprocess_isBypassed(),createBlur:()=>lt.createShader(nn,"#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:()=>lt.createShader(nn,"#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:()=>lt.createShader(nn,"#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:()=>lt.createShader(nn,"#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")},nn="#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 rn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(rn||(rn={}));let sn=null,on=0;function an(e){sn=e,on=sn._malloc(64)}function cn(){sn&&on&&(sn._free(on),on=0),sn=null}const ln={init(e,t){sn?.renderer_init(e,t)},resize(e,t){sn?.renderer_resize(e,t)},begin(e,t){sn&&on&&(sn.HEAPF32.set(e,on/4),sn.renderer_begin(on,t??0))},flush(){sn?.renderer_flush()},end(){sn?.renderer_end()},submitSprites(e){sn&&sn.renderer_submitSprites(e._cpp)},submitBitmapText(e){sn&&sn.renderer_submitBitmapText(e._cpp)},submitSpine(e){sn&&sn.renderer_submitSpine?.(e._cpp)},setStage(e){sn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>sn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){sn?.renderer_releaseTarget(e)},getTargetTexture:e=>sn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>sn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,r){sn?.renderer_setClearColor?.(e,t,n,r)},setViewport(e,t,n,r){sn?.renderer_setViewport(e,t,n,r)},setScissor(e,t,n,r,s){sn?.renderer_setScissor(e,t,n,r,s)},clearBuffers(e){sn?.renderer_clearBuffers(e)},getStats:()=>sn?{drawCalls:sn.renderer_getDrawCalls(),triangles:sn.renderer_getTriangles(),sprites:sn.renderer_getSprites(),text:sn.renderer_getText(),spine:sn.renderer_getSpine?.()??0,meshes:sn.renderer_getMeshes(),culled:sn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let un=null;function hn(e){un=e}function dn(){un=null}const fn={enable(){un?.gl_enableErrorCheck(!0)},disable(){un?.gl_enableErrorCheck(!1)},check:e=>un?.gl_checkErrors(e)??0,diagnose(){un?.renderer_diagnose()}},pn=new Map;function _n(e,t){pn.set(e,t)}function mn(e){pn.delete(e)}function gn(){pn.clear()}class yn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}setSpineRenderer(e){this.spineRenderer_=e}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:n,width:r,height:s,elapsed:i}=e;r===this.lastWidth_&&s===this.lastHeight_||(ln.resize(r,s),tn.isInitialized()&&tn.getPassCount()>0&&tn.resize(r,s),this.lastWidth_=r,this.lastHeight_=s),ln.setViewport(0,0,r,s),ln.clearBuffers(3),ln.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,r,s),ln.submitSprites(t),ln.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):ln.submitSpine(t),ln.flush(),this.executeDrawCallbacks(n,i),ln.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:r,clearFlags:s,elapsed:i}=e;ln.setViewport(r.x,r.y,r.w,r.h),ln.setScissor(r.x,r.y,r.w,r.h,!0),ln.clearBuffers(s),ln.setScissor(0,0,0,0,!1),ln.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,r.x,r.y,r.w,r.h),ln.submitSprites(t),ln.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):ln.submitSpine(t),ln.flush(),this.executeDrawCallbacks(n,i),ln.end()}executeDrawCallbacks(e,t){const n=pn;if(n.size>0){$t.begin(e);const r=[];for(const[e,s]of n.entries())try{s(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),r.push(e)}$t.end();for(const e of r)mn(e)}}}class wn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.runSchedule(Ee.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Ee.FixedPreUpdate),this.runSchedule(Ee.FixedUpdate),this.runSchedule(Ee.FixedPostUpdate);this.runSchedule(Ee.PreUpdate),this.runSchedule(Ee.Update),this.runSchedule(Ee.PostUpdate),this.runSchedule(Ee.Last),requestAnimationFrame(this.mainLoop)},this.world_=new $e,this.resources_=new ge;for(const e of Object.values(Ee))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new wn}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(Ee.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Ee.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new Be(this.world_,this.resources_),this.resources_.insert(ye,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Ee.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,dn(),cn(),Zt(),Yt(),at(),Wt()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(ye);t.delta=e,t.elapsed+=e,t.frameCount++}}function xn(e,t){const n=wn.new(),r=new e.Registry;n.connectCpp(r,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),kt(e),ot(e),Gt(e),Qt(e),an(e),hn(e);const s=new yn;n.pipeline_=s;let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),a={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=o(),a=e.registry_getCanvasEntity(r);if(a>=0){const e=r.getCanvas(a).backgroundColor;ln.setClearColor(e.r,e.g,e.b,e.a)}const c=(d()-i)/1e3;ln.resize(t,n),tn.isInitialized()&&tn.getPassCount()>0&&!tn.isBypassed()&&tn.resize(t,n);const l=function(e,t,n,r){const s=e.registry_getCameraEntities(t);if(0===s.length)return[];const i=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),o=[];for(const e of s){const s=t.getCamera(e),a=t.getLocalTransform(e),c={x:s.viewportX,y:s.viewportY,w:s.viewportW,h:s.viewportH},l=c.w*n/(c.h*r);let u;if(1===s.projectionType){let e=s.orthoSize;if(i){e=Pn(i.designResolution.y/2,i.designResolution.x/i.designResolution.y,l,i.scaleMode,i.matchWidthOrHeight)}const t=e*l;u=Cn(-t,t,-e,e,-s.farPlane,s.farPlane)}else u=Tn(s.fov*Math.PI/180,l,s.nearPlane,s.farPlane);const h=Mn(a.position.x,a.position.y,a.position.z);o.push({entity:e,viewProjection:Rn(u,h),viewportRect:c,clearFlags:s.clearFlags,priority:s.priority})}return o.sort((e,t)=>e.priority-t.priority),o}(e,r,t,n);if(0===l.length)s.render({registry:{_cpp:r},viewProjection:vn,width:t,height:n,elapsed:c});else{for(const e of l){const i=e.viewportRect,o=Math.round(i.x*t),a=Math.round((1-i.y-i.h)*n),l=Math.round(i.w*t),u=Math.round(i.h*n);s.renderCamera({registry:{_cpp:r},viewProjection:e.viewProjection,viewportPixels:{x:o,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}ln.setViewport(0,0,t,n)}}};return n.addSystemToSchedule(Ee.Last,a),n.addPlugin(At),n.addPlugin(ze),n.addPlugin(Ge),n.addPlugin(Ze),n}function bn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const vn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Pn(e,t,n,r,s){const i=e*t/n,o=e;switch(r){case 0:return i;case 1:default:return o;case 2:return Math.max(i,o);case 3:return Math.min(i,o);case 4:{const e=s;return Math.pow(i,1-e)*Math.pow(o,e)}}}const Sn=new Float32Array(16);function Cn(e,t,n,r,s,i){const o=Sn;o.fill(0);const a=t-e,c=r-n,l=i-s;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(r+n)/c,o[14]=-(i+s)/l,o[15]=1,o}const En=new Float32Array(16);function Tn(e,t,n,r){const s=En;s.fill(0);const i=1/Math.tan(e/2),o=n-r;return s[0]=i/t,s[5]=i,s[10]=(r+n)/o,s[11]=-1,s[14]=2*r*n/o,s}const An=new Float32Array(16);function Mn(e,t,n){const r=An;return r[0]=1,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=1,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=1,r[11]=0,r[12]=-e,r[13]=-t,r[14]=-n,r[15]=1,r}function Rn(e,t){const n=new Float32Array(16);for(let r=0;r<4;r++)for(let s=0;s<4;s++)n[4*s+r]=e[0+r]*t[4*s+0]+e[4+r]*t[4*s+1]+e[8+r]*t[4*s+2]+e[12+r]*t[4*s+3];return n}async function Fn(e,t){if(t)return t();return(0,(await import(e)).default)()}const Un=fe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Bn=fe(null,"PhysicsAPI");function In(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function kn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Wn{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Un,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,r=Fn(this.wasmUrl_,this.factory_).then(r=>{r._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const s=function(e){const t=e.world.getEntitiesWithComponents([re]);for(const n of t){const t=e.world.get(n,re);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/s,o=e.world;e.addSystemToSchedule(Ee.PostUpdate,Ae([pe(ye)],a=>{const c=o.getEntitiesWithComponents([D,Z,ee]),l=new Set;for(const s of c){l.add(s);const a=o.get(s,D),c=o.get(s,ee);if(t.has(s)){const e=n.get(s);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(r._physics_updateBodyProperties(s,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const o=In(c.rotation);r._physics_createBody(s,a.bodyType,c.position.x*i,c.position.y*i,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),zn(e,r,s),t.add(s),n.set(s,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===O.Kinematic){const e=In(c.rotation);r._physics_setBodyTransform(s,c.position.x*i,c.position.y*i,e)}}for(const e of t)l.has(e)||(r._physics_destroyBody(e),t.delete(e),n.delete(e));r._physics_step(a.delta),function(e,t,n){const r=t._physics_getDynamicBodyCount();if(0===r)return;const s=t._physics_getDynamicBodyTransforms(),i=s>>2;for(let s=0;s<r;s++){const r=i+4*s,o=t.HEAPU32[r],a=t.HEAPF32[r+1]*n,c=t.HEAPF32[r+2]*n,l=t.HEAPF32[r+3];if(!e.world.valid(o))continue;const u=e.world.get(o,Z);if(!u)continue;let h=a,d=c,f=l;if(e.world.has(o,ie)){const t=e.world.get(o,ie);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ee)){const n=e.world.get(t.entity,ee),r=In(n.rotation),s=a-n.position.x,i=c-n.position.y,o=Math.cos(-r),u=Math.sin(-r);h=(s*o-i*u)/(0!==n.scale.x?n.scale.x:1),d=(s*u+i*o)/(0!==n.scale.y?n.scale.y:1),f=l-r}}u.position.x=h,u.position.y=d;const p=kn(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(o,Z,u)}}(e,r,s),function(e,t,n){t._physics_collectEvents();const r=[],s=t._physics_getCollisionEnterCount();if(s>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<s;i++){const s=e+6*i;r.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1],normalX:t.HEAPF32[s+2],normalY:t.HEAPF32[s+3],contactX:t.HEAPF32[s+4]*n,contactY:t.HEAPF32[s+5]*n})}}const i=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<o;n++){const r=e+2*n;i.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1]})}}const a=[],c=t._physics_getSensorEnterCount();if(c>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<c;n++){const r=e+2*n;a.push({sensorEntity:t.HEAPU32[r],visitorEntity:t.HEAPU32[r+1]})}}const l=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const r=e+2*n;l.push({sensorEntity:t.HEAPU32[r],visitorEntity:t.HEAPU32[r+1]})}}e.insertResource(Un,{collisionEnters:r,collisionExits:i,sensorEnters:a,sensorExits:l})}(e,r,s)},{name:"PhysicsSystem"})),e.__physicsModule=r,e.insertResource(Bn,Dn._fromModule(r)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=r}}function zn(e,t,n){const r=e.world;if(r.has(n,$)){const e=r.get(n,$);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(r.has(n,H)){const e=r.get(n,H);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(r.has(n,L)){const e=r.get(n,L);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Dn{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(Dn.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function $n(e,t,n=!0){const r=e.getResourceManager(),s=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,s);const i=r.createTexture(t.width,t.height,s,t.pixels.length,1,n);return e._free(s),i}function Hn(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function Ln(e,t,n,r){const s=e.scale.x*t*(n?-1:1),i=e.scale.y*t*(r?-1:1),o=e.scale.z,a=e.rotation.x,c=e.rotation.y,l=e.rotation.z,u=e.rotation.w,h=a+a,d=c+c,f=l+l,p=a*h,_=a*d,m=a*f,g=c*d,y=c*f,w=l*f,x=u*h,b=u*d,v=u*f;return new Float32Array([(1-(g+w))*s,(_+v)*s,(m-b)*s,0,(_-v)*i,(1-(p+w))*i,(y+x)*i,0,(m+b)*o,(y-x)*o,(1-(p+g))*o,0,e.position.x,e.position.y,e.position.z,1])}async function On(e,t,n,r,s,i,o){const a=await async function(e,t,n){const r={};for(const s of t.entities)for(const t of s.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const s=t.data.texture;if(void 0!==r[s])continue;try{r[s]=$n(e,await n.loadPixels(s))}catch{r[s]=0}}return r}(t,n,r);!function(e,t,n){if(!t.textureMetadata)return;const r=e.getResourceManager();for(const e in t.textureMetadata){const s=n[e];if(s&&s>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;r.setTextureMetadata(s,e.left,e.right,e.top,e.bottom)}}}}(t,n,a);let c={},l=null;if(s&&(l=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(s),c=await async function(e,t,n,r,s){const i={};for(const o of r.entities)for(const r of o.components){if("SpineAnimation"!==r.type||!r.data)continue;const o=r.data.skeletonPath,a=r.data.atlasPath;if(!o||!a)continue;const c=s.resolvePath(o),l=s.resolvePath(a);try{const r=s.readText(a),u=c.endsWith(".skel");let h,d;if(u){const e=s.readBinary(o);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=s.readText(o),n=(new TextEncoder).encode(e);d=n.length,h=t._malloc(d+1),t.HEAPU8.set(n,h),t.HEAPU8[h+d]=0}const f=n.loadSkeleton(h,d,r,r.length,u);if(t._free(h),f<0)continue;i[o]=f;const p=Hn(r),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<p.length;t++){const r=_+"/"+p[t];try{const i=s.loadPixelsRaw?await s.loadPixelsRaw(r):await s.loadPixels(r),o=$n(e,i,!1),a=e.getResourceManager().getTextureGLId(o);n.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,s,l,n,r)),i){new Wn("",{gravity:o?.gravity??{x:0,y:-9.81},fixedTimestep:o?.fixedTimestep??1/60,subStepCount:o?.subStepCount??4},()=>Promise.resolve(i)).build(e)}const u=function(e,t){const n={},r={};for(const s of e.entities)for(const e of s.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const s=e.data.material;if(void 0===n[s])try{const e=JSON.parse(t.readText(s));if(!e.vertexSource||!e.fragmentSource){n[s]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=r[i];o||(o=lt.createShader(e.vertexSource,e.fragmentSource),r[i]=o),n[s]=lt.createFromAsset(e,o)}catch{n[s]=0}}return n}(n,r),h=wt(e.world,n);if(function(e,t,n,r){for(const s of t.entities){const t=r.get(s.id);if(void 0!==t)for(const r of s.components)if("Sprite"===r.type&&r.data.texture&&"string"==typeof r.data.texture){const s=e.get(t,te);s&&(s.texture=n[r.data.texture]||0,e.insert(t,te,s))}}}(e.world,n,a,h),function(e,t,n,r){for(const s of t.entities){const t=r.get(s.id);if(void 0!==t)for(const r of s.components){if(!r.data||"string"!=typeof r.data.material||!r.data.material)continue;const s=n[r.data.material]||0;if(s)if("Sprite"===r.type){const n=e.get(t,te);n&&(n.material=s,e.insert(t,te,n))}else if("SpineAnimation"===r.type){const n=e.get(t,ce);n&&(n.material=s,e.insert(t,ce,n))}}}}(e.world,n,u,h),s&&l){const r=function(e,t,n,r){const s={};for(const i of t.entities)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=n[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const c=r.get(i.id);void 0!==c&&(s[c]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return s}(l,n,c,h);!function(e,t,n,r,s){let i=0;e.setSpineRenderer((o,a)=>{let c=a-i;i=a,(c<=0||c>.5)&&(c=1/60);const l=e.world;for(const e in s){const i=Number(e),o=s[e],a=l.has(i,ce)?l.get(i,ce):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&r.update(o,c*h);let d=0;if(l.has(i,ee)){const e=Ln(l.get(i,ee),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=r.getMeshBatchCount(o);for(let e=0;e<f;e++){const s=r.getMeshBatchVertexCount(o,e),i=r.getMeshBatchIndexCount(o,e);if(!s||!i)continue;const a=8*s*4,c=2*i,l=n._malloc(a),u=n._malloc(c),h=n._malloc(4),f=n._malloc(4);r.getMeshBatchData(o,e,l,u,h,f);const p=n.HEAPU32[h>>2],_=n.HEAPU32[f>>2],m=new Float32Array(n.HEAPF32.buffer,l,8*s),g=new Uint16Array(n.HEAPU8.buffer,u,i),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(m,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(g),t.renderer_submitTriangles(y,s,w,i,p,_,d),t._free(y),t._free(w),n._free(l),n._free(u),n._free(h),n._free(f)}d&&t._free(d)}})}(e,t,s,l,r)}}class Nn{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const r=e.data.skeletonPath,s=e.data.atlasPath;r&&(r.endsWith(".skel")?n.add(r):t.add(r)),s&&t.add(s)}"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(r)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),r=await n.blob(),s=await createImageBitmap(r),i=new OffscreenCanvas(s.width,s.height).getContext("2d");i.drawImage(s,0,0);const o=i.getImageData(0,0,s.width,s.height);return s.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class jn{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new Nn(this.baseUrl_);await n.prefetch(t);let r=null;const s=this.app_.__spineInitPromise;if(s){r=(await s).controller.raw}await On(this.app_,this.app_.wasmModule,t,n,r),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([ne]);for(const r of n){if(e.get(r,ne).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const r=e.getEntitiesWithComponents([re]);for(const s of r){const r=e.get(s,re);if(r.designResolution){const e=r.pixelsPerUnit||100;t=r.designResolution.y/2/e,n=r.designResolution.x/r.designResolution.y;break}}const s=e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(s,Z,i);const o={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3};e.insert(s,ne,o)}}}const Vn={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=ln.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:ln.getTargetTexture(n),width:e.width,height:e.height}},release(e){ln.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(ln.releaseRenderTarget(e._handle),Vn.create({width:t,height:n,depth:!0})),begin(e,t){ln.begin(t,e._handle)},end(){ln.end()},getDepthTexture:e=>ln.getTargetDepthTexture(e._handle)};let Xn=!1;function Gn(e){Xn=e}function Yn(){return Xn}function qn(){return!Xn}T||(T=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),r={method:t?.method??"GET",headers:t?.headers,body:t?.body},s=await f(n,r);return{ok:s.ok,status:s.status,statusText:s.statusText,headers:new Headers(s.headers),json:()=>s.json(),text:()=>s.text(),arrayBuffer:()=>s.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:n}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return p(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),n=new Uint8Array(t);let r=0;for(let t=0;t<e.length;t++){let s=e.charCodeAt(t);s<128?n[r++]=s:s<2048?(n[r++]=192|s>>6,n[r++]=128|63&s):s>=55296&&s<=56319?(s=e.charCodeAt(++t)-56320+(s-55296<<10)+65536,n[r++]=240|s>>18,n[r++]=128|s>>12&63,n[r++]=128|s>>6&63,n[r++]=128|63&s):(n[r++]=224|s>>12,n[r++]=128|s>>6&63,n[r++]=128|63&s)}return n.subarray(0,r)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let n="";for(let e=0;e<t.length;){const r=t[e];if(r<128)n+=String.fromCharCode(r),e++;else if(192==(224&r))n+=String.fromCharCode((31&r)<<6|63&t[e+1]),e+=2;else if(224==(240&r))n+=String.fromCharCode((15&r)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const s=((7&r)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(s>>10),56320+(1023&s)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=A;export{wn as App,Tt as AssetPlugin,Ct as AssetServer,Et as Assets,St as AsyncCache,ae as BitmapText,et as BlendMode,O as BodyType,$ as BoxCollider,ne as Camera,re as Canvas,L as CapsuleCollider,oe as Children,H as CircleCollider,Pe as Commands,Ce as CommandsInstance,Ot as DataType,$t as Draw,Se as EntityCommands,fn as GLDebug,Kt as Geometry,M as INVALID_ENTITY,F as INVALID_FONT,R as INVALID_TEXTURE,ke as Input,We as InputPlugin,Ie as InputState,Z as LocalTransform,lt as Material,yt as MaterialLoader,we as Mut,le as Name,ie as Parent,Dn as Physics,Un as PhysicsEvents,Wn as PhysicsPlugin,tn as PostProcess,jn as PreviewPlugin,be as Query,ve as QueryInstance,yn as RenderPipeline,rn as RenderStage,Vn as RenderTexture,ln as Renderer,pe as Res,_e as ResMut,D as RigidBody,Ee as Schedule,gt as ShaderSources,ce as SpineAnimation,te as Sprite,Be as SystemRunner,Ne as Text,He as TextAlign,Oe as TextOverflow,Xe as TextPlugin,je as TextRenderer,Le as TextVerticalAlign,ye as Time,Ye as UIMask,Qe as UIMaskPlugin,Ve as UIRect,se as Velocity,Nn as WebAssetProvider,$e as World,ee as WorldTransform,Fe as addStartupSystem,Re as addSystem,Ue as addSystemToSchedule,At as assetPlugin,gn as clearDrawCallbacks,q as clearUserComponents,k as color,Je as createMaskProcessor,xn as createWebApp,X as defineComponent,fe as defineResource,Ae as defineSystem,G as defineTag,Pt as findEntityByName,bn as flushPendingSystems,he as getComponentDefaults,t as getPlatform,r as getPlatformType,Y as getUserComponent,kt as initDrawAPI,hn as initGLDebugAPI,Gt as initGeometryAPI,ot as initMaterialAPI,Qt as initPostProcessAPI,an as initRendererAPI,ze as inputPlugin,Q as isBuiltinComponent,Yn as isEditor,n as isPlatformInitialized,qn as isRuntime,tt as isTextureRef,s as isWeChat,i as isWeb,bt as loadComponent,Fn as loadPhysicsModule,On as loadRuntimeScene,wt as loadSceneData,xt as loadSceneWithAssets,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,W as quat,_n as registerDrawCallback,Mt as registerEmbeddedAssets,mt as registerMaterialCallback,Gn as setEditorMode,Wt as shutdownDrawAPI,dn as shutdownGLDebugAPI,Yt as shutdownGeometryAPI,at as shutdownMaterialAPI,Zt as shutdownPostProcessAPI,cn as shutdownRendererAPI,Ge as textPlugin,Ze as uiMaskPlugin,mn as unregisterDrawCallback,vt as updateCameraAspectRatio,U as vec2,B as vec3,I as vec4,w as wxFileExists,x as wxFileExistsSync,C as wxGetImagePixels,S as wxLoadImage,E as wxLoadImagePixels,g as wxReadFile,y as wxReadTextFile,b as wxWriteFile};+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}function f(e,t){return new Promise((n,s)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];n({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,n="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(n).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function p(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const n=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(n,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${n}": ${t}`)}}let m=null;function _(){return m||(m=wx.getFileSystemManager()),m}function g(e){return new Promise((t,n)=>{_().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function y(e,t="utf-8"){return new Promise((n,s)=>{_().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function w(e){return new Promise(t=>{_().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function x(e){const t=_();try{return t.accessSync(e),!0}catch{return!1}}function v(e,t){return new Promise((n,s)=>{_().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}let b=null,P=null;function S(e){return new Promise((t,n)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>n(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function C(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){return b||(b=wx.createCanvas(),b.width=e,b.height=t,P=b.getContext("2d")),(b.width<e||b.height<t)&&(b.width=Math.max(b.width,e),b.height=Math.max(b.height,t)),{canvas:b,ctx:P}}(t,n);s.clearRect(0,0,t,n),s.drawImage(e,0,0);const r=s.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(r.data.buffer)}}async function M(e){return C(await S(e))}let T=!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)}createImage(){return wx.createImage()}createCanvas(e,t){const n=wx.createCanvas();return n.width=e,n.height=t,n}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{const n=t.touches[0];n&&e.onPointerDown(0,n.clientX,n.clientY)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX,n.clientY)}),wx.onTouchEnd(()=>{e.onPointerUp(0)})}},A=0,R=4294967295,F=0,U=(e=0,t=0)=>({x:e,y:t}),B=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),I=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),k=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),W=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function z(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const D=z("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),H=z("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),$=z("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),L=z("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),O={Static:0,Kinematic:1,Dynamic:2};let j=0;function N(e,t){const n=++j;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function X(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function V(e,t){const n=X(),s=n.get(e);if(s)return s;const r=N(e,t);return n.set(e,r),K(e,t,!1),r}function Y(e){const t=X(),n=t.get(e);if(n)return n;const s=N(e,{});return t.set(e,s),K(e,{},!0),s}function G(e){return X().get(e)}function q(){X().clear()}function K(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function J(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function Q(e){return!0===e._builtin}const Z=J("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),ee=J("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),te=J("Sprite",{texture:R,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),ne=J("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),se=J("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),re=J("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),oe=J("Parent",{entity:0}),ie=J("Children",{entities:[]}),ae=J("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:0}),ce=J("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),le={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},ue={LocalTransform:Z,WorldTransform:ee,Sprite:te,Camera:ne,Canvas:se,Velocity:re,Parent:oe,Children:ie,BitmapText:ae,SpineAnimation:ce,RigidBody:D,BoxCollider:H,CircleCollider:$,CapsuleCollider:L};function he(e){const t=ue[e];if(t)return{...t._default};const n=G(e);return n?{...n._default}:null}let de=0;function fe(e,t){const n=++de;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function pe(e){return{_type:"res",_resource:e}}function me(e){return{_type:"res_mut",_resource:e}}class _e{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}}class ge{constructor(){this.resources_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id)}getResMut(e){return new _e(this.get(e),t=>this.set(e,t))}}const ye=fe({delta:0,elapsed:0,frameCount:0},"Time");function we(e){return{_type:"mut",_component:e}}function xe(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function ve(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{xe(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class be{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>xe(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with)}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),r=n.length,o=e.length>0,i=t.length>0,a=new Array(r+1);let c=null,l=[];try{for(const u of s){if(null!==c&&o){for(let e=0;e<l.length;e++){const t=l[e];this.world_.insert(c,t.component,t.data)}l.length=0}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(u,t[n])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,n[e]);if(o){for(let t=0;t<e.length;t++){const s=e[t];l.push({component:n[s],data:a[s+1]})}c=u}yield a}}finally{if(null!==c&&o)for(let e=0;e<l.length;e++){const t=l[e];this.world_.insert(c,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function Pe(){return{_type:"commands"}}class Se{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=Q(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Ce{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Se(this,null);return this.spawned_.push(e),e}entity(e){return new Se(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Me;!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(Me||(Me={}));let Te=0;function Ee(e,t,n){const s=++Te;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Ae(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Re(e){Ae().push({schedule:Me.Update,system:e})}function Fe(e){Ae().push({schedule:Me.Startup,system:e})}function Ue(e,t){Ae().push({schedule:e,system:t})}class Be{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Ce&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new be(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Ce(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ie{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const ke=fe(new Ie,"Input");class We{constructor(e){this.target_=e??null}build(e){const n=new Ie;e.insertResource(ke,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(Me.First,Ee([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ze=new We;function De(e){if(null==e||"object"!=typeof e||Array.isArray(e))return e;const t=e;if("r"in t&&"g"in t&&"b"in t&&"a"in t&&!("x"in t))return{x:t.r,y:t.g,z:t.b,w:t.a};const n={};for(const e of Object.keys(t)){const s=t[e];n[e]=null==s||"object"!=typeof s||Array.isArray(s)?s:De(s)}return n}class He{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return Q(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return Q(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return Q(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){Q(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const s={...t._default,...n};if(this.cppRegistry_){const n=`add${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e,De(s))}return s}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const n=`get${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const n=`has${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const n=`remove${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e)}insertScript(e,t,n){const s=t.create(n);return this.getStorage(t).set(e,s),s}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();let t=null,n=1/0;for(const s of e)if(!Q(s)){const e=this.tsStorage_.get(s._id),r=e?e.size:0;r<n&&(n=r,t=e??null)}const s=[],r=t?t.keys():this.entities_;for(const t of r){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&s.push(t)}return s}}var $e,Le,Oe;!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"}(Le||(Le={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Oe||(Oe={}));const je=V("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:$e.Left,verticalAlign:Le.Top,wordWrap:!0,overflow:Oe.Visible,lineHeight:1.2,dirty:!0});class Ne{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let 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=r?Math.ceil(o):h+2*u,p=r?Math.ceil(i):d+2*u;if(r&&e.overflow===Oe.Ellipsis&&d>i){const e=Math.floor(i/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<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const m=Math.round(255*e.color.r),_=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${_}, ${g}, ${y})`,r&&e.overflow===Oe.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=c.length*l;let x;if(r)switch(e.verticalAlign){case Le.Top:x=u;break;case Le.Middle:x=(p-w)/2;break;case Le.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let s;switch(e.align){case $e.Left:s=u;break;case $e.Center:s=f/2;break;case $e.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=l}r&&e.overflow===Oe.Clip&&n.restore();const b=n.getImageData(0,0,f,p),P=new Uint8Array(b.data.buffer),S=this.module.getResourceManager(),C=this.module._malloc(P.length);this.module.HEAPU8.set(P,C);const M=S.createTexture(f,p,C,P.length,1,!0);return this.module._free(C),{textureHandle:M,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const r=this.renderText(t,n);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case $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}}const Xe=V("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class Ve{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Ne(t),s=e.world;e.addSystemToSchedule(Me.PreUpdate,Ee([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,je));const e=s.getEntitiesWithComponents([je]);for(const t of e){const e=s.get(t,je);if(!e.dirty)continue;s.has(t,te)||s.insert(t,te,{texture:R,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const r=s.has(t,Xe)?s.get(t,Xe):null,o=n.renderForEntity(t,e,r),i=s.get(t,te);i.texture=o.textureHandle,i.size.x=o.width,i.size.y=o.height,i.uvOffset.x=0,i.uvOffset.y=0,i.uvScale.x=1,i.uvScale.y=1,s.insert(t,te,i),e.dirty=!1}}))}}const Ye=new Ve,Ge=V("UIMask",{enabled:!0});function qe(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,o-s)}}function Ke(e,t,n,s,r,o,i,a,c,l,u){const h=e-n*r,d=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function m(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*l,c+(.5*(s/r)+.5)*u]}const[_,g]=m(h,f),[y,w]=m(d,p),x=Math.min(_,y),v=Math.max(_,y),b=Math.min(g,w),P=Math.max(g,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(P-b)}}function Je(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],c=e[5],l=e[6],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],m=e[12],_=e[13],g=e[14],y=e[15],w=s*c-r*a,x=s*l-o*a,v=s*u-i*a,b=r*l-o*c,P=r*u-i*c,S=o*u-i*l,C=h*_-d*m,M=h*g-f*m,T=h*y-p*m,E=d*g-f*_,A=d*y-p*_,R=f*y-p*g;let F=w*R-x*A+v*E+b*T-P*M+S*C;return Math.abs(F)<1e-8||(F=1/F,n[0]=(c*R-l*A+u*E)*F,n[1]=(o*A-r*R-i*E)*F,n[2]=(_*S-g*P+y*b)*F,n[3]=(f*P-d*S-p*b)*F,n[4]=(l*T-a*R-u*M)*F,n[5]=(s*R-o*T+i*M)*F,n[6]=(g*v-m*S-y*x)*F,n[7]=(h*S-f*v+p*x)*F,n[8]=(a*A-c*T+u*C)*F,n[9]=(r*T-s*A-i*C)*F,n[10]=(m*P-_*v+y*w)*F,n[11]=(d*v-h*P-p*w)*F,n[12]=(c*M-a*E-l*C)*F,n[13]=(s*E-r*M+o*C)*F,n[14]=(_*x-m*b-g*w)*F,n[15]=(h*b-d*x+f*w)*F),n}function Qe(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,c=(t-r)/i*2-1,l=n[0]*a+n[4]*c+n[12],u=n[1]*a+n[5]*c+n[13],h=n[3]*a+n[7]*c+n[15];return{x:l/h,y:u/h}}function Ze(e,t,n,s,r,o,i,a){return e>=n-r*i&&e<=n+r*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function et(e,t,n,s,r,o,i){if(!e.has(t,Xe)||!e.has(t,ee))return null;const a=e.get(t,Xe),c=e.get(t,ee),l=a.size.x*c.scale.x,u=a.size.y*c.scale.y;return Ke(c.position.x,c.position.y,l,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function tt(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([Ge]);if(0!==c.length)try{!function(e,t,n,s,r,o,i,a,c){const l=new Set;for(const e of s){t.get(e,Ge).enabled&&l.add(e)}const u=[];for(const e of s){if(!l.has(e))continue;let n=!0,s=e;for(;t.has(s,oe);){const e=t.get(s,oe);if(l.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function h(s,u){const d=e.getChildEntities(n,s);for(const n of d){let s=u;if(l.has(n)){const e=et(t,n,r,o,i,a,c);e&&(s=qe(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of u){const n=et(t,e,r,o,i,a,c);n&&h(e,n)}}(e,t,n,c,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class nt{build(e){if(!e.wasmModule)return;const t=e.pipeline_;t&&t.setMaskProcessor(tt(e.wasmModule,e.world))}}const st=new nt,rt=V("Interactable",{enabled:!0}),ot=V("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var it;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(it||(it={}));const at=V("Button",{state:it.Normal,transition:null});class ct{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const lt=fe(new ct,"UIEvents"),ut=fe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo"),ht=new Float32Array(16);class dt{build(e){const t=e.world,n=new ct;e.insertResource(lt,n);let s=null,r=null;e.addSystemToSchedule(Me.PreUpdate,Ee([pe(ke),pe(ut)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([ot]);for(const e of i){const n=t.get(e,ot);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a="undefined"!=typeof window&&window.devicePixelRatio||1,c=e.mouseX*a,l=o.screenH-e.mouseY*a;Je(o.viewProjection,ht);const u=Qe(c,l,ht,o.vpX,o.vpY,o.vpW,o.vpH),h=t.getEntitiesWithComponents([rt,Xe,ee]);let d=null,f=-1/0;for(const e of h){t.has(e,ot)||t.insert(e,ot);if(!t.get(e,rt).enabled)continue;const n=t.get(e,ee),s=t.get(e,Xe),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(Ze(u.x,u.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y)){let n=0;t.has(e,te)&&(n=t.get(e,te).layer),n>=f&&(f=n,d=e)}}if(s!==d){if(null!==s&&t.valid(s)&&t.has(s,ot)){t.get(s,ot).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,ot).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,ot);e.pressed=!0,e.justPressed=!0,r=d,n.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,ot)){const e=t.get(r,ot);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Me.Update,Ee([],()=>{const e=t.getEntitiesWithComponents([at]);for(const n of e){if(t.has(n,rt)||t.insert(n,rt,{enabled:!0}),!t.has(n,ot))continue;const e=t.get(n,ot),s=t.get(n,at),r=t.get(n,rt),o=s.state;if(r.enabled?e.pressed?s.state=it.Pressed:e.hovered?s.state=it.Hovered:s.state=it.Normal:s.state=it.Disabled,o!==s.state&&s.transition&&t.has(n,te)){const e=t.get(n,te),r=s.transition;switch(s.state){case it.Normal:e.color={...r.normalColor};break;case it.Hovered:e.color={...r.hoveredColor};break;case it.Pressed:e.color={...r.pressedColor};break;case it.Disabled:e.color={...r.disabledColor}}t.insert(n,te,e)}}},{name:"ButtonSystem"}))}}const ft=new dt,pt=Y("ScreenSpace");function mt(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,c=o.left+e.x*i,l=o.left+t.x*i,u=o.bottom+e.y*a,h=o.bottom+t.y*a;let d,f,p,m;if(c===l&&u===h){const e=c+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;d=e-s,f=t-o,p=e+s,m=t+o}else d=c+n.x,f=u+n.y,p=l+s.x,m=h+s.y;return{centerX:.5*(d+p),centerY:.5*(f+m),width:p-d,height:m-f,rect:{left:d,bottom:f,right:p,top:m}}}function _t(e,t,n,s,r,o){if(!e.has(t,Xe))return;const i=e.get(t,Xe),a=mt(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const c=e.get(t,Z);if(o?(c.position.x=a.centerX,c.position.y=a.centerY):(c.position.x=a.centerX-s,c.position.y=a.centerY-r),e.insert(t,Z,c),!e.has(t,ie))return;const l=e.get(t,ie);if(l&&l.entities)for(const t of l.entities)e.valid(t)&&_t(e,t,a.rect,a.centerX,a.centerY,!1)}class gt{build(e){const t=e.world;e.addSystemToSchedule(Me.PreUpdate,Ee([pe(ut)],e=>{if(!e.valid)return;const n={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(n.left+n.right),r=.5*(n.bottom+n.top),o=t.getEntitiesWithComponents([pt,Xe,Z]);for(const e of o)_t(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const yt=new gt;var wt;function xt(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"}(wt||(wt={}));let vt=null,bt=null,Pt=1;const St=new Map;function Ct(e){vt=e,bt=e.getResourceManager(),kt()}function Mt(){0!==Rt&&vt&&(vt._free(Rt),Rt=0),St.clear(),Pt=1,At=!1,bt=null,vt=null}function Tt(){if(!bt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return bt}const Et={createShader:(e,t)=>Tt().createShader(e,t),releaseShader(e){e>0&&Tt().releaseShader(e)},create(e){const t=Pt++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??wt.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return St.set(t,n),t},get:e=>St.get(e),setUniform(e,t,n){const s=St.get(e);s&&s.uniforms.set(t,n)},getUniform(e,t){const n=St.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=St.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=St.get(e);return t?.blendMode??wt.Normal},setDepthTest(e,t){const n=St.get(e);n&&(n.depthTest=t)},getShader(e){const t=St.get(e);return t?.shader??0},release(e){St.delete(e)},isValid:e=>St.has(e),createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??wt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=St.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Pt++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return St.set(n,s),n},toAssetData(e,t){const n=St.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=St.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let At=!1,Rt=0;const Ft=4096,Ut=new Map;let Bt=null;function It(e){const t=(0===Rt&&vt&&(Rt=vt._malloc(Ft)),Rt);if(0===t||!vt)return{ptr:0,count:0};let n=0,s=0;const r=vt.HEAPU8,o=vt.HEAPU32,i=vt.HEAPF32;for(const[a,c]of e){if(n+128>Ft)break;let e=Ut.get(a);e||(Bt||(Bt=new TextEncoder),e=Bt.encode(a),Ut.set(a,e));const l=e.length,u=4*Math.ceil(l/4);o[t+n>>2]=l,n+=4,r.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof c)h=0,d[0]=c;else if(Array.isArray(c)){h=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(h=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(h=2,d=[c.x,c.y,c.z,0]):"y"in c&&(h=1,d=[c.x,c.y,0,0]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function kt(){if(!vt||At)return;vt.materialDataProvider=(e,t,n,s,r)=>{const o=St.get(e);if(!o)return vt.HEAPU32[t>>2]=0,vt.HEAPU32[n>>2]=0,vt.HEAPU32[s>>2]=0,void(vt.HEAPU32[r>>2]=0);vt.HEAPU32[t>>2]=o.shader,vt.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=It(o.uniforms);vt.HEAPU32[s>>2]=i,vt.HEAPU32[r>>2]=a},At=!0}const Wt={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class zt{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const n=this.pending_.get(e);if(n)return n;const s=this.loadInternal(e);this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Et.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Et.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const n=await c(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(r);return{handle:Et.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function Dt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();n.set(s.id,t),e.insert(t,le,{value:s.name});for(const n of s.components)$t(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function Ht(e,t,n){const s=new Map,r=n?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();s.set(i.id,t),e.insert(t,le,{value:i.name});for(const s of i.components){if("Sprite"===s.type&&r){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:n?.assetBaseUrl?`${n.assetBaseUrl}/${t}`:`/${t}`;try{const n=await r.loadTexture(s);e.texture=n.handle,o.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("BitmapText"===s.type&&r){const e=s.data;if("string"==typeof e.font&&e.font)try{const t=await r.loadBitmapFont(e.font,n?.assetBaseUrl);e.font=t}catch(t){console.warn(`Failed to load bitmap font: ${e.font}`,t),e.font=0}}if("SpineAnimation"===s.type&&r){const e=s.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await r.loadSpine(t,o,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}$t(e,t,s)}}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function $t(e,t,n){const s=n.data;switch(n.type){case"LocalTransform":e.insert(t,Z,s);break;case"Sprite":e.insert(t,te,s);break;case"Camera":e.insert(t,ne,s);break;case"Canvas":e.insert(t,se,s);break;case"Text":e.insert(t,je,s);break;case"BitmapText":e.insert(t,ae,s);break;case"SpineAnimation":e.insert(t,ce,s);break;case"UIRect":{const n=s;n.anchor&&!n.anchorMin&&(n.anchorMin={...n.anchor},n.anchorMax={...n.anchor},delete n.anchor),e.insert(t,Xe,n);break}case"UIMask":e.insert(t,Ge,s);break;case"RigidBody":e.insert(t,D,s);break;case"BoxCollider":e.insert(t,H,s);break;case"CircleCollider":e.insert(t,$,s);break;case"CapsuleCollider":e.insert(t,L,s);break;default:{const r=G(n.type);r?e.insert(t,r,s):console.warn(`Unknown component type: ${n.type}`);break}}}function Lt(e,t){const n=e.getEntitiesWithComponents([ne]);for(const s of n){const n=e.get(s,ne);n&&(n.aspectRatio=t,e.insert(s,ne,n))}}function Ot(e,t){const n=e.getEntitiesWithComponents([le]);for(const s of n){const n=e.get(s,le);if(n&&n.value===t)return s}return null}class jt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const n=this.cache_.get(e);if(void 0!==n)return n;const s=this.pending_.get(e);if(s)return s;const r=t();this.pending_.set(e,r);try{const t=await r;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class Nt{constructor(e){this.textureCache_=new jt,this.shaderCache_=new jt,this.jsonCache_=new jt,this.textCache_=new jt,this.binaryCache_=new jt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new jt,this.embedded_=new Map,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.module_=e,this.canvas_=h(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new zt(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n)}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);this.textureCache_.clear(),this.fontCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o);for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),l=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);return this.writeToVirtualFS(e,l)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>e.endsWith(".bmfont")?this.loadBmfontAsset(n):this.loadFntFile(n))}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return Ht(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];if(e.textures)for(const s of e.textures)n.push(this.loadTexture(s).then(e=>{t.textures.set(s,e)}));if(e.materials)for(const s of e.materials)n.push(this.loadMaterial(s).then(e=>{t.materials.set(s,e)}));if(e.spine)for(const s of e.spine){const e=`${s.skeleton}:${s.atlas}`;n.push(this.loadSpine(s.skeleton,s.atlas,s.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const s of e.json)n.push(this.loadJson(s).then(e=>{t.json.set(s,e)}));if(e.text)for(const s of e.text)n.push(this.loadText(s).then(e=>{t.text.set(s,e)}));if(e.binary)for(const s of e.binary)n.push(this.loadBinary(s).then(e=>{t.binary.set(s,e)}));return await Promise.all(n),t}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups)){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}async loadByAddress(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path);default:return this.loadBinary(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e)switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(e=>{t.textures.set(s.path,e)}));break;case"material":n.push(this.loadMaterial(s.path).then(e=>{t.materials.set(s.path,e)}));break;case"json":n.push(this.loadJson(s.path).then(e=>{t.json.set(s.path,e)}));break;case"text":n.push(this.loadText(s.path).then(e=>{t.text.set(s.path,e)}));break;default:n.push(this.loadBinary(s.path).then(e=>{t.binary.set(s.path,e)}))}return await Promise.all(n),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n)??n;return new Promise((n,r)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>r(new Error(`Failed to load image: ${e}`)),o.src=s})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const c=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:c,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e;if(!await l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:s,fragment:r}=this.parseEsShader(n);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return Et.createShader(s,r)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const n=await c(t);return JSON.parse(n)}const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):c(t)}const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):a(t)}const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Xt=fe(null,"Assets");class Vt{build(e){const t=e.wasmModule;t?e.insertResource(Xt,new Nt(t)):console.warn("AssetPlugin: No WASM module available")}}const Yt=new Vt;function Gt(e,t){const n=e.getResource(Xt);n&&n.registerEmbeddedAssets(t)}let qt=null,Kt=0,Jt=0,Qt=0;const Zt=new Float32Array(256);function en(e){qt=e,Kt=qt._malloc(64),Jt=qt._malloc(64),Qt=qt._malloc(1024)}function tn(){qt&&(Kt&&(qt._free(Kt),Kt=0),Jt&&(qt._free(Jt),Jt=0),Qt&&(qt._free(Qt),Qt=0)),qt=null}function nn(){if(!qt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return qt}const sn={r:1,g:1,b:1,a:1},rn={begin(e){const t=nn();t.HEAPF32.set(e,Kt/4),t.draw_begin(Kt)},end(){nn().draw_end()},line(e,t,n,s=1){nn().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rect(e,t,n,s=!0){nn().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rectOutline(e,t,n,s=1){nn().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},circle(e,t,n,s=!0,r=32){nn().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},circleOutline(e,t,n,s=1,r=32){nn().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=sn){nn().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)},textureRotated(e,t,n,s,r=sn){nn().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){nn().draw_setLayer(e)},setDepth(e){nn().draw_setDepth(e)},getDrawCallCount:()=>qt?qt.draw_getDrawCallCount():0,getPrimitiveCount:()=>qt?qt.draw_getPrimitiveCount():0,setBlendMode(e){nn().draw_setBlendMode(e)},setDepthTest(e){nn().draw_setDepthTest(e)},drawMesh(e,t,n){const s=nn();s.HEAPF32.set(n,Jt/4),s.draw_mesh(e,t,Jt)},drawMeshWithMaterial(e,t,n){const s=nn(),r=Et.get(t);if(!r)return;if(rn.setBlendMode(r.blendMode),rn.setDepthTest(r.depthTest),0===r.uniforms.size)return void rn.drawMesh(e,r.shader,n);s.HEAPF32.set(n,Jt/4);let o=0,i=0;for(const[e,t]of r.uniforms){const n=an(e);if(!(n<0)){if(xt(t))Zt[o++]=10,Zt[o++]=n,Zt[o++]=t.slot??i++,Zt[o++]=t.textureId;else if("number"==typeof t)Zt[o++]=1,Zt[o++]=n,Zt[o++]=t;else if(Array.isArray(t)){Zt[o++]=t.length,Zt[o++]=n;for(let e=0;e<t.length;e++)Zt[o++]=t[e]}else"w"in t?(Zt[o++]=4,Zt[o++]=n,Zt[o++]=t.x,Zt[o++]=t.y,Zt[o++]=t.z,Zt[o++]=t.w):"z"in t?(Zt[o++]=3,Zt[o++]=n,Zt[o++]=t.x,Zt[o++]=t.y,Zt[o++]=t.z):(Zt[o++]=2,Zt[o++]=n,Zt[o++]=t.x,Zt[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(Zt.subarray(0,o),Qt/4),s.draw_meshWithUniforms(e,r.shader,Jt,Qt,o)):s.draw_mesh(e,r.shader,Jt)}},on={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 an(e){return on[e]??-1}var cn;!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"}(cn||(cn={}));let ln=null,un=0,hn=0,dn=0;function fn(e){ln=e,un=ln._malloc(262144),hn=ln._malloc(65536),dn=ln._malloc(256)}function pn(){ln&&(un&&ln._free(un),hn&&ln._free(hn),dn&&ln._free(dn),un=0,hn=0,dn=0),ln=null}function mn(){if(!ln)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ln}const _n={create(e){const t=mn(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,un/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,dn,r).set(o),t.geometry_init(n,un,s,dn,r,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,hn,s).set(e.indices),t.geometry_setIndices16(n,hn,s)}else{new Uint32Array(t.HEAPU8.buffer,hn,s).set(e.indices),t.geometry_setIndices32(n,hn,s)}}return n},updateVertices(e,t,n=0){const s=mn(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,un/4),s.geometry_updateVertices(e,un,r,n)},release(e){e>0&&mn().geometry_release(e)},isValid:e=>!(!ln||e<=0)&&ln.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return _n.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:cn.Float2},{name:"a_texCoord",type:cn.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,c=(Math.sin(r)+1)/2;n.push(o,i,a,c)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return _n.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:cn.Float2},{name:"a_texCoord",type:cn.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-n);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return _n.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:cn.Float2},{name:"a_texCoord",type:cn.Float2}],indices:new Uint16Array(i)})}};let gn=null;function yn(e){gn=e}function wn(){gn&&vn.isInitialized()&&vn.shutdown(),gn=null}function xn(){if(!gn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return gn}const vn={init:(e,t)=>xn().postprocess_init(e,t),shutdown(){xn().postprocess_shutdown()},resize(e,t){xn().postprocess_resize(e,t)},addPass:(e,t)=>xn().postprocess_addPass(e,t),removePass(e){xn().postprocess_removePass(e)},setEnabled(e,t){xn().postprocess_setPassEnabled(e,t)},isEnabled:e=>xn().postprocess_isPassEnabled(e),setUniform(e,t,n){xn().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){xn().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){xn().postprocess_begin()},end(){xn().postprocess_end()},getPassCount:()=>xn().postprocess_getPassCount(),isInitialized:()=>!!gn&&gn.postprocess_isInitialized(),setBypass(e){xn().postprocess_setBypass(e)},isBypassed:()=>!gn||gn.postprocess_isBypassed(),createBlur:()=>Et.createShader(bn,"#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:()=>Et.createShader(bn,"#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:()=>Et.createShader(bn,"#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:()=>Et.createShader(bn,"#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")},bn="#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 Pn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Pn||(Pn={}));let Sn=null,Cn=0;function Mn(e){Sn=e,Cn=Sn._malloc(64)}function Tn(){Sn&&Cn&&(Sn._free(Cn),Cn=0),Sn=null}const En={init(e,t){Sn?.renderer_init(e,t)},resize(e,t){Sn?.renderer_resize(e,t)},begin(e,t){Sn&&Cn&&(Sn.HEAPF32.set(e,Cn/4),Sn.renderer_begin(Cn,t??0))},flush(){Sn?.renderer_flush()},end(){Sn?.renderer_end()},submitSprites(e){Sn&&Sn.renderer_submitSprites(e._cpp)},submitBitmapText(e){Sn&&Sn.renderer_submitBitmapText(e._cpp)},submitSpine(e){Sn&&Sn.renderer_submitSpine?.(e._cpp)},setStage(e){Sn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Sn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Sn?.renderer_releaseTarget(e)},getTargetTexture:e=>Sn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Sn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Sn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Sn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){Sn?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){Sn?.renderer_clearBuffers(e)},getStats:()=>Sn?{drawCalls:Sn.renderer_getDrawCalls(),triangles:Sn.renderer_getTriangles(),sprites:Sn.renderer_getSprites(),text:Sn.renderer_getText(),spine:Sn.renderer_getSpine?.()??0,meshes:Sn.renderer_getMeshes(),culled:Sn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let An=null;function Rn(e){An=e}function Fn(){An=null}const Un={enable(){An?.gl_enableErrorCheck(!0)},disable(){An?.gl_enableErrorCheck(!1)},check:e=>An?.gl_checkErrors(e)??0,diagnose(){An?.renderer_diagnose()}},Bn=new Map;function In(e,t){Bn.set(e,t)}function kn(e){Bn.delete(e)}function Wn(){Bn.clear()}class zn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}setSpineRenderer(e){this.spineRenderer_=e}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(En.resize(s,r),vn.isInitialized()&&vn.getPassCount()>0&&vn.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),En.setViewport(0,0,s,r),En.clearBuffers(3),En.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),En.submitSprites(t),En.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):En.submitSpine(t),En.flush(),this.executeDrawCallbacks(n,o),En.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;En.setViewport(s.x,s.y,s.w,s.h),En.setScissor(s.x,s.y,s.w,s.h,!0),En.clearBuffers(r),En.setScissor(0,0,0,0,!1),En.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),En.submitSprites(t),En.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):En.submitSpine(t),En.flush(),this.executeDrawCallbacks(n,o),En.end()}executeDrawCallbacks(e,t){const n=Bn;if(n.size>0){rn.begin(e);const s=[];for(const[e,r]of n.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}rn.end();for(const e of s)kn(e)}}}class Dn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.runSchedule(Me.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Me.FixedPreUpdate),this.runSchedule(Me.FixedUpdate),this.runSchedule(Me.FixedPostUpdate);this.runSchedule(Me.PreUpdate),this.runSchedule(Me.Update),this.runSchedule(Me.PostUpdate),this.runSchedule(Me.Last),requestAnimationFrame(this.mainLoop)},this.world_=new He,this.resources_=new ge;for(const e of Object.values(Me))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Dn}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(Me.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Me.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new Be(this.world_,this.resources_),this.resources_.insert(ye,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Me.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Fn(),Tn(),wn(),pn(),Mt(),tn()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(ye);t.delta=e,t.elapsed+=e,t.frameCount++}}function Hn(e,t){const n=Dn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),en(e),Ct(e),fn(e),yn(e),Mn(e),Rn(e);const r=new zn;n.pipeline_=r;let o=d();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));n.insertResource(ut,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const a={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:a}=i(),c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;En.setClearColor(e.r,e.g,e.b,e.a)}const l=(d()-o)/1e3;En.resize(t,a),vn.isInitialized()&&vn.getPassCount()>0&&!vn.isBypassed()&&vn.resize(t,a);const u=function(e,t,n,s){const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),c={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},l=c.w*n/(c.h*s);let u,h=0,d=0;if(1===r.projectionType){if(d=r.orthoSize,o){d=On(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,l,o.scaleMode,o.matchWidthOrHeight)}h=d*l,u=Nn(-h,h,-d,d,-r.farPlane,r.farPlane)}else u=Vn(r.fov*Math.PI/180,l,r.nearPlane,r.farPlane);const f=Gn(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:qn(u,f),viewportRect:c,clearFlags:r.clearFlags,priority:r.priority,halfW:h,halfH:d,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}(e,s,t,a),h=n.getResource(ut);if(u.length>0){const e=u[0],n=e.viewportRect;h.viewProjection.set(e.viewProjection),h.vpX=Math.round(n.x*t),h.vpY=Math.round((1-n.y-n.h)*a),h.vpW=Math.round(n.w*t),h.vpH=Math.round(n.h*a),h.screenW=t,h.screenH=a,h.worldLeft=e.cameraX-e.halfW,h.worldRight=e.cameraX+e.halfW,h.worldBottom=e.cameraY-e.halfH,h.worldTop=e.cameraY+e.halfH,h.valid=!0}else h.valid=!1;if(0===u.length)r.render({registry:{_cpp:s},viewProjection:Ln,width:t,height:a,elapsed:l});else{for(const e of u){const n=e.viewportRect,o=Math.round(n.x*t),i=Math.round((1-n.y-n.h)*a),c=Math.round(n.w*t),u=Math.round(n.h*a);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:c,h:u},clearFlags:e.clearFlags,elapsed:l})}En.setViewport(0,0,t,a)}}};return n.addSystemToSchedule(Me.Last,a),n.addPlugin(Yt),n.addPlugin(ze),n.addPlugin(Ye),n.addPlugin(st),n.addPlugin(yt),n.addPlugin(ft),n}function $n(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Ln=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function On(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}}}const jn=new Float32Array(16);function Nn(e,t,n,s,r,o){const i=jn;i.fill(0);const a=t-e,c=s-n,l=o-r;return i[0]=2/a,i[5]=2/c,i[10]=-2/l,i[12]=-(t+e)/a,i[13]=-(s+n)/c,i[14]=-(o+r)/l,i[15]=1,i}const Xn=new Float32Array(16);function Vn(e,t,n,s){const r=Xn;r.fill(0);const o=1/Math.tan(e/2),i=n-s;return r[0]=o/t,r[5]=o,r[10]=(s+n)/i,r[11]=-1,r[14]=2*s*n/i,r}const Yn=new Float32Array(16);function Gn(e,t,n){const s=Yn;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}function qn(e,t){const n=new Float32Array(16);for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}async function Kn(e,t){if(t)return t();return(0,(await import(e)).default)()}const Jn=fe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Qn=fe(null,"PhysicsAPI");function Zn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function es(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class ts{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Jn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Kn(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([se]);for(const n of t){const t=e.world.get(n,se);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(Me.PostUpdate,Ee([pe(ye)],a=>{const c=i.getEntitiesWithComponents([D,Z,ee]),l=new Set;for(const r of c){l.add(r);const a=i.get(r,D),c=i.get(r,ee);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=Zn(c.rotation);s._physics_createBody(r,a.bodyType,c.position.x*o,c.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),ns(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===O.Kinematic){const e=Zn(c.rotation);s._physics_setBodyTransform(r,c.position.x*o,c.position.y*o,e)}}for(const e of t)l.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,c=t.HEAPF32[s+2]*n,l=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,Z);if(!u)continue;let h=a,d=c,f=l;if(e.world.has(i,oe)){const t=e.world.get(i,oe);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ee)){const n=e.world.get(t.entity,ee),s=Zn(n.rotation),r=a-n.position.x,o=c-n.position.y,i=Math.cos(-s),u=Math.sin(-s);h=(r*i-o*u)/(0!==n.scale.x?n.scale.x:1),d=(r*u+o*i)/(0!==n.scale.y?n.scale.y:1),f=l-s}}u.position.x=h,u.position.y=d;const p=es(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(i,Z,u)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],c=t._physics_getSensorEnterCount();if(c>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<c;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const l=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;l.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Jn,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:l})}(e,s,r)},{name:"PhysicsSystem"})),e.__physicsModule=s,e.insertResource(Qn,ss._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=s}}function ns(e,t,n){const s=e.world;if(s.has(n,H)){const e=s.get(n,H);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,$)){const e=s.get(n,$);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,L)){const e=s.get(n,L);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class ss{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(ss.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function rs(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function os(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function is(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,c=e.rotation.y,l=e.rotation.z,u=e.rotation.w,h=a+a,d=c+c,f=l+l,p=a*h,m=a*d,_=a*f,g=c*d,y=c*f,w=l*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(g+w))*r,(m+b)*r,(_-v)*r,0,(m-b)*o,(1-(p+w))*o,(y+x)*o,0,(_+v)*i,(y-x)*i,(1-(p+g))*i,0,e.position.x,e.position.y,e.position.z,1])}async function as(e,t,n,s,r,o,i){const a=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=rs(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,a);let c={},l=null;if(r&&(l=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),c=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const c=r.resolvePath(i),l=r.resolvePath(a);try{const s=r.readText(a),u=c.endsWith(".skel");let h,d;if(u){const e=r.readBinary(i);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=r.readText(i),n=(new TextEncoder).encode(e);d=n.length,h=t._malloc(d+1),t.HEAPU8.set(n,h),t.HEAPU8[h+d]=0}const f=n.loadSkeleton(h,d,s,s.length,u);if(t._free(h),f<0)continue;o[i]=f;const p=os(s),m=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=rs(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,l,n,s)),o){new ts("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const u=function(e,t){const n={},s={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===n[r])try{const e=JSON.parse(t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=Et.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=Et.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),h=Dt(e.world,n);if(function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const r=e.get(t,te);r&&(r.texture=n[s.data.texture]||0,e.insert(t,te,r))}}}(e.world,n,a,h),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const r=n[s.data.material]||0;if(r)if("Sprite"===s.type){const n=e.get(t,te);n&&(n.material=r,e.insert(t,te,n))}else if("SpineAnimation"===s.type){const n=e.get(t,ce);n&&(n.material=r,e.insert(t,ce,n))}}}}(e.world,n,u,h),r&&l){const s=function(e,t,n,s){const r={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const c=s.get(o.id);void 0!==c&&(r[c]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(l,n,c,h);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let c=a-o;o=a,(c<=0||c>.5)&&(c=1/60);const l=e.world;for(const e in r){const o=Number(e),i=r[e],a=l.has(o,ce)?l.get(o,ce):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&s.update(i,c*h);let d=0;if(l.has(o,ee)){const e=is(l.get(o,ee),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,c=2*o,l=n._malloc(a),u=n._malloc(c),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,l,u,h,f);const p=n.HEAPU32[h>>2],m=n.HEAPU32[f>>2],_=new Float32Array(n.HEAPF32.buffer,l,8*r),g=new Uint16Array(n.HEAPU8.buffer,u,o),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(_,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(g),t.renderer_submitTriangles(y,r,w,o,p,m,d),t._free(y),t._free(w),n._free(l),n._free(u),n._free(h),n._free(f)}d&&t._free(d)}})}(e,t,r,l,s)}}class cs{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set;for(const s of e.entities)for(const e of s.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&(s.endsWith(".skel")?n.add(s):t.add(s)),r&&t.add(r)}"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const s=[];for(const e of t)s.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of n)s.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(s)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class ls{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 cs(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.__spineInitPromise;if(r){s=(await r).controller.raw}await as(this.app_,this.app_.wasmModule,t,n,s),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([ne]);for(const s of n){if(e.get(s,ne).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const s=e.getEntitiesWithComponents([se]);for(const r of s){const s=e.get(r,se);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,Z,o);const i={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3};e.insert(r,ne,i)}}}const us={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=En.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:En.getTargetTexture(n),width:e.width,height:e.height}},release(e){En.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(En.releaseRenderTarget(e._handle),us.create({width:t,height:n,depth:!0})),begin(e,t){En.begin(t,e._handle)},end(){En.end()},getDepthTexture:e=>En.getTargetDepthTexture(e._handle)};let hs=!1;function ds(e){hs=e}function fs(){return hs}function ps(){return!hs}T||(T=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await f(n,s);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:n}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return p(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),n=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?n[s++]=r:r<2048?(n[s++]=192|r>>6,n[s++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,n[s++]=240|r>>18,n[s++]=128|r>>12&63,n[s++]=128|r>>6&63,n[s++]=128|63&r):(n[s++]=224|r>>12,n[s++]=128|r>>6&63,n[s++]=128|63&r)}return n.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let n="";for(let e=0;e<t.length;){const s=t[e];if(s<128)n+=String.fromCharCode(s),e++;else if(192==(224&s))n+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))n+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=E;export{Dn as App,Vt as AssetPlugin,Nt as AssetServer,Xt as Assets,jt as AsyncCache,ae as BitmapText,wt as BlendMode,O as BodyType,H as BoxCollider,at as Button,it as ButtonState,ne as Camera,se as Canvas,L as CapsuleCollider,ie as Children,$ as CircleCollider,Pe as Commands,Ce as CommandsInstance,cn as DataType,rn as Draw,Se as EntityCommands,Un as GLDebug,_n as Geometry,A as INVALID_ENTITY,F as INVALID_FONT,R as INVALID_TEXTURE,ke as Input,We as InputPlugin,Ie as InputState,rt as Interactable,Z as LocalTransform,Et as Material,zt as MaterialLoader,we as Mut,le as Name,oe as Parent,ss as Physics,Jn as PhysicsEvents,ts as PhysicsPlugin,vn as PostProcess,ls as PreviewPlugin,ve as Query,be as QueryInstance,zn as RenderPipeline,Pn as RenderStage,us as RenderTexture,En as Renderer,pe as Res,me as ResMut,D as RigidBody,Me as Schedule,pt as ScreenSpace,Wt as ShaderSources,ce as SpineAnimation,te as Sprite,Be as SystemRunner,je as Text,$e as TextAlign,Oe as TextOverflow,Ve as TextPlugin,Ne as TextRenderer,Le as TextVerticalAlign,ye as Time,ut as UICameraInfo,ct as UIEventQueue,lt as UIEvents,ot as UIInteraction,dt as UIInteractionPlugin,gt as UILayoutPlugin,Ge as UIMask,nt as UIMaskPlugin,Xe as UIRect,re as Velocity,cs as WebAssetProvider,He as World,ee as WorldTransform,Fe as addStartupSystem,Re as addSystem,Ue as addSystemToSchedule,Yt as assetPlugin,Wn as clearDrawCallbacks,q as clearUserComponents,k as color,mt as computeUIRectLayout,tt as createMaskProcessor,Hn as createWebApp,V as defineComponent,fe as defineResource,Ee as defineSystem,Y as defineTag,Ot as findEntityByName,$n as flushPendingSystems,he as getComponentDefaults,t as getPlatform,s as getPlatformType,G as getUserComponent,en as initDrawAPI,Rn as initGLDebugAPI,fn as initGeometryAPI,Ct as initMaterialAPI,yn as initPostProcessAPI,Mn as initRendererAPI,ze as inputPlugin,qe as intersectRects,Je as invertMatrix4,Q as isBuiltinComponent,fs as isEditor,n as isPlatformInitialized,ps as isRuntime,xt as isTextureRef,r as isWeChat,o as isWeb,$t as loadComponent,Kn as loadPhysicsModule,as as loadRuntimeScene,Dt as loadSceneData,Ht as loadSceneWithAssets,i as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,Ze as pointInWorldRect,W as quat,In as registerDrawCallback,Gt as registerEmbeddedAssets,kt as registerMaterialCallback,Qe as screenToWorld,ds as setEditorMode,tn as shutdownDrawAPI,Fn as shutdownGLDebugAPI,pn as shutdownGeometryAPI,Mt as shutdownMaterialAPI,wn as shutdownPostProcessAPI,Tn as shutdownRendererAPI,Ye as textPlugin,ft as uiInteractionPlugin,yt as uiLayoutPlugin,st as uiMaskPlugin,kn as unregisterDrawCallback,Lt as updateCameraAspectRatio,U as vec2,B as vec3,I as vec4,Ke as worldRectToScreen,w as wxFileExists,x as wxFileExistsSync,C as wxGetImagePixels,S as wxLoadImage,M 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 899543dda..68bfcea06 100644--- a/desktop/public/sdk/esm/esengine.d.ts+++ b/desktop/public/sdk/esm/esengine.d.ts@@ -782,8 +782,11 @@ interface TextData {declare const Text: ComponentDef<TextData>;interface UIRectData {+ anchorMin: Vec2;+ anchorMax: Vec2;+ offsetMin: Vec2;+ offsetMax: Vec2;size: Vec2;- anchor: Vec2;pivot: Vec2;}declare const UIRect: ComponentDef<UIRectData>;@@ -853,6 +856,124 @@ declare class UIMaskPlugin implements Plugin {}declare const uiMaskPlugin: UIMaskPlugin;+interface ScreenRect {+ x: number;+ y: number;+ w: number;+ h: number;+}+declare function intersectRects(a: ScreenRect, b: ScreenRect): ScreenRect;+declare function worldRectToScreen(worldX: number, worldY: number, worldW: number, worldH: number, pivotX: number, pivotY: number, vp: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): ScreenRect;+declare function invertMatrix4(m: Float32Array, result?: Float32Array): Float32Array;+declare function screenToWorld(screenX: number, screenY: number, inverseVP: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): {+ x: number;+ y: number;+};+declare function pointInWorldRect(px: number, py: number, worldX: number, worldY: number, worldW: number, worldH: number, pivotX: number, pivotY: number): boolean;++interface InteractableData {+ enabled: boolean;+}+declare const Interactable: ComponentDef<InteractableData>;++interface UIInteractionData {+ hovered: boolean;+ pressed: boolean;+ justPressed: boolean;+ justReleased: boolean;+}+declare const UIInteraction: ComponentDef<UIInteractionData>;++declare enum ButtonState {+ Normal = 0,+ Hovered = 1,+ Pressed = 2,+ Disabled = 3+}+interface ButtonTransition {+ normalColor: Color;+ hoveredColor: Color;+ pressedColor: Color;+ disabledColor: Color;+}+interface ButtonData {+ state: ButtonState;+ transition: ButtonTransition | null;+}+declare const Button: ComponentDef<ButtonData>;++type UIEventType = 'click' | 'press' | 'release' | 'hover_enter' | 'hover_exit';+interface UIEvent {+ entity: Entity;+ type: UIEventType;+}+declare class UIEventQueue {+ private events_;+ emit(entity: Entity, type: UIEventType): void;+ drain(): UIEvent[];+ query(type: UIEventType): UIEvent[];+ hasEvent(entity: Entity, type: UIEventType): boolean;+}+declare const UIEvents: ResourceDef<UIEventQueue>;++interface UICameraData {+ viewProjection: Float32Array;+ vpX: number;+ vpY: number;+ vpW: number;+ vpH: number;+ screenW: number;+ screenH: number;+ worldLeft: number;+ worldBottom: number;+ worldRight: number;+ worldTop: number;+ valid: boolean;+}+declare const UICameraInfo: ResourceDef<UICameraData>;++declare const ScreenSpace: ComponentDef<{}>;++interface LayoutRect {+ left: number;+ bottom: number;+ right: number;+ top: number;+}+interface LayoutResult {+ centerX: number;+ centerY: number;+ width: number;+ height: number;+ rect: LayoutRect;+}+declare function computeUIRectLayout(anchorMin: {+ x: number;+ y: number;+}, anchorMax: {+ x: number;+ y: number;+}, offsetMin: {+ x: number;+ y: number;+}, offsetMax: {+ x: number;+ y: number;+}, size: {+ x: number;+ y: number;+}, parentRect: LayoutRect): LayoutResult;++declare class UILayoutPlugin implements Plugin {+ build(app: App): void;+}+declare const uiLayoutPlugin: UILayoutPlugin;++declare class UIInteractionPlugin implements Plugin {+ build(app: App): void;+}+declare const uiInteractionPlugin: UIInteractionPlugin;+/*** @file blend.ts* @brief Blend mode definitions for rendering@@ -1130,6 +1251,22 @@ interface AssetBundle {text: Map<string, string>;binary: Map<string, ArrayBuffer>;}+interface AddressableManifestAsset {+ path: string;+ address?: string;+ type: string;+ size: number;+ labels: string[];+}+interface AddressableManifestGroup {+ bundleMode: string;+ labels: string[];+ assets: Record<string, AddressableManifestAsset>;+}+interface AddressableManifest {+ version: '2.0';+ groups: Record<string, AddressableManifestGroup>;+}declare class AssetServer {baseUrl?: string;private module_;@@ -1145,6 +1282,10 @@ declare class AssetServer {private ctx_;private fontCache_;private embedded_;+ private addressableManifest_;+ private addressIndex_;+ private labelIndex_;+ private groupAssets_;constructor(module: ESEngineModule);registerEmbeddedAssets(assets: Record<string, string>): void;/**@@ -1180,6 +1321,12 @@ declare class AssetServer {loadBinary(path: string, options?: FileLoadOptions): Promise<ArrayBuffer>;loadScene(world: World, sceneData: SceneData): Promise<Map<number, Entity>>;loadAll(manifest: AssetManifest): Promise<AssetBundle>;+ setAddressableManifest(manifest: AddressableManifest): void;+ loadByAddress(address: string): Promise<TextureInfo | LoadedMaterial | unknown>;+ loadByLabel(label: string): Promise<AssetBundle>;+ loadGroup(groupName: string): Promise<AssetBundle>;+ private loadAddressableAsset;+ private loadAddressableAssets;private textureCacheKey;private loadTextureWithFlip;private loadTextureInternal;@@ -1951,5 +2098,5 @@ declare const GLDebug: {diagnose(): void;};-export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BitmapText, BlendMode, BodyType, BoxCollider, Camera, Canvas, CapsuleCollider, Children, CircleCollider, Commands, CommandsInstance, DataType, Draw, EntityCommands, GLDebug, Geometry, INVALID_ENTITY, INVALID_FONT, INVALID_TEXTURE, Input, InputPlugin, InputState, LocalTransform, Material, MaterialLoader, Mut, Name, Parent, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PreviewPlugin, Query, QueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, RigidBody, Schedule, ShaderSources, SpineAnimation, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIMask, UIMaskPlugin, UIRect, Velocity, WebAssetProvider, World, WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, assetPlugin, clearDrawCallbacks, clearUserComponents, color, createMaskProcessor, createWebApp, defineComponent, defineResource, defineSystem, defineTag, findEntityByName, flushPendingSystems, getComponentDefaults, getPlatform, getPlatformType, getUserComponent, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, inputPlugin, isBuiltinComponent, isEditor, isPlatformInitialized, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, setEditorMode, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textPlugin, uiMaskPlugin, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4 };-export type { AnyComponentDef, AssetBundle, AssetManifest, AssetsData, BitmapTextData, BoxColliderData, BuiltinComponentDef, CameraData, CameraRenderParams, CanvasData, CapsuleColliderData, ChildrenData, CircleColliderData, CollisionEnterEvent, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DrawAPI, DrawCallback, ESEngineModule, Entity, FileLoadOptions, FontHandle, GeometryHandle, GeometryOptions, InferParam, InferParams, LoadedMaterial, LocalTransformData, MaskProcessorFn, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, NameData, ParentData, PhysicsEventsData, PhysicsModuleFactory, PhysicsPluginConfig, PhysicsWasmModule, PlatformAdapter, PlatformRequestOptions, PlatformResponse, PlatformType, Plugin, Quat, QueryDescriptor, QueryResult, RenderParams, RenderStats, RenderTargetHandle, RenderTextureHandle, RenderTextureOptions, ResDescriptor, ResMutDescriptor, ResourceDef, RigidBodyData, RuntimeAssetProvider, SceneComponentData, SceneData, SceneEntityData, SceneLoadOptions, SensorEvent, ShaderHandle, ShaderLoader, SliceBorder, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteData, SystemDef, SystemParam, TextData, TextRenderResult, TextureHandle, TextureInfo, TextureRef, TimeData, UIMaskData, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WorldTransformData };+export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BitmapText, BlendMode, BodyType, BoxCollider, Button, ButtonState, Camera, Canvas, CapsuleCollider, Children, CircleCollider, Commands, CommandsInstance, DataType, Draw, EntityCommands, GLDebug, Geometry, INVALID_ENTITY, INVALID_FONT, INVALID_TEXTURE, Input, InputPlugin, InputState, Interactable, LocalTransform, Material, MaterialLoader, Mut, Name, Parent, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PreviewPlugin, Query, QueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, RigidBody, Schedule, ScreenSpace, ShaderSources, SpineAnimation, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UICameraInfo, UIEventQueue, UIEvents, UIInteraction, UIInteractionPlugin, UILayoutPlugin, UIMask, UIMaskPlugin, UIRect, Velocity, WebAssetProvider, World, WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, assetPlugin, clearDrawCallbacks, clearUserComponents, color, computeUIRectLayout, createMaskProcessor, createWebApp, defineComponent, defineResource, defineSystem, defineTag, findEntityByName, flushPendingSystems, getComponentDefaults, getPlatform, getPlatformType, getUserComponent, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, inputPlugin, intersectRects, invertMatrix4, isBuiltinComponent, isEditor, isPlatformInitialized, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInWorldRect, quat, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, screenToWorld, setEditorMode, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textPlugin, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, worldRectToScreen };+export type { AddressableManifest, AddressableManifestAsset, AddressableManifestGroup, AnyComponentDef, AssetBundle, AssetManifest, AssetsData, BitmapTextData, BoxColliderData, BuiltinComponentDef, ButtonData, ButtonTransition, CameraData, CameraRenderParams, CanvasData, CapsuleColliderData, ChildrenData, CircleColliderData, CollisionEnterEvent, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DrawAPI, DrawCallback, ESEngineModule, Entity, FileLoadOptions, FontHandle, GeometryHandle, GeometryOptions, InferParam, InferParams, InteractableData, LayoutRect, LayoutResult, LoadedMaterial, LocalTransformData, MaskProcessorFn, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, NameData, ParentData, PhysicsEventsData, PhysicsModuleFactory, PhysicsPluginConfig, PhysicsWasmModule, PlatformAdapter, PlatformRequestOptions, PlatformResponse, PlatformType, Plugin, Quat, QueryDescriptor, QueryResult, RenderParams, RenderStats, RenderTargetHandle, RenderTextureHandle, RenderTextureOptions, ResDescriptor, ResMutDescriptor, ResourceDef, RigidBodyData, RuntimeAssetProvider, SceneComponentData, SceneData, SceneEntityData, SceneLoadOptions, ScreenRect, SensorEvent, ShaderHandle, ShaderLoader, SliceBorder, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteData, SystemDef, SystemParam, TextData, TextRenderResult, TextureHandle, TextureInfo, TextureRef, TimeData, UICameraData, UIEvent, UIEventType, UIInteractionData, UIMaskData, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WorldTransformData };diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.jsindex 05b24fb18..90313b7a0 100644--- a/desktop/public/sdk/esm/esengine.js+++ b/desktop/public/sdk/esm/esengine.js@@ -1,2 +1,2 @@-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.module}}createImage(){return new Image}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),r=t=>e.onKeyUp(t.code),i=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},o=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},u=()=>{e.onPointerUp(0)},h=t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)};document.addEventListener("keydown",s),document.addEventListener("keyup",r),n.addEventListener("mousemove",i),n.addEventListener("mousedown",o),n.addEventListener("mouseup",a),n.addEventListener("touchstart",c),n.addEventListener("touchmove",l),n.addEventListener("touchend",u),n.addEventListener("wheel",h),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",r),n.removeEventListener("mousemove",i),n.removeEventListener("mousedown",o),n.removeEventListener("mouseup",a),n.removeEventListener("touchstart",c),n.removeEventListener("touchmove",l),n.removeEventListener("touchend",u),n.removeEventListener("wheel",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=0,_=4294967295,m=0,g=(e=0,t=0)=>({x:e,y:t}),y=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),w=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),x=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),v=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function b(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const P=b("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),S=b("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),C=b("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),E=b("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),T={Static:0,Kinematic:1,Dynamic:2};let M=0;function A(e,t){const n=++M;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function R(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function F(e,t){const n=R(),s=n.get(e);if(s)return s;const r=A(e,t);return n.set(e,r),I(e,t,!1),r}function U(e){const t=R(),n=t.get(e);if(n)return n;const s=A(e,{});return t.set(e,s),I(e,{},!0),s}function B(e){return R().get(e)}function k(){R().clear()}function I(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function z(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function L(e){return!0===e._builtin}const D=z("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),$=z("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),H=z("Sprite",{texture:_,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),W=z("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),O=z("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),N=z("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),V=z("Parent",{entity:0}),j=z("Children",{entities:[]}),X=z("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:0}),G=z("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),Y={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},K={LocalTransform:D,WorldTransform:$,Sprite:H,Camera:W,Canvas:O,Velocity:N,Parent:V,Children:j,BitmapText:X,SpineAnimation:G,RigidBody:P,BoxCollider:S,CircleCollider:C,CapsuleCollider:E};function q(e){const t=K[e];if(t)return{...t._default};const n=B(e);return n?{...n._default}:null}let J=0;function Q(e,t){const n=++J;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function Z(e){return{_type:"res",_resource:e}}function ee(e){return{_type:"res_mut",_resource:e}}class te{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}}class ne{constructor(){this.resources_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id)}getResMut(e){return new te(this.get(e),t=>this.set(e,t))}}const se=Q({delta:0,elapsed:0,frameCount:0},"Time");function re(e){return{_type:"mut",_component:e}}function ie(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function oe(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{ie(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class ae{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>ie(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with)}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),r=n.length,i=e.length>0,o=t.length>0,a=new Array(r+1);let c=null,l=[];try{for(const u of s){if(null!==c&&i){for(let e=0;e<l.length;e++){const t=l[e];this.world_.insert(c,t.component,t.data)}l.length=0}if(o){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(u,t[n])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,n[e]);if(i){for(let t=0;t<e.length;t++){const s=e[t];l.push({component:n[s],data:a[s+1]})}c=u}yield a}}finally{if(null!==c&&i)for(let e=0;e<l.length;e++){const t=l[e];this.world_.insert(c,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function ce(){return{_type:"commands"}}class le{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=L(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class ue{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new le(this,null);return this.spawned_.push(e),e}entity(e){return new le(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var he;!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(he||(he={}));let de=0;function fe(e,t,n){const s=++de;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function pe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function _e(e){pe().push({schedule:he.Update,system:e})}function me(e){pe().push({schedule:he.Startup,system:e})}function ge(e,t){pe().push({schedule:e,system:t})}class ye{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof ue&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new ae(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new ue(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class we{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const xe=Q(new we,"Input");class ve{constructor(e){this.target_=e??null}build(e){const n=new we;e.insertResource(xe,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(he.First,fe([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const be=new ve;function Pe(e){if(null==e||"object"!=typeof e||Array.isArray(e))return e;const t=e;if("r"in t&&"g"in t&&"b"in t&&"a"in t&&!("x"in t))return{x:t.r,y:t.g,z:t.b,w:t.a};const n={};for(const e of Object.keys(t)){const s=t[e];n[e]=null==s||"object"!=typeof s||Array.isArray(s)?s:Pe(s)}return n}class Se{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return L(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return L(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return L(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){L(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const s={...t._default,...n};if(this.cppRegistry_){const n=`add${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e,Pe(s))}return s}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const n=`get${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const n=`has${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const n=`remove${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e)}insertScript(e,t,n){const s=t.create(n);return this.getStorage(t).set(e,s),s}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();let t=null,n=1/0;for(const s of e)if(!L(s)){const e=this.tsStorage_.get(s._id),r=e?e.size:0;r<n&&(n=r,t=e??null)}const s=[],r=t?t.keys():this.entities_;for(const t of r){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&s.push(t)}return s}}var Ce,Ee,Te;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Ce||(Ce={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Ee||(Ee={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Te||(Te={}));const Me=F("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Ce.Left,verticalAlign:Ee.Top,wordWrap:!0,overflow:Te.Visible,lineHeight:1.2,dirty:!0});class Ae{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,i=r?t.size.x:0,o=r?t.size.y:0,a=e.wordWrap&&r;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=r?Math.ceil(i):h+2*u,p=r?Math.ceil(o):d+2*u;if(r&&e.overflow===Te.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const _=Math.round(255*e.color.r),m=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${_}, ${m}, ${g}, ${y})`,r&&e.overflow===Te.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=c.length*l;let x;if(r)switch(e.verticalAlign){case Ee.Top:x=u;break;case Ee.Middle:x=(p-w)/2;break;case Ee.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let s;switch(e.align){case Ce.Left:s=u;break;case Ce.Center:s=f/2;break;case Ce.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=l}r&&e.overflow===Te.Clip&&n.restore();const b=n.getImageData(0,0,f,p),P=new Uint8Array(b.data.buffer),S=this.module.getResourceManager(),C=this.module._malloc(P.length);this.module.HEAPU8.set(P,C);const E=S.createTexture(f,p,C,P.length,1,!0);return this.module._free(C),{textureHandle:E,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const r=this.renderText(t,n);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case Ce.Left:return"left";case Ce.Center:return"center";case Ce.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const Re=F("UIRect",{size:{x:100,y:100},anchor:{x:.5,y:.5},pivot:{x:.5,y:.5}});class Fe{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Ae(t),s=e.world;e.addSystemToSchedule(he.PreUpdate,fe([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Me));const e=s.getEntitiesWithComponents([Me]);for(const t of e){const e=s.get(t,Me);if(!e.dirty)continue;s.has(t,H)||s.insert(t,H,{texture:_,size:{x:0,y:0},color:{r:1,g:1,b:1,a:1},anchor:{x:.5,y:.5},flip:{x:!1,y:!1}});const r=s.has(t,Re)?s.get(t,Re):null,i=n.renderForEntity(t,e,r),o=s.get(t,H);o.texture=i.textureHandle,o.size.x=i.width,o.size.y=i.height,o.uvOffset.x=0,o.uvOffset.y=0,o.uvScale.x=1,o.uvScale.y=1,s.insert(t,H,o),e.dirty=!1}}))}}const Ue=new Fe,Be=F("UIMask",{enabled:!0});function ke(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),i=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,i-s)}}function Ie(e,t,n,s,r,i,o){if(!e.has(t,Re)||!e.has(t,$))return null;const a=e.get(t,Re),c=e.get(t,$),l=a.size.x*c.scale.x,u=a.size.y*c.scale.y;return function(e,t,n,s,r,i,o,a,c,l,u){const h=e-n*r,d=e+n*(1-r),f=t-s*i,p=t+s*(1-i);function _(e,t){const n=o[0]*e+o[4]*t+o[12],s=o[1]*e+o[5]*t+o[13],r=o[3]*e+o[7]*t+o[15];return[a+(n/r*.5+.5)*l,c+(s/r*.5+.5)*u]}const[m,g]=_(h,f),[y,w]=_(d,p),x=Math.min(m,y),v=Math.max(m,y),b=Math.min(g,w),P=Math.max(g,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(P-b)}}(c.position.x,c.position.y,l,u,.5,.5,n,s,r,i,o)}function ze(e,t){return(n,s,r,i,o,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([Be]);if(0!==c.length)try{!function(e,t,n,s,r,i,o,a,c){const l=new Set;for(const e of s){t.get(e,Be).enabled&&l.add(e)}const u=[];for(const e of s){if(!l.has(e))continue;let n=!0,s=e;for(;t.has(s,V);){const e=t.get(s,V);if(l.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function h(s,u){const d=e.getChildEntities(n,s);for(const n of d){let s=u;if(l.has(n)){const e=Ie(t,n,r,i,o,a,c);e&&(s=ke(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of u){const n=Ie(t,e,r,i,o,a,c);n&&h(e,n)}}(e,t,n,c,s,r,i,o,a)}catch(t){e.renderer_clearAllClipRects()}}}class Le{build(e){if(!e.wasmModule)return;const t=e.pipeline_;t&&t.setMaskProcessor(ze(e.wasmModule,e.world))}}const De=new Le;var $e;function He(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"}($e||($e={}));let We=null,Oe=null,Ne=1;const Ve=new Map;function je(e){We=e,Oe=e.getResourceManager(),tt()}function Xe(){0!==qe&&We&&(We._free(qe),qe=0),Ve.clear(),Ne=1,Ke=!1,Oe=null,We=null}function Ge(){if(!Oe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Oe}const Ye={createShader:(e,t)=>Ge().createShader(e,t),releaseShader(e){e>0&&Ge().releaseShader(e)},create(e){const t=Ne++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??$e.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return Ve.set(t,n),t},get:e=>Ve.get(e),setUniform(e,t,n){const s=Ve.get(e);s&&s.uniforms.set(t,n)},getUniform(e,t){const n=Ve.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Ve.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Ve.get(e);return t?.blendMode??$e.Normal},setDepthTest(e,t){const n=Ve.get(e);n&&(n.depthTest=t)},getShader(e){const t=Ve.get(e);return t?.shader??0},release(e){Ve.delete(e)},isValid:e=>Ve.has(e),createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??$e.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ve.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Ne++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return Ve.set(n,s),n},toAssetData(e,t){const n=Ve.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=Ve.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ke=!1,qe=0;const Je=4096,Qe=new Map;let Ze=null;function et(e){const t=(0===qe&&We&&(qe=We._malloc(Je)),qe);if(0===t||!We)return{ptr:0,count:0};let n=0,s=0;const r=We.HEAPU8,i=We.HEAPU32,o=We.HEAPF32;for(const[a,c]of e){if(n+128>Je)break;let e=Qe.get(a);e||(Ze||(Ze=new TextEncoder),e=Ze.encode(a),Qe.set(a,e));const l=e.length,u=4*Math.ceil(l/4);i[t+n>>2]=l,n+=4,r.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof c)h=0,d[0]=c;else if(Array.isArray(c)){h=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(h=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(h=2,d=[c.x,c.y,c.z,0]):"y"in c&&(h=1,d=[c.x,c.y,0,0]);i[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function tt(){if(!We||Ke)return;We.materialDataProvider=(e,t,n,s,r)=>{const i=Ve.get(e);if(!i)return We.HEAPU32[t>>2]=0,We.HEAPU32[n>>2]=0,We.HEAPU32[s>>2]=0,void(We.HEAPU32[r>>2]=0);We.HEAPU32[t>>2]=i.shader,We.HEAPU32[n>>2]=i.blendMode;const{ptr:o,count:a}=et(i.uniforms);We.HEAPU32[s>>2]=o,We.HEAPU32[r>>2]=a},Ke=!0}const nt={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class 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 n=this.pending_.get(e);if(n)return n;const s=this.loadInternal(e);this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ye.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ye.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const n=await c(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),i=await this.shaderLoader_.load(r);return{handle:Ye.createFromAsset(s,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function rt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();n.set(s.id,t),e.insert(t,Y,{value:s.name});for(const n of s.components)ot(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function it(e,t,n){const s=new Map,r=n?.assetServer,i=new Map;for(const o of t.entities){const t=e.spawn();s.set(o.id,t),e.insert(t,Y,{value:o.name});for(const s of o.components){if("Sprite"===s.type&&r){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:n?.assetBaseUrl?`${n.assetBaseUrl}/${t}`:`/${t}`;try{const n=await r.loadTexture(s);e.texture=n.handle,i.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("BitmapText"===s.type&&r){const e=s.data;if("string"==typeof e.font&&e.font)try{const t=await r.loadBitmapFont(e.font,n?.assetBaseUrl);e.font=t}catch(t){console.warn(`Failed to load bitmap font: ${e.font}`,t),e.font=0}}if("SpineAnimation"===s.type&&r){const e=s.data,t=e.skeletonPath,i=e.atlasPath;if(t&&i){const e=await r.loadSpine(t,i,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}ot(e,t,s)}}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function ot(e,t,n){const s=n.data;switch(n.type){case"LocalTransform":e.insert(t,D,s);break;case"Sprite":e.insert(t,H,s);break;case"Camera":e.insert(t,W,s);break;case"Canvas":e.insert(t,O,s);break;case"Text":e.insert(t,Me,s);break;case"BitmapText":e.insert(t,X,s);break;case"SpineAnimation":e.insert(t,G,s);break;case"UIRect":e.insert(t,Re,s);break;case"UIMask":e.insert(t,Be,s);break;case"RigidBody":e.insert(t,P,s);break;case"BoxCollider":e.insert(t,S,s);break;case"CircleCollider":e.insert(t,C,s);break;case"CapsuleCollider":e.insert(t,E,s);break;default:{const r=B(n.type);r?e.insert(t,r,s):console.warn(`Unknown component type: ${n.type}`);break}}}function at(e,t){const n=e.getEntitiesWithComponents([W]);for(const s of n){const n=e.get(s,W);n&&(n.aspectRatio=t,e.insert(s,W,n))}}function ct(e,t){const n=e.getEntitiesWithComponents([Y]);for(const s of n){const n=e.get(s,Y);if(n&&n.value===t)return s}return null}class lt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const n=this.cache_.get(e);if(void 0!==n)return n;const s=this.pending_.get(e);if(s)return s;const r=t();this.pending_.set(e,r);try{const t=await r;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class ut{constructor(e){this.textureCache_=new lt,this.shaderCache_=new lt,this.jsonCache_=new lt,this.textCache_=new lt,this.binaryCache_=new lt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new lt,this.embedded_=new Map,this.module_=e,this.canvas_=h(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new st(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n)}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);this.textureCache_.clear(),this.fontCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),i=await this.fetchText(r);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i);for(const e of a){const t=o?`${o}/${e}`:e,s=this.resolveUrl(t,n);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),l=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);return this.writeToVirtualFS(e,l)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>e.endsWith(".bmfont")?this.loadBmfontAsset(n):this.loadFntFile(n))}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),i=r?`${r}/${s}`:s,o=await this.loadTextureRaw(i);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return it(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];if(e.textures)for(const s of e.textures)n.push(this.loadTexture(s).then(e=>{t.textures.set(s,e)}));if(e.materials)for(const s of e.materials)n.push(this.loadMaterial(s).then(e=>{t.materials.set(s,e)}));if(e.spine)for(const s of e.spine){const e=`${s.skeleton}:${s.atlas}`;n.push(this.loadSpine(s.skeleton,s.atlas,s.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const s of e.json)n.push(this.loadJson(s).then(e=>{t.json.set(s,e)}));if(e.text)for(const s of e.text)n.push(this.loadText(s).then(e=>{t.text.set(s,e)}));if(e.binary)for(const s of e.binary)n.push(this.loadBinary(s).then(e=>{t.binary.set(s,e)}));return await Promise.all(n),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n)??n;return new Promise((n,r)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(i)},i.onerror=()=>r(new Error(`Failed to load image: ${e}`)),i.src=s})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),i=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,n,a,i.length,1,s);return this.module_._free(a),{handle:c,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e;if(!await l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:s,fragment:r}=this.parseEsShader(n);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return Ye.createShader(s,r)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const n=await c(t);return JSON.parse(n)}const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):c(t)}const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):a(t)}const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const ht=Q(null,"Assets");class dt{build(e){const t=e.wasmModule;t?e.insertResource(ht,new ut(t)):console.warn("AssetPlugin: No WASM module available")}}const ft=new dt;function pt(e,t){const n=e.getResource(ht);n&&n.registerEmbeddedAssets(t)}let _t=null,mt=0,gt=0,yt=0;const wt=new Float32Array(256);function xt(e){_t=e,mt=_t._malloc(64),gt=_t._malloc(64),yt=_t._malloc(1024)}function vt(){_t&&(mt&&(_t._free(mt),mt=0),gt&&(_t._free(gt),gt=0),yt&&(_t._free(yt),yt=0)),_t=null}function bt(){if(!_t)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return _t}const Pt={r:1,g:1,b:1,a:1},St={begin(e){const t=bt();t.HEAPF32.set(e,mt/4),t.draw_begin(mt)},end(){bt().draw_end()},line(e,t,n,s=1){bt().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rect(e,t,n,s=!0){bt().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rectOutline(e,t,n,s=1){bt().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},circle(e,t,n,s=!0,r=32){bt().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},circleOutline(e,t,n,s=1,r=32){bt().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=Pt){bt().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)},textureRotated(e,t,n,s,r=Pt){bt().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){bt().draw_setLayer(e)},setDepth(e){bt().draw_setDepth(e)},getDrawCallCount:()=>_t?_t.draw_getDrawCallCount():0,getPrimitiveCount:()=>_t?_t.draw_getPrimitiveCount():0,setBlendMode(e){bt().draw_setBlendMode(e)},setDepthTest(e){bt().draw_setDepthTest(e)},drawMesh(e,t,n){const s=bt();s.HEAPF32.set(n,gt/4),s.draw_mesh(e,t,gt)},drawMeshWithMaterial(e,t,n){const s=bt(),r=Ye.get(t);if(!r)return;if(St.setBlendMode(r.blendMode),St.setDepthTest(r.depthTest),0===r.uniforms.size)return void St.drawMesh(e,r.shader,n);s.HEAPF32.set(n,gt/4);let i=0,o=0;for(const[e,t]of r.uniforms){const n=Et(e);if(!(n<0)){if(He(t))wt[i++]=10,wt[i++]=n,wt[i++]=t.slot??o++,wt[i++]=t.textureId;else if("number"==typeof t)wt[i++]=1,wt[i++]=n,wt[i++]=t;else if(Array.isArray(t)){wt[i++]=t.length,wt[i++]=n;for(let e=0;e<t.length;e++)wt[i++]=t[e]}else"w"in t?(wt[i++]=4,wt[i++]=n,wt[i++]=t.x,wt[i++]=t.y,wt[i++]=t.z,wt[i++]=t.w):"z"in t?(wt[i++]=3,wt[i++]=n,wt[i++]=t.x,wt[i++]=t.y,wt[i++]=t.z):(wt[i++]=2,wt[i++]=n,wt[i++]=t.x,wt[i++]=t.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==i?(s.HEAPF32.set(wt.subarray(0,i),yt/4),s.draw_meshWithUniforms(e,r.shader,gt,yt,i)):s.draw_mesh(e,r.shader,gt)}},Ct={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 Et(e){return Ct[e]??-1}var Tt;!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"}(Tt||(Tt={}));let Mt=null,At=0,Rt=0,Ft=0;function Ut(e){Mt=e,At=Mt._malloc(262144),Rt=Mt._malloc(65536),Ft=Mt._malloc(256)}function Bt(){Mt&&(At&&Mt._free(At),Rt&&Mt._free(Rt),Ft&&Mt._free(Ft),At=0,Rt=0,Ft=0),Mt=null}function kt(){if(!Mt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Mt}const It={create(e){const t=kt(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,At/4);const r=e.layout.length,i=new Int32Array(r);for(let t=0;t<r;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Ft,r).set(i),t.geometry_init(n,At,s,Ft,r,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Rt,s).set(e.indices),t.geometry_setIndices16(n,Rt,s)}else{new Uint32Array(t.HEAPU8.buffer,Rt,s).set(e.indices),t.geometry_setIndices32(n,Rt,s)}}return n},updateVertices(e,t,n=0){const s=kt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,At/4),s.geometry_updateVertices(e,At,r,n)},release(e){e>0&&kt().geometry_release(e)},isValid:e=>!(!Mt||e<=0)&&Mt.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return It.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:Tt.Float2},{name:"a_texCoord",type:Tt.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,i=Math.cos(r)*e,o=Math.sin(r)*e,a=(Math.cos(r)+1)/2,c=(Math.sin(r)+1)/2;n.push(i,o,a,c)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return It.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Tt.Float2},{name:"a_texCoord",type:Tt.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const i of e)t=Math.min(t,i.x),n=Math.min(n,i.y),s=Math.max(s,i.x),r=Math.max(r,i.y);const i=[];for(const o of e){const e=(o.x-t)/(s-t),a=(o.y-n)/(r-n);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return It.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:Tt.Float2},{name:"a_texCoord",type:Tt.Float2}],indices:new Uint16Array(o)})}};let zt=null;function Lt(e){zt=e}function Dt(){zt&&Ht.isInitialized()&&Ht.shutdown(),zt=null}function $t(){if(!zt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return zt}const Ht={init:(e,t)=>$t().postprocess_init(e,t),shutdown(){$t().postprocess_shutdown()},resize(e,t){$t().postprocess_resize(e,t)},addPass:(e,t)=>$t().postprocess_addPass(e,t),removePass(e){$t().postprocess_removePass(e)},setEnabled(e,t){$t().postprocess_setPassEnabled(e,t)},isEnabled:e=>$t().postprocess_isPassEnabled(e),setUniform(e,t,n){$t().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){$t().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){$t().postprocess_begin()},end(){$t().postprocess_end()},getPassCount:()=>$t().postprocess_getPassCount(),isInitialized:()=>!!zt&&zt.postprocess_isInitialized(),setBypass(e){$t().postprocess_setBypass(e)},isBypassed:()=>!zt||zt.postprocess_isBypassed(),createBlur:()=>Ye.createShader(Wt,"#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:()=>Ye.createShader(Wt,"#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:()=>Ye.createShader(Wt,"#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:()=>Ye.createShader(Wt,"#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")},Wt="#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 Ot;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Ot||(Ot={}));let Nt=null,Vt=0;function jt(e){Nt=e,Vt=Nt._malloc(64)}function Xt(){Nt&&Vt&&(Nt._free(Vt),Vt=0),Nt=null}const Gt={init(e,t){Nt?.renderer_init(e,t)},resize(e,t){Nt?.renderer_resize(e,t)},begin(e,t){Nt&&Vt&&(Nt.HEAPF32.set(e,Vt/4),Nt.renderer_begin(Vt,t??0))},flush(){Nt?.renderer_flush()},end(){Nt?.renderer_end()},submitSprites(e){Nt&&Nt.renderer_submitSprites(e._cpp)},submitBitmapText(e){Nt&&Nt.renderer_submitBitmapText(e._cpp)},submitSpine(e){Nt&&Nt.renderer_submitSpine?.(e._cpp)},setStage(e){Nt?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Nt?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Nt?.renderer_releaseTarget(e)},getTargetTexture:e=>Nt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Nt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Nt?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Nt?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){Nt?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){Nt?.renderer_clearBuffers(e)},getStats:()=>Nt?{drawCalls:Nt.renderer_getDrawCalls(),triangles:Nt.renderer_getTriangles(),sprites:Nt.renderer_getSprites(),text:Nt.renderer_getText(),spine:Nt.renderer_getSpine?.()??0,meshes:Nt.renderer_getMeshes(),culled:Nt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Yt=null;function Kt(e){Yt=e}function qt(){Yt=null}const Jt={enable(){Yt?.gl_enableErrorCheck(!0)},disable(){Yt?.gl_enableErrorCheck(!1)},check:e=>Yt?.gl_checkErrors(e)??0,diagnose(){Yt?.renderer_diagnose()}},Qt=new Map;function Zt(e,t){Qt.set(e,t)}function en(e){Qt.delete(e)}function tn(){Qt.clear()}class nn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}setSpineRenderer(e){this.spineRenderer_=e}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:i}=e;s===this.lastWidth_&&r===this.lastHeight_||(Gt.resize(s,r),Ht.isInitialized()&&Ht.getPassCount()>0&&Ht.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),Gt.setViewport(0,0,s,r),Gt.clearBuffers(3),Gt.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),Gt.submitSprites(t),Gt.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Gt.submitSpine(t),Gt.flush(),this.executeDrawCallbacks(n,i),Gt.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:i}=e;Gt.setViewport(s.x,s.y,s.w,s.h),Gt.setScissor(s.x,s.y,s.w,s.h,!0),Gt.clearBuffers(r),Gt.setScissor(0,0,0,0,!1),Gt.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Gt.submitSprites(t),Gt.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Gt.submitSpine(t),Gt.flush(),this.executeDrawCallbacks(n,i),Gt.end()}executeDrawCallbacks(e,t){const n=Qt;if(n.size>0){St.begin(e);const s=[];for(const[e,r]of n.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}St.end();for(const e of s)en(e)}}}class sn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.runSchedule(he.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(he.FixedPreUpdate),this.runSchedule(he.FixedUpdate),this.runSchedule(he.FixedPostUpdate);this.runSchedule(he.PreUpdate),this.runSchedule(he.Update),this.runSchedule(he.PostUpdate),this.runSchedule(he.Last),requestAnimationFrame(this.mainLoop)},this.world_=new Se,this.resources_=new ne;for(const e of Object.values(he))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new sn}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(he.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(he.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new ye(this.world_,this.resources_),this.resources_.insert(se,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(he.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,qt(),Xt(),Dt(),Bt(),Xe(),vt()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(se);t.delta=e,t.elapsed+=e,t.frameCount++}}function rn(e,t){const n=sn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),xt(e),je(e),Ut(e),Lt(e),jt(e),Kt(e);const r=new nn;n.pipeline_=r;let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)})),a={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=o(),a=e.registry_getCanvasEntity(s);if(a>=0){const e=s.getCanvas(a).backgroundColor;Gt.setClearColor(e.r,e.g,e.b,e.a)}const c=(d()-i)/1e3;Gt.resize(t,n),Ht.isInitialized()&&Ht.getPassCount()>0&&!Ht.isBypassed()&&Ht.resize(t,n);const l=function(e,t,n,s){const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const i=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),o=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),c={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},l=c.w*n/(c.h*s);let u;if(1===r.projectionType){let e=r.orthoSize;if(i){e=cn(i.designResolution.y/2,i.designResolution.x/i.designResolution.y,l,i.scaleMode,i.matchWidthOrHeight)}const t=e*l;u=un(-t,t,-e,e,-r.farPlane,r.farPlane)}else u=dn(r.fov*Math.PI/180,l,r.nearPlane,r.farPlane);const h=pn(a.position.x,a.position.y,a.position.z);o.push({entity:e,viewProjection:_n(u,h),viewportRect:c,clearFlags:r.clearFlags,priority:r.priority})}return o.sort((e,t)=>e.priority-t.priority),o}(e,s,t,n);if(0===l.length)r.render({registry:{_cpp:s},viewProjection:an,width:t,height:n,elapsed:c});else{for(const e of l){const i=e.viewportRect,o=Math.round(i.x*t),a=Math.round((1-i.y-i.h)*n),l=Math.round(i.w*t),u=Math.round(i.h*n);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:o,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}Gt.setViewport(0,0,t,n)}}};return n.addSystemToSchedule(he.Last,a),n.addPlugin(ft),n.addPlugin(be),n.addPlugin(Ue),n.addPlugin(De),n}function on(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 an=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function cn(e,t,n,s,r){const i=e*t/n,o=e;switch(s){case 0:return i;case 1:default:return o;case 2:return Math.max(i,o);case 3:return Math.min(i,o);case 4:{const e=r;return Math.pow(i,1-e)*Math.pow(o,e)}}}const ln=new Float32Array(16);function un(e,t,n,s,r,i){const o=ln;o.fill(0);const a=t-e,c=s-n,l=i-r;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(s+n)/c,o[14]=-(i+r)/l,o[15]=1,o}const hn=new Float32Array(16);function dn(e,t,n,s){const r=hn;r.fill(0);const i=1/Math.tan(e/2),o=n-s;return r[0]=i/t,r[5]=i,r[10]=(s+n)/o,r[11]=-1,r[14]=2*s*n/o,r}const fn=new Float32Array(16);function pn(e,t,n){const s=fn;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}function _n(e,t){const n=new Float32Array(16);for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}async function mn(e,t){if(t)return t();return(0,(await import(e)).default)()}const gn=Q({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),yn=Q(null,"PhysicsAPI");function wn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function xn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class vn{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(gn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=mn(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([O]);for(const n of t){const t=e.world.get(n,O);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/r,o=e.world;e.addSystemToSchedule(he.PostUpdate,fe([Z(se)],a=>{const c=o.getEntitiesWithComponents([P,D,$]),l=new Set;for(const r of c){l.add(r);const a=o.get(r,P),c=o.get(r,$);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const o=wn(c.rotation);s._physics_createBody(r,a.bodyType,c.position.x*i,c.position.y*i,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),bn(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===T.Kinematic){const e=wn(c.rotation);s._physics_setBodyTransform(r,c.position.x*i,c.position.y*i,e)}}for(const e of t)l.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),i=r>>2;for(let r=0;r<s;r++){const s=i+4*r,o=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,c=t.HEAPF32[s+2]*n,l=t.HEAPF32[s+3];if(!e.world.valid(o))continue;const u=e.world.get(o,D);if(!u)continue;let h=a,d=c,f=l;if(e.world.has(o,V)){const t=e.world.get(o,V);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,$)){const n=e.world.get(t.entity,$),s=wn(n.rotation),r=a-n.position.x,i=c-n.position.y,o=Math.cos(-s),u=Math.sin(-s);h=(r*o-i*u)/(0!==n.scale.x?n.scale.x:1),d=(r*u+i*o)/(0!==n.scale.y?n.scale.y:1),f=l-s}}u.position.x=h,u.position.y=d;const p=xn(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(o,D,u)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<r;i++){const r=e+6*i;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const i=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<o;n++){const s=e+2*n;i.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],c=t._physics_getSensorEnterCount();if(c>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<c;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const l=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;l.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(gn,{collisionEnters:s,collisionExits:i,sensorEnters:a,sensorExits:l})}(e,s,r)},{name:"PhysicsSystem"})),e.__physicsModule=s,e.insertResource(yn,Pn._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=s}}function bn(e,t,n){const s=e.world;if(s.has(n,S)){const e=s.get(n,S);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,C)){const e=s.get(n,C);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,E)){const e=s.get(n,E);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Pn{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(Pn.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function Sn(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const i=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),i}function Cn(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function En(e,t,n,s){const r=e.scale.x*t*(n?-1:1),i=e.scale.y*t*(s?-1:1),o=e.scale.z,a=e.rotation.x,c=e.rotation.y,l=e.rotation.z,u=e.rotation.w,h=a+a,d=c+c,f=l+l,p=a*h,_=a*d,m=a*f,g=c*d,y=c*f,w=l*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(g+w))*r,(_+b)*r,(m-v)*r,0,(_-b)*i,(1-(p+w))*i,(y+x)*i,0,(m+v)*o,(y-x)*o,(1-(p+g))*o,0,e.position.x,e.position.y,e.position.z,1])}async function Tn(e,t,n,s,r,i,o){const a=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=Sn(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,a);let c={},l=null;if(r&&(l=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),c=await async function(e,t,n,s,r){const i={};for(const o of s.entities)for(const s of o.components){if("SpineAnimation"!==s.type||!s.data)continue;const o=s.data.skeletonPath,a=s.data.atlasPath;if(!o||!a)continue;const c=r.resolvePath(o),l=r.resolvePath(a);try{const s=r.readText(a),u=c.endsWith(".skel");let h,d;if(u){const e=r.readBinary(o);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=r.readText(o),n=(new TextEncoder).encode(e);d=n.length,h=t._malloc(d+1),t.HEAPU8.set(n,h),t.HEAPU8[h+d]=0}const f=n.loadSkeleton(h,d,s,s.length,u);if(t._free(h),f<0)continue;i[o]=f;const p=Cn(s),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=_+"/"+p[t];try{const i=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),o=Sn(e,i,!1),a=e.getResourceManager().getTextureGLId(o);n.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,l,n,s)),i){new vn("",{gravity:o?.gravity??{x:0,y:-9.81},fixedTimestep:o?.fixedTimestep??1/60,subStepCount:o?.subStepCount??4},()=>Promise.resolve(i)).build(e)}const u=function(e,t){const n={},s={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===n[r])try{const e=JSON.parse(t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=s[i];o||(o=Ye.createShader(e.vertexSource,e.fragmentSource),s[i]=o),n[r]=Ye.createFromAsset(e,o)}catch{n[r]=0}}return n}(n,s),h=rt(e.world,n);if(function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const r=e.get(t,H);r&&(r.texture=n[s.data.texture]||0,e.insert(t,H,r))}}}(e.world,n,a,h),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const r=n[s.data.material]||0;if(r)if("Sprite"===s.type){const n=e.get(t,H);n&&(n.material=r,e.insert(t,H,n))}else if("SpineAnimation"===s.type){const n=e.get(t,G);n&&(n.material=r,e.insert(t,G,n))}}}}(e.world,n,u,h),r&&l){const s=function(e,t,n,s){const r={};for(const i of t.entities)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=n[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const c=s.get(i.id);void 0!==c&&(r[c]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(l,n,c,h);!function(e,t,n,s,r){let i=0;e.setSpineRenderer((o,a)=>{let c=a-i;i=a,(c<=0||c>.5)&&(c=1/60);const l=e.world;for(const e in r){const i=Number(e),o=r[e],a=l.has(i,G)?l.get(i,G):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&s.update(o,c*h);let d=0;if(l.has(i,$)){const e=En(l.get(i,$),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=s.getMeshBatchCount(o);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(o,e),i=s.getMeshBatchIndexCount(o,e);if(!r||!i)continue;const a=8*r*4,c=2*i,l=n._malloc(a),u=n._malloc(c),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(o,e,l,u,h,f);const p=n.HEAPU32[h>>2],_=n.HEAPU32[f>>2],m=new Float32Array(n.HEAPF32.buffer,l,8*r),g=new Uint16Array(n.HEAPU8.buffer,u,i),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(m,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(g),t.renderer_submitTriangles(y,r,w,i,p,_,d),t._free(y),t._free(w),n._free(l),n._free(u),n._free(h),n._free(f)}d&&t._free(d)}})}(e,t,r,l,s)}}class Mn{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set;for(const s of e.entities)for(const e of s.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&(s.endsWith(".skel")?n.add(s):t.add(s)),r&&t.add(r)}"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const s=[];for(const e of t)s.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of n)s.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(s)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),i=new OffscreenCanvas(r.width,r.height).getContext("2d");i.drawImage(r,0,0);const o=i.getImageData(0,0,r.width,r.height);return r.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class An{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new Mn(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.__spineInitPromise;if(r){s=(await r).controller.raw}await Tn(this.app_,this.app_.wasmModule,t,n,s),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([W]);for(const s of n){if(e.get(s,W).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const s=e.getEntitiesWithComponents([O]);for(const r of s){const s=e.get(r,O);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,D,i);const o={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3};e.insert(r,W,o)}}}const Rn={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),Rn.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 Fn=!1;function Un(e){Fn=e}function Bn(){return Fn}function kn(){return!Fn}e=f;export{sn as App,dt as AssetPlugin,ut as AssetServer,ht as Assets,lt as AsyncCache,X as BitmapText,$e as BlendMode,T as BodyType,S as BoxCollider,W as Camera,O as Canvas,E as CapsuleCollider,j as Children,C as CircleCollider,ce as Commands,ue as CommandsInstance,Tt as DataType,St as Draw,le as EntityCommands,Jt as GLDebug,It as Geometry,p as INVALID_ENTITY,m as INVALID_FONT,_ as INVALID_TEXTURE,xe as Input,ve as InputPlugin,we as InputState,D as LocalTransform,Ye as Material,st as MaterialLoader,re as Mut,Y as Name,V as Parent,Pn as Physics,gn as PhysicsEvents,vn as PhysicsPlugin,Ht as PostProcess,An as PreviewPlugin,oe as Query,ae as QueryInstance,nn as RenderPipeline,Ot as RenderStage,Rn as RenderTexture,Gt as Renderer,Z as Res,ee as ResMut,P as RigidBody,he as Schedule,nt as ShaderSources,G as SpineAnimation,H as Sprite,ye as SystemRunner,Me as Text,Ce as TextAlign,Te as TextOverflow,Fe as TextPlugin,Ae as TextRenderer,Ee as TextVerticalAlign,se as Time,Be as UIMask,Le as UIMaskPlugin,Re as UIRect,N as Velocity,Mn as WebAssetProvider,Se as World,$ as WorldTransform,me as addStartupSystem,_e as addSystem,ge as addSystemToSchedule,ft as assetPlugin,tn as clearDrawCallbacks,k as clearUserComponents,x as color,ze as createMaskProcessor,rn as createWebApp,F as defineComponent,Q as defineResource,fe as defineSystem,U as defineTag,ct as findEntityByName,on as flushPendingSystems,q as getComponentDefaults,t as getPlatform,s as getPlatformType,B as getUserComponent,xt as initDrawAPI,Kt as initGLDebugAPI,Ut as initGeometryAPI,je as initMaterialAPI,Lt as initPostProcessAPI,jt as initRendererAPI,be as inputPlugin,L as isBuiltinComponent,Bn as isEditor,n as isPlatformInitialized,kn as isRuntime,He as isTextureRef,r as isWeChat,i as isWeb,ot as loadComponent,mn as loadPhysicsModule,Tn as loadRuntimeScene,rt as loadSceneData,it as loadSceneWithAssets,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,v as quat,Zt as registerDrawCallback,pt as registerEmbeddedAssets,tt as registerMaterialCallback,Un as setEditorMode,vt as shutdownDrawAPI,qt as shutdownGLDebugAPI,Bt as shutdownGeometryAPI,Xe as shutdownMaterialAPI,Dt as shutdownPostProcessAPI,Xt as shutdownRendererAPI,Ue as textPlugin,De as uiMaskPlugin,en as unregisterDrawCallback,at as updateCameraAspectRatio,g as vec2,y as vec3,w as vec4};+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function 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",this.inputCleanup_=null}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.module}}createImage(){return new Image}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),r=t=>e.onKeyUp(t.code),o=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},i=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},u=()=>{e.onPointerUp(0)},h=t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)};document.addEventListener("keydown",s),document.addEventListener("keyup",r),n.addEventListener("mousemove",o),n.addEventListener("mousedown",i),n.addEventListener("mouseup",a),n.addEventListener("touchstart",c),n.addEventListener("touchmove",l),n.addEventListener("touchend",u),n.addEventListener("wheel",h),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",r),n.removeEventListener("mousemove",o),n.removeEventListener("mousedown",i),n.removeEventListener("mouseup",a),n.removeEventListener("touchstart",c),n.removeEventListener("touchmove",l),n.removeEventListener("touchend",u),n.removeEventListener("wheel",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=0,_=4294967295,m=0,g=(e=0,t=0)=>({x:e,y:t}),y=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),w=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),x=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),v=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function b(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const P=b("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),S=b("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),C=b("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),E=b("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),M={Static:0,Kinematic:1,Dynamic:2};let T=0;function A(e,t){const n=++T;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function R(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function F(e,t){const n=R(),s=n.get(e);if(s)return s;const r=A(e,t);return n.set(e,r),k(e,t,!1),r}function U(e){const t=R(),n=t.get(e);if(n)return n;const s=A(e,{});return t.set(e,s),k(e,{},!0),s}function B(e){return R().get(e)}function I(){R().clear()}function k(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function z(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function L(e){return!0===e._builtin}const D=z("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),H=z("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),W=z("Sprite",{texture:_,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),$=z("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),O=z("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),j=z("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),N=z("Parent",{entity:0}),X=z("Children",{entities:[]}),V=z("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:0}),Y=z("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),G={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},q={LocalTransform:D,WorldTransform:H,Sprite:W,Camera:$,Canvas:O,Velocity:j,Parent:N,Children:X,BitmapText:V,SpineAnimation:Y,RigidBody:P,BoxCollider:S,CircleCollider:C,CapsuleCollider:E};function K(e){const t=q[e];if(t)return{...t._default};const n=B(e);return n?{...n._default}:null}let J=0;function Q(e,t){const n=++J;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function Z(e){return{_type:"res",_resource:e}}function ee(e){return{_type:"res_mut",_resource:e}}class te{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}}class ne{constructor(){this.resources_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id)}getResMut(e){return new te(this.get(e),t=>this.set(e,t))}}const se=Q({delta:0,elapsed:0,frameCount:0},"Time");function re(e){return{_type:"mut",_component:e}}function oe(e){return"object"==typeof e&&null!==e&&"mut"===e._type}function ie(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{oe(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class ae{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>oe(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with)}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),r=n.length,o=e.length>0,i=t.length>0,a=new Array(r+1);let c=null,l=[];try{for(const u of s){if(null!==c&&o){for(let e=0;e<l.length;e++){const t=l[e];this.world_.insert(c,t.component,t.data)}l.length=0}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(u,t[n])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,n[e]);if(o){for(let t=0;t<e.length;t++){const s=e[t];l.push({component:n[s],data:a[s+1]})}c=u}yield a}}finally{if(null!==c&&o)for(let e=0;e<l.length;e++){const t=l[e];this.world_.insert(c,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function ce(){return{_type:"commands"}}class le{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=L(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class ue{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new le(this,null);return this.spawned_.push(e),e}entity(e){return new le(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var he;!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(he||(he={}));let de=0;function fe(e,t,n){const s=++de;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function pe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function _e(e){pe().push({schedule:he.Update,system:e})}function me(e){pe().push({schedule:he.Startup,system:e})}function ge(e,t){pe().push({schedule:e,system:t})}class ye{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof ue&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new ae(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new ue(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class we{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const xe=Q(new we,"Input");class ve{constructor(e){this.target_=e??null}build(e){const n=new we;e.insertResource(xe,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(he.First,fe([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const be=new ve;function Pe(e){if(null==e||"object"!=typeof e||Array.isArray(e))return e;const t=e;if("r"in t&&"g"in t&&"b"in t&&"a"in t&&!("x"in t))return{x:t.r,y:t.g,z:t.b,w:t.a};const n={};for(const e of Object.keys(t)){const s=t[e];n[e]=null==s||"object"!=typeof s||Array.isArray(s)?s:Pe(s)}return n}class Se{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return L(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return L(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return L(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){L(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const s={...t._default,...n};if(this.cppRegistry_){const n=`add${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e,Pe(s))}return s}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const n=`get${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const n=`has${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const n=`remove${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e)}insertScript(e,t,n){const s=t.create(n);return this.getStorage(t).set(e,s),s}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();let t=null,n=1/0;for(const s of e)if(!L(s)){const e=this.tsStorage_.get(s._id),r=e?e.size:0;r<n&&(n=r,t=e??null)}const s=[],r=t?t.keys():this.entities_;for(const t of r){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&s.push(t)}return s}}var Ce,Ee,Me;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Ce||(Ce={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Ee||(Ee={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Me||(Me={}));const Te=F("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Ce.Left,verticalAlign:Ee.Top,wordWrap:!0,overflow:Me.Visible,lineHeight:1.2,dirty:!0});class Ae{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let 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=r?Math.ceil(o):h+2*u,p=r?Math.ceil(i):d+2*u;if(r&&e.overflow===Me.Ellipsis&&d>i){const e=Math.floor(i/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<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const _=Math.round(255*e.color.r),m=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${_}, ${m}, ${g}, ${y})`,r&&e.overflow===Me.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=c.length*l;let x;if(r)switch(e.verticalAlign){case Ee.Top:x=u;break;case Ee.Middle:x=(p-w)/2;break;case Ee.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let s;switch(e.align){case Ce.Left:s=u;break;case Ce.Center:s=f/2;break;case Ce.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=l}r&&e.overflow===Me.Clip&&n.restore();const b=n.getImageData(0,0,f,p),P=new Uint8Array(b.data.buffer),S=this.module.getResourceManager(),C=this.module._malloc(P.length);this.module.HEAPU8.set(P,C);const E=S.createTexture(f,p,C,P.length,1,!0);return this.module._free(C),{textureHandle:E,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const r=this.renderText(t,n);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case Ce.Left:return"left";case Ce.Center:return"center";case Ce.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const Re=F("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class Fe{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Ae(t),s=e.world;e.addSystemToSchedule(he.PreUpdate,fe([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Te));const e=s.getEntitiesWithComponents([Te]);for(const t of e){const e=s.get(t,Te);if(!e.dirty)continue;s.has(t,W)||s.insert(t,W,{texture:_,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const r=s.has(t,Re)?s.get(t,Re):null,o=n.renderForEntity(t,e,r),i=s.get(t,W);i.texture=o.textureHandle,i.size.x=o.width,i.size.y=o.height,i.uvOffset.x=0,i.uvOffset.y=0,i.uvScale.x=1,i.uvScale.y=1,s.insert(t,W,i),e.dirty=!1}}))}}const Ue=new Fe,Be=F("UIMask",{enabled:!0});function Ie(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,o-s)}}function ke(e,t,n,s,r,o,i,a,c,l,u){const h=e-n*r,d=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function _(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*l,c+(.5*(s/r)+.5)*u]}const[m,g]=_(h,f),[y,w]=_(d,p),x=Math.min(m,y),v=Math.max(m,y),b=Math.min(g,w),P=Math.max(g,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(P-b)}}function ze(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],c=e[5],l=e[6],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],_=e[12],m=e[13],g=e[14],y=e[15],w=s*c-r*a,x=s*l-o*a,v=s*u-i*a,b=r*l-o*c,P=r*u-i*c,S=o*u-i*l,C=h*m-d*_,E=h*g-f*_,M=h*y-p*_,T=d*g-f*m,A=d*y-p*m,R=f*y-p*g;let F=w*R-x*A+v*T+b*M-P*E+S*C;return Math.abs(F)<1e-8||(F=1/F,n[0]=(c*R-l*A+u*T)*F,n[1]=(o*A-r*R-i*T)*F,n[2]=(m*S-g*P+y*b)*F,n[3]=(f*P-d*S-p*b)*F,n[4]=(l*M-a*R-u*E)*F,n[5]=(s*R-o*M+i*E)*F,n[6]=(g*v-_*S-y*x)*F,n[7]=(h*S-f*v+p*x)*F,n[8]=(a*A-c*M+u*C)*F,n[9]=(r*M-s*A-i*C)*F,n[10]=(_*P-m*v+y*w)*F,n[11]=(d*v-h*P-p*w)*F,n[12]=(c*E-a*T-l*C)*F,n[13]=(s*T-r*E+o*C)*F,n[14]=(m*x-_*b-g*w)*F,n[15]=(h*b-d*x+f*w)*F),n}function Le(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,c=(t-r)/i*2-1,l=n[0]*a+n[4]*c+n[12],u=n[1]*a+n[5]*c+n[13],h=n[3]*a+n[7]*c+n[15];return{x:l/h,y:u/h}}function De(e,t,n,s,r,o,i,a){return e>=n-r*i&&e<=n+r*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function He(e,t,n,s,r,o,i){if(!e.has(t,Re)||!e.has(t,H))return null;const a=e.get(t,Re),c=e.get(t,H),l=a.size.x*c.scale.x,u=a.size.y*c.scale.y;return ke(c.position.x,c.position.y,l,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function We(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([Be]);if(0!==c.length)try{!function(e,t,n,s,r,o,i,a,c){const l=new Set;for(const e of s){t.get(e,Be).enabled&&l.add(e)}const u=[];for(const e of s){if(!l.has(e))continue;let n=!0,s=e;for(;t.has(s,N);){const e=t.get(s,N);if(l.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function h(s,u){const d=e.getChildEntities(n,s);for(const n of d){let s=u;if(l.has(n)){const e=He(t,n,r,o,i,a,c);e&&(s=Ie(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of u){const n=He(t,e,r,o,i,a,c);n&&h(e,n)}}(e,t,n,c,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class $e{build(e){if(!e.wasmModule)return;const t=e.pipeline_;t&&t.setMaskProcessor(We(e.wasmModule,e.world))}}const Oe=new $e,je=F("Interactable",{enabled:!0}),Ne=F("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Xe;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Xe||(Xe={}));const Ve=F("Button",{state:Xe.Normal,transition:null});class Ye{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const Ge=Q(new Ye,"UIEvents"),qe=Q({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo"),Ke=new Float32Array(16);class Je{build(e){const t=e.world,n=new Ye;e.insertResource(Ge,n);let s=null,r=null;e.addSystemToSchedule(he.PreUpdate,fe([Z(xe),Z(qe)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([Ne]);for(const e of i){const n=t.get(e,Ne);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a="undefined"!=typeof window&&window.devicePixelRatio||1,c=e.mouseX*a,l=o.screenH-e.mouseY*a;ze(o.viewProjection,Ke);const u=Le(c,l,Ke,o.vpX,o.vpY,o.vpW,o.vpH),h=t.getEntitiesWithComponents([je,Re,H]);let d=null,f=-1/0;for(const e of h){t.has(e,Ne)||t.insert(e,Ne);if(!t.get(e,je).enabled)continue;const n=t.get(e,H),s=t.get(e,Re),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(De(u.x,u.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y)){let n=0;t.has(e,W)&&(n=t.get(e,W).layer),n>=f&&(f=n,d=e)}}if(s!==d){if(null!==s&&t.valid(s)&&t.has(s,Ne)){t.get(s,Ne).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,Ne).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,Ne);e.pressed=!0,e.justPressed=!0,r=d,n.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Ne)){const e=t.get(r,Ne);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(he.Update,fe([],()=>{const e=t.getEntitiesWithComponents([Ve]);for(const n of e){if(t.has(n,je)||t.insert(n,je,{enabled:!0}),!t.has(n,Ne))continue;const e=t.get(n,Ne),s=t.get(n,Ve),r=t.get(n,je),o=s.state;if(r.enabled?e.pressed?s.state=Xe.Pressed:e.hovered?s.state=Xe.Hovered:s.state=Xe.Normal:s.state=Xe.Disabled,o!==s.state&&s.transition&&t.has(n,W)){const e=t.get(n,W),r=s.transition;switch(s.state){case Xe.Normal:e.color={...r.normalColor};break;case Xe.Hovered:e.color={...r.hoveredColor};break;case Xe.Pressed:e.color={...r.pressedColor};break;case Xe.Disabled:e.color={...r.disabledColor}}t.insert(n,W,e)}}},{name:"ButtonSystem"}))}}const Qe=new Je,Ze=U("ScreenSpace");function et(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,c=o.left+e.x*i,l=o.left+t.x*i,u=o.bottom+e.y*a,h=o.bottom+t.y*a;let d,f,p,_;if(c===l&&u===h){const e=c+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;d=e-s,f=t-o,p=e+s,_=t+o}else d=c+n.x,f=u+n.y,p=l+s.x,_=h+s.y;return{centerX:.5*(d+p),centerY:.5*(f+_),width:p-d,height:_-f,rect:{left:d,bottom:f,right:p,top:_}}}function tt(e,t,n,s,r,o){if(!e.has(t,Re))return;const i=e.get(t,Re),a=et(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const c=e.get(t,D);if(o?(c.position.x=a.centerX,c.position.y=a.centerY):(c.position.x=a.centerX-s,c.position.y=a.centerY-r),e.insert(t,D,c),!e.has(t,X))return;const l=e.get(t,X);if(l&&l.entities)for(const t of l.entities)e.valid(t)&&tt(e,t,a.rect,a.centerX,a.centerY,!1)}class nt{build(e){const t=e.world;e.addSystemToSchedule(he.PreUpdate,fe([Z(qe)],e=>{if(!e.valid)return;const n={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(n.left+n.right),r=.5*(n.bottom+n.top),o=t.getEntitiesWithComponents([Ze,Re,D]);for(const e of o)tt(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const st=new nt;var rt;function ot(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"}(rt||(rt={}));let it=null,at=null,ct=1;const lt=new Map;function ut(e){it=e,at=e.getResourceManager(),xt()}function ht(){0!==_t&&it&&(it._free(_t),_t=0),lt.clear(),ct=1,pt=!1,at=null,it=null}function dt(){if(!at)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return at}const ft={createShader:(e,t)=>dt().createShader(e,t),releaseShader(e){e>0&&dt().releaseShader(e)},create(e){const t=ct++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??rt.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return lt.set(t,n),t},get:e=>lt.get(e),setUniform(e,t,n){const s=lt.get(e);s&&s.uniforms.set(t,n)},getUniform(e,t){const n=lt.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=lt.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=lt.get(e);return t?.blendMode??rt.Normal},setDepthTest(e,t){const n=lt.get(e);n&&(n.depthTest=t)},getShader(e){const t=lt.get(e);return t?.shader??0},release(e){lt.delete(e)},isValid:e=>lt.has(e),createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??rt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=lt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=ct++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return lt.set(n,s),n},toAssetData(e,t){const n=lt.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=lt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let pt=!1,_t=0;const mt=4096,gt=new Map;let yt=null;function wt(e){const t=(0===_t&&it&&(_t=it._malloc(mt)),_t);if(0===t||!it)return{ptr:0,count:0};let n=0,s=0;const r=it.HEAPU8,o=it.HEAPU32,i=it.HEAPF32;for(const[a,c]of e){if(n+128>mt)break;let e=gt.get(a);e||(yt||(yt=new TextEncoder),e=yt.encode(a),gt.set(a,e));const l=e.length,u=4*Math.ceil(l/4);o[t+n>>2]=l,n+=4,r.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof c)h=0,d[0]=c;else if(Array.isArray(c)){h=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(h=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(h=2,d=[c.x,c.y,c.z,0]):"y"in c&&(h=1,d=[c.x,c.y,0,0]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function xt(){if(!it||pt)return;it.materialDataProvider=(e,t,n,s,r)=>{const o=lt.get(e);if(!o)return it.HEAPU32[t>>2]=0,it.HEAPU32[n>>2]=0,it.HEAPU32[s>>2]=0,void(it.HEAPU32[r>>2]=0);it.HEAPU32[t>>2]=o.shader,it.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=wt(o.uniforms);it.HEAPU32[s>>2]=i,it.HEAPU32[r>>2]=a},pt=!0}const vt={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class bt{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const n=this.pending_.get(e);if(n)return n;const s=this.loadInternal(e);this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(ft.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())ft.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const n=await c(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(r);return{handle:ft.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function Pt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();n.set(s.id,t),e.insert(t,G,{value:s.name});for(const n of s.components)Ct(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function St(e,t,n){const s=new Map,r=n?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();s.set(i.id,t),e.insert(t,G,{value:i.name});for(const s of i.components){if("Sprite"===s.type&&r){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:n?.assetBaseUrl?`${n.assetBaseUrl}/${t}`:`/${t}`;try{const n=await r.loadTexture(s);e.texture=n.handle,o.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("BitmapText"===s.type&&r){const e=s.data;if("string"==typeof e.font&&e.font)try{const t=await r.loadBitmapFont(e.font,n?.assetBaseUrl);e.font=t}catch(t){console.warn(`Failed to load bitmap font: ${e.font}`,t),e.font=0}}if("SpineAnimation"===s.type&&r){const e=s.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await r.loadSpine(t,o,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Ct(e,t,s)}}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function Ct(e,t,n){const s=n.data;switch(n.type){case"LocalTransform":e.insert(t,D,s);break;case"Sprite":e.insert(t,W,s);break;case"Camera":e.insert(t,$,s);break;case"Canvas":e.insert(t,O,s);break;case"Text":e.insert(t,Te,s);break;case"BitmapText":e.insert(t,V,s);break;case"SpineAnimation":e.insert(t,Y,s);break;case"UIRect":{const n=s;n.anchor&&!n.anchorMin&&(n.anchorMin={...n.anchor},n.anchorMax={...n.anchor},delete n.anchor),e.insert(t,Re,n);break}case"UIMask":e.insert(t,Be,s);break;case"RigidBody":e.insert(t,P,s);break;case"BoxCollider":e.insert(t,S,s);break;case"CircleCollider":e.insert(t,C,s);break;case"CapsuleCollider":e.insert(t,E,s);break;default:{const r=B(n.type);r?e.insert(t,r,s):console.warn(`Unknown component type: ${n.type}`);break}}}function Et(e,t){const n=e.getEntitiesWithComponents([$]);for(const s of n){const n=e.get(s,$);n&&(n.aspectRatio=t,e.insert(s,$,n))}}function Mt(e,t){const n=e.getEntitiesWithComponents([G]);for(const s of n){const n=e.get(s,G);if(n&&n.value===t)return s}return null}class Tt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const n=this.cache_.get(e);if(void 0!==n)return n;const s=this.pending_.get(e);if(s)return s;const r=t();this.pending_.set(e,r);try{const t=await r;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class At{constructor(e){this.textureCache_=new Tt,this.shaderCache_=new Tt,this.jsonCache_=new Tt,this.textCache_=new Tt,this.binaryCache_=new Tt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Tt,this.embedded_=new Map,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.module_=e,this.canvas_=h(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new bt(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n)}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);this.textureCache_.clear(),this.fontCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o);for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),l=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);return this.writeToVirtualFS(e,l)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>e.endsWith(".bmfont")?this.loadBmfontAsset(n):this.loadFntFile(n))}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return St(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];if(e.textures)for(const s of e.textures)n.push(this.loadTexture(s).then(e=>{t.textures.set(s,e)}));if(e.materials)for(const s of e.materials)n.push(this.loadMaterial(s).then(e=>{t.materials.set(s,e)}));if(e.spine)for(const s of e.spine){const e=`${s.skeleton}:${s.atlas}`;n.push(this.loadSpine(s.skeleton,s.atlas,s.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const s of e.json)n.push(this.loadJson(s).then(e=>{t.json.set(s,e)}));if(e.text)for(const s of e.text)n.push(this.loadText(s).then(e=>{t.text.set(s,e)}));if(e.binary)for(const s of e.binary)n.push(this.loadBinary(s).then(e=>{t.binary.set(s,e)}));return await Promise.all(n),t}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups)){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}async loadByAddress(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path);default:return this.loadBinary(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e)switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(e=>{t.textures.set(s.path,e)}));break;case"material":n.push(this.loadMaterial(s.path).then(e=>{t.materials.set(s.path,e)}));break;case"json":n.push(this.loadJson(s.path).then(e=>{t.json.set(s.path,e)}));break;case"text":n.push(this.loadText(s.path).then(e=>{t.text.set(s.path,e)}));break;default:n.push(this.loadBinary(s.path).then(e=>{t.binary.set(s.path,e)}))}return await Promise.all(n),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n)??n;return new Promise((n,r)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>r(new Error(`Failed to load image: ${e}`)),o.src=s})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const c=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:c,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e;if(!await l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:s,fragment:r}=this.parseEsShader(n);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return ft.createShader(s,r)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const n=await c(t);return JSON.parse(n)}const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):c(t)}const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):a(t)}const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Rt=Q(null,"Assets");class Ft{build(e){const t=e.wasmModule;t?e.insertResource(Rt,new At(t)):console.warn("AssetPlugin: No WASM module available")}}const Ut=new Ft;function Bt(e,t){const n=e.getResource(Rt);n&&n.registerEmbeddedAssets(t)}let It=null,kt=0,zt=0,Lt=0;const Dt=new Float32Array(256);function Ht(e){It=e,kt=It._malloc(64),zt=It._malloc(64),Lt=It._malloc(1024)}function Wt(){It&&(kt&&(It._free(kt),kt=0),zt&&(It._free(zt),zt=0),Lt&&(It._free(Lt),Lt=0)),It=null}function $t(){if(!It)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return It}const Ot={r:1,g:1,b:1,a:1},jt={begin(e){const t=$t();t.HEAPF32.set(e,kt/4),t.draw_begin(kt)},end(){$t().draw_end()},line(e,t,n,s=1){$t().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rect(e,t,n,s=!0){$t().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rectOutline(e,t,n,s=1){$t().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},circle(e,t,n,s=!0,r=32){$t().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},circleOutline(e,t,n,s=1,r=32){$t().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=Ot){$t().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)},textureRotated(e,t,n,s,r=Ot){$t().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){$t().draw_setLayer(e)},setDepth(e){$t().draw_setDepth(e)},getDrawCallCount:()=>It?It.draw_getDrawCallCount():0,getPrimitiveCount:()=>It?It.draw_getPrimitiveCount():0,setBlendMode(e){$t().draw_setBlendMode(e)},setDepthTest(e){$t().draw_setDepthTest(e)},drawMesh(e,t,n){const s=$t();s.HEAPF32.set(n,zt/4),s.draw_mesh(e,t,zt)},drawMeshWithMaterial(e,t,n){const s=$t(),r=ft.get(t);if(!r)return;if(jt.setBlendMode(r.blendMode),jt.setDepthTest(r.depthTest),0===r.uniforms.size)return void jt.drawMesh(e,r.shader,n);s.HEAPF32.set(n,zt/4);let o=0,i=0;for(const[e,t]of r.uniforms){const n=Xt(e);if(!(n<0)){if(ot(t))Dt[o++]=10,Dt[o++]=n,Dt[o++]=t.slot??i++,Dt[o++]=t.textureId;else if("number"==typeof t)Dt[o++]=1,Dt[o++]=n,Dt[o++]=t;else if(Array.isArray(t)){Dt[o++]=t.length,Dt[o++]=n;for(let e=0;e<t.length;e++)Dt[o++]=t[e]}else"w"in t?(Dt[o++]=4,Dt[o++]=n,Dt[o++]=t.x,Dt[o++]=t.y,Dt[o++]=t.z,Dt[o++]=t.w):"z"in t?(Dt[o++]=3,Dt[o++]=n,Dt[o++]=t.x,Dt[o++]=t.y,Dt[o++]=t.z):(Dt[o++]=2,Dt[o++]=n,Dt[o++]=t.x,Dt[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(Dt.subarray(0,o),Lt/4),s.draw_meshWithUniforms(e,r.shader,zt,Lt,o)):s.draw_mesh(e,r.shader,zt)}},Nt={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function Xt(e){return Nt[e]??-1}var Vt;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(Vt||(Vt={}));let Yt=null,Gt=0,qt=0,Kt=0;function Jt(e){Yt=e,Gt=Yt._malloc(262144),qt=Yt._malloc(65536),Kt=Yt._malloc(256)}function Qt(){Yt&&(Gt&&Yt._free(Gt),qt&&Yt._free(qt),Kt&&Yt._free(Kt),Gt=0,qt=0,Kt=0),Yt=null}function Zt(){if(!Yt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Yt}const en={create(e){const t=Zt(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,Gt/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Kt,r).set(o),t.geometry_init(n,Gt,s,Kt,r,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,qt,s).set(e.indices),t.geometry_setIndices16(n,qt,s)}else{new Uint32Array(t.HEAPU8.buffer,qt,s).set(e.indices),t.geometry_setIndices32(n,qt,s)}}return n},updateVertices(e,t,n=0){const s=Zt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,Gt/4),s.geometry_updateVertices(e,Gt,r,n)},release(e){e>0&&Zt().geometry_release(e)},isValid:e=>!(!Yt||e<=0)&&Yt.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return en.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:Vt.Float2},{name:"a_texCoord",type:Vt.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,c=(Math.sin(r)+1)/2;n.push(o,i,a,c)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return en.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Vt.Float2},{name:"a_texCoord",type:Vt.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-n);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return en.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Vt.Float2},{name:"a_texCoord",type:Vt.Float2}],indices:new Uint16Array(i)})}};let tn=null;function nn(e){tn=e}function sn(){tn&&on.isInitialized()&&on.shutdown(),tn=null}function rn(){if(!tn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return tn}const on={init:(e,t)=>rn().postprocess_init(e,t),shutdown(){rn().postprocess_shutdown()},resize(e,t){rn().postprocess_resize(e,t)},addPass:(e,t)=>rn().postprocess_addPass(e,t),removePass(e){rn().postprocess_removePass(e)},setEnabled(e,t){rn().postprocess_setPassEnabled(e,t)},isEnabled:e=>rn().postprocess_isPassEnabled(e),setUniform(e,t,n){rn().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){rn().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){rn().postprocess_begin()},end(){rn().postprocess_end()},getPassCount:()=>rn().postprocess_getPassCount(),isInitialized:()=>!!tn&&tn.postprocess_isInitialized(),setBypass(e){rn().postprocess_setBypass(e)},isBypassed:()=>!tn||tn.postprocess_isBypassed(),createBlur:()=>ft.createShader(an,"#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:()=>ft.createShader(an,"#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:()=>ft.createShader(an,"#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:()=>ft.createShader(an,"#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")},an="#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 cn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(cn||(cn={}));let ln=null,un=0;function hn(e){ln=e,un=ln._malloc(64)}function dn(){ln&&un&&(ln._free(un),un=0),ln=null}const fn={init(e,t){ln?.renderer_init(e,t)},resize(e,t){ln?.renderer_resize(e,t)},begin(e,t){ln&&un&&(ln.HEAPF32.set(e,un/4),ln.renderer_begin(un,t??0))},flush(){ln?.renderer_flush()},end(){ln?.renderer_end()},submitSprites(e){ln&&ln.renderer_submitSprites(e._cpp)},submitBitmapText(e){ln&&ln.renderer_submitBitmapText(e._cpp)},submitSpine(e){ln&&ln.renderer_submitSpine?.(e._cpp)},setStage(e){ln?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>ln?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){ln?.renderer_releaseTarget(e)},getTargetTexture:e=>ln?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>ln?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){ln?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){ln?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){ln?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){ln?.renderer_clearBuffers(e)},getStats:()=>ln?{drawCalls:ln.renderer_getDrawCalls(),triangles:ln.renderer_getTriangles(),sprites:ln.renderer_getSprites(),text:ln.renderer_getText(),spine:ln.renderer_getSpine?.()??0,meshes:ln.renderer_getMeshes(),culled:ln.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let pn=null;function _n(e){pn=e}function mn(){pn=null}const gn={enable(){pn?.gl_enableErrorCheck(!0)},disable(){pn?.gl_enableErrorCheck(!1)},check:e=>pn?.gl_checkErrors(e)??0,diagnose(){pn?.renderer_diagnose()}},yn=new Map;function wn(e,t){yn.set(e,t)}function xn(e){yn.delete(e)}function vn(){yn.clear()}class bn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}setSpineRenderer(e){this.spineRenderer_=e}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(fn.resize(s,r),on.isInitialized()&&on.getPassCount()>0&&on.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),fn.setViewport(0,0,s,r),fn.clearBuffers(3),fn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),fn.submitSprites(t),fn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):fn.submitSpine(t),fn.flush(),this.executeDrawCallbacks(n,o),fn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;fn.setViewport(s.x,s.y,s.w,s.h),fn.setScissor(s.x,s.y,s.w,s.h,!0),fn.clearBuffers(r),fn.setScissor(0,0,0,0,!1),fn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),fn.submitSprites(t),fn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):fn.submitSpine(t),fn.flush(),this.executeDrawCallbacks(n,o),fn.end()}executeDrawCallbacks(e,t){const n=yn;if(n.size>0){jt.begin(e);const s=[];for(const[e,r]of n.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}jt.end();for(const e of s)xn(e)}}}class Pn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.runSchedule(he.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(he.FixedPreUpdate),this.runSchedule(he.FixedUpdate),this.runSchedule(he.FixedPostUpdate);this.runSchedule(he.PreUpdate),this.runSchedule(he.Update),this.runSchedule(he.PostUpdate),this.runSchedule(he.Last),requestAnimationFrame(this.mainLoop)},this.world_=new Se,this.resources_=new ne;for(const e of Object.values(he))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Pn}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(he.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(he.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new ye(this.world_,this.resources_),this.resources_.insert(se,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(he.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,mn(),dn(),sn(),Qt(),ht(),Wt()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(se);t.delta=e,t.elapsed+=e,t.frameCount++}}function Sn(e,t){const n=Pn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ht(e),ut(e),Jt(e),nn(e),hn(e),_n(e);const r=new bn;n.pipeline_=r;let o=d();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));n.insertResource(qe,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const a={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:a}=i(),c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;fn.setClearColor(e.r,e.g,e.b,e.a)}const l=(d()-o)/1e3;fn.resize(t,a),on.isInitialized()&&on.getPassCount()>0&&!on.isBypassed()&&on.resize(t,a);const u=function(e,t,n,s){const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),c={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},l=c.w*n/(c.h*s);let u,h=0,d=0;if(1===r.projectionType){if(d=r.orthoSize,o){d=Mn(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,l,o.scaleMode,o.matchWidthOrHeight)}h=d*l,u=An(-h,h,-d,d,-r.farPlane,r.farPlane)}else u=Fn(r.fov*Math.PI/180,l,r.nearPlane,r.farPlane);const f=Bn(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:In(u,f),viewportRect:c,clearFlags:r.clearFlags,priority:r.priority,halfW:h,halfH:d,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}(e,s,t,a),h=n.getResource(qe);if(u.length>0){const e=u[0],n=e.viewportRect;h.viewProjection.set(e.viewProjection),h.vpX=Math.round(n.x*t),h.vpY=Math.round((1-n.y-n.h)*a),h.vpW=Math.round(n.w*t),h.vpH=Math.round(n.h*a),h.screenW=t,h.screenH=a,h.worldLeft=e.cameraX-e.halfW,h.worldRight=e.cameraX+e.halfW,h.worldBottom=e.cameraY-e.halfH,h.worldTop=e.cameraY+e.halfH,h.valid=!0}else h.valid=!1;if(0===u.length)r.render({registry:{_cpp:s},viewProjection:En,width:t,height:a,elapsed:l});else{for(const e of u){const n=e.viewportRect,o=Math.round(n.x*t),i=Math.round((1-n.y-n.h)*a),c=Math.round(n.w*t),u=Math.round(n.h*a);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:c,h:u},clearFlags:e.clearFlags,elapsed:l})}fn.setViewport(0,0,t,a)}}};return n.addSystemToSchedule(he.Last,a),n.addPlugin(Ut),n.addPlugin(be),n.addPlugin(Ue),n.addPlugin(Oe),n.addPlugin(st),n.addPlugin(Qe),n}function Cn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const En=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Mn(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}}}const Tn=new Float32Array(16);function An(e,t,n,s,r,o){const i=Tn;i.fill(0);const a=t-e,c=s-n,l=o-r;return i[0]=2/a,i[5]=2/c,i[10]=-2/l,i[12]=-(t+e)/a,i[13]=-(s+n)/c,i[14]=-(o+r)/l,i[15]=1,i}const Rn=new Float32Array(16);function Fn(e,t,n,s){const r=Rn;r.fill(0);const o=1/Math.tan(e/2),i=n-s;return r[0]=o/t,r[5]=o,r[10]=(s+n)/i,r[11]=-1,r[14]=2*s*n/i,r}const Un=new Float32Array(16);function Bn(e,t,n){const s=Un;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}function In(e,t){const n=new Float32Array(16);for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}async function kn(e,t){if(t)return t();return(0,(await import(e)).default)()}const zn=Q({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Ln=Q(null,"PhysicsAPI");function Dn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Hn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Wn{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(zn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=kn(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([O]);for(const n of t){const t=e.world.get(n,O);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(he.PostUpdate,fe([Z(se)],a=>{const c=i.getEntitiesWithComponents([P,D,H]),l=new Set;for(const r of c){l.add(r);const a=i.get(r,P),c=i.get(r,H);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=Dn(c.rotation);s._physics_createBody(r,a.bodyType,c.position.x*o,c.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),$n(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===M.Kinematic){const e=Dn(c.rotation);s._physics_setBodyTransform(r,c.position.x*o,c.position.y*o,e)}}for(const e of t)l.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,c=t.HEAPF32[s+2]*n,l=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,D);if(!u)continue;let h=a,d=c,f=l;if(e.world.has(i,N)){const t=e.world.get(i,N);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,H)){const n=e.world.get(t.entity,H),s=Dn(n.rotation),r=a-n.position.x,o=c-n.position.y,i=Math.cos(-s),u=Math.sin(-s);h=(r*i-o*u)/(0!==n.scale.x?n.scale.x:1),d=(r*u+o*i)/(0!==n.scale.y?n.scale.y:1),f=l-s}}u.position.x=h,u.position.y=d;const p=Hn(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(i,D,u)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],c=t._physics_getSensorEnterCount();if(c>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<c;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const l=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;l.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(zn,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:l})}(e,s,r)},{name:"PhysicsSystem"})),e.__physicsModule=s,e.insertResource(Ln,On._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=s}}function $n(e,t,n){const s=e.world;if(s.has(n,S)){const e=s.get(n,S);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,C)){const e=s.get(n,C);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,E)){const e=s.get(n,E);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class On{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(On.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function jn(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function Nn(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function Xn(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,c=e.rotation.y,l=e.rotation.z,u=e.rotation.w,h=a+a,d=c+c,f=l+l,p=a*h,_=a*d,m=a*f,g=c*d,y=c*f,w=l*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(g+w))*r,(_+b)*r,(m-v)*r,0,(_-b)*o,(1-(p+w))*o,(y+x)*o,0,(m+v)*i,(y-x)*i,(1-(p+g))*i,0,e.position.x,e.position.y,e.position.z,1])}async function Vn(e,t,n,s,r,o,i){const a=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=jn(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,a);let c={},l=null;if(r&&(l=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),c=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const c=r.resolvePath(i),l=r.resolvePath(a);try{const s=r.readText(a),u=c.endsWith(".skel");let h,d;if(u){const e=r.readBinary(i);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=r.readText(i),n=(new TextEncoder).encode(e);d=n.length,h=t._malloc(d+1),t.HEAPU8.set(n,h),t.HEAPU8[h+d]=0}const f=n.loadSkeleton(h,d,s,s.length,u);if(t._free(h),f<0)continue;o[i]=f;const p=Nn(s),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=_+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=jn(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,l,n,s)),o){new Wn("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const u=function(e,t){const n={},s={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===n[r])try{const e=JSON.parse(t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=ft.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=ft.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),h=Pt(e.world,n);if(function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const r=e.get(t,W);r&&(r.texture=n[s.data.texture]||0,e.insert(t,W,r))}}}(e.world,n,a,h),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const r=n[s.data.material]||0;if(r)if("Sprite"===s.type){const n=e.get(t,W);n&&(n.material=r,e.insert(t,W,n))}else if("SpineAnimation"===s.type){const n=e.get(t,Y);n&&(n.material=r,e.insert(t,Y,n))}}}}(e.world,n,u,h),r&&l){const s=function(e,t,n,s){const r={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const c=s.get(o.id);void 0!==c&&(r[c]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(l,n,c,h);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let c=a-o;o=a,(c<=0||c>.5)&&(c=1/60);const l=e.world;for(const e in r){const o=Number(e),i=r[e],a=l.has(o,Y)?l.get(o,Y):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&s.update(i,c*h);let d=0;if(l.has(o,H)){const e=Xn(l.get(o,H),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,c=2*o,l=n._malloc(a),u=n._malloc(c),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,l,u,h,f);const p=n.HEAPU32[h>>2],_=n.HEAPU32[f>>2],m=new Float32Array(n.HEAPF32.buffer,l,8*r),g=new Uint16Array(n.HEAPU8.buffer,u,o),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(m,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(g),t.renderer_submitTriangles(y,r,w,o,p,_,d),t._free(y),t._free(w),n._free(l),n._free(u),n._free(h),n._free(f)}d&&t._free(d)}})}(e,t,r,l,s)}}class Yn{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set;for(const s of e.entities)for(const e of s.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&(s.endsWith(".skel")?n.add(s):t.add(s)),r&&t.add(r)}"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const s=[];for(const e of t)s.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of n)s.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(s)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class Gn{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 Yn(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.__spineInitPromise;if(r){s=(await r).controller.raw}await Vn(this.app_,this.app_.wasmModule,t,n,s),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([$]);for(const s of n){if(e.get(s,$).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const s=e.getEntitiesWithComponents([O]);for(const r of s){const s=e.get(r,O);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,D,o);const i={isActive:!0,projectionType:0,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3};e.insert(r,$,i)}}}const qn={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=fn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:fn.getTargetTexture(n),width:e.width,height:e.height}},release(e){fn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(fn.releaseRenderTarget(e._handle),qn.create({width:t,height:n,depth:!0})),begin(e,t){fn.begin(t,e._handle)},end(){fn.end()},getDepthTexture:e=>fn.getTargetDepthTexture(e._handle)};let Kn=!1;function Jn(e){Kn=e}function Qn(){return Kn}function Zn(){return!Kn}e=f;export{Pn as App,Ft as AssetPlugin,At as AssetServer,Rt as Assets,Tt as AsyncCache,V as BitmapText,rt as BlendMode,M as BodyType,S as BoxCollider,Ve as Button,Xe as ButtonState,$ as Camera,O as Canvas,E as CapsuleCollider,X as Children,C as CircleCollider,ce as Commands,ue as CommandsInstance,Vt as DataType,jt as Draw,le as EntityCommands,gn as GLDebug,en as Geometry,p as INVALID_ENTITY,m as INVALID_FONT,_ as INVALID_TEXTURE,xe as Input,ve as InputPlugin,we as InputState,je as Interactable,D as LocalTransform,ft as Material,bt as MaterialLoader,re as Mut,G as Name,N as Parent,On as Physics,zn as PhysicsEvents,Wn as PhysicsPlugin,on as PostProcess,Gn as PreviewPlugin,ie as Query,ae as QueryInstance,bn as RenderPipeline,cn as RenderStage,qn as RenderTexture,fn as Renderer,Z as Res,ee as ResMut,P as RigidBody,he as Schedule,Ze as ScreenSpace,vt as ShaderSources,Y as SpineAnimation,W as Sprite,ye as SystemRunner,Te as Text,Ce as TextAlign,Me as TextOverflow,Fe as TextPlugin,Ae as TextRenderer,Ee as TextVerticalAlign,se as Time,qe as UICameraInfo,Ye as UIEventQueue,Ge as UIEvents,Ne as UIInteraction,Je as UIInteractionPlugin,nt as UILayoutPlugin,Be as UIMask,$e as UIMaskPlugin,Re as UIRect,j as Velocity,Yn as WebAssetProvider,Se as World,H as WorldTransform,me as addStartupSystem,_e as addSystem,ge as addSystemToSchedule,Ut as assetPlugin,vn as clearDrawCallbacks,I as clearUserComponents,x as color,et as computeUIRectLayout,We as createMaskProcessor,Sn as createWebApp,F as defineComponent,Q as defineResource,fe as defineSystem,U as defineTag,Mt as findEntityByName,Cn as flushPendingSystems,K as getComponentDefaults,t as getPlatform,s as getPlatformType,B as getUserComponent,Ht as initDrawAPI,_n as initGLDebugAPI,Jt as initGeometryAPI,ut as initMaterialAPI,nn as initPostProcessAPI,hn as initRendererAPI,be as inputPlugin,Ie as intersectRects,ze as invertMatrix4,L as isBuiltinComponent,Qn as isEditor,n as isPlatformInitialized,Zn as isRuntime,ot as isTextureRef,r as isWeChat,o as isWeb,Ct as loadComponent,kn as loadPhysicsModule,Vn as loadRuntimeScene,Pt as loadSceneData,St as loadSceneWithAssets,i as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,De as pointInWorldRect,v as quat,wn as registerDrawCallback,Bt as registerEmbeddedAssets,xt as registerMaterialCallback,Le as screenToWorld,Jn as setEditorMode,Wt as shutdownDrawAPI,mn as shutdownGLDebugAPI,Qt as shutdownGeometryAPI,ht as shutdownMaterialAPI,sn as shutdownPostProcessAPI,dn as shutdownRendererAPI,Ue as textPlugin,Qe as uiInteractionPlugin,st as uiLayoutPlugin,Oe as uiMaskPlugin,xn as unregisterDrawCallback,Et as updateCameraAspectRatio,g as vec2,y as vec3,w as vec4,ke as worldRectToScreen};//# sourceMappingURL=index.js.mapdiff --git a/editor/src/asset/AssetLibrary.ts b/editor/src/asset/AssetLibrary.tsindex 024b0d18b..1071284ac 100644--- a/editor/src/asset/AssetLibrary.ts+++ b/editor/src/asset/AssetLibrary.ts@@ -1,302 +1,17 @@/*** @file AssetLibrary.ts- * @brief UUID-based asset library with bidirectional path/UUID mapping+ * @brief Backward-compatible re-export from AssetDatabase*/-import type { SceneData } from '../types/SceneTypes';-import type { TextureMetadata } from '../types/TextureMetadata';-import { joinPath, getFileExtension } from '../utils/path';-import type { NativeFS } from '../types/NativeFS';-import { ASSET_EXTENSIONS, getAssetType } from './AssetTypes';--// =============================================================================-// Types-// =============================================================================--interface AssetMeta {- uuid: string;- version: string;- type: string;- sliceBorder?: { left: number; right: number; top: number; bottom: number };-}--const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;--export function isUUID(value: string): boolean {- return UUID_REGEX.test(value);-}--// =============================================================================-// AssetLibrary-// =============================================================================--export class AssetLibrary {- private uuidToPath_ = new Map<string, string>();- private pathToUuid_ = new Map<string, string>();- private fs_: NativeFS | null = null;- private projectDir_ = '';-- async initialize(projectDir: string, fs: NativeFS): Promise<void> {- this.fs_ = fs;- this.projectDir_ = projectDir;- this.uuidToPath_.clear();- this.pathToUuid_.clear();-- const assetsDir = joinPath(projectDir, 'assets');- if (await fs.exists(assetsDir)) {- await this.scanDirectory(assetsDir, 'assets');- }- }-- getPath(uuid: string): string | undefined {- return this.uuidToPath_.get(uuid);- }-- getUuid(path: string): string | undefined {- return this.pathToUuid_.get(path);- }-- async ensureMeta(relativePath: string): Promise<string> {- const existing = this.pathToUuid_.get(relativePath);- if (existing) return existing;-- if (!this.fs_) {- throw new Error('AssetLibrary not initialized');- }-- const fullPath = joinPath(this.projectDir_, relativePath);- const metaPath = `${fullPath}.meta`;-- if (await this.fs_.exists(metaPath)) {- const content = await this.fs_.readFile(metaPath);- if (content) {- try {- const meta = JSON.parse(content) as AssetMeta;- if (meta.uuid) {- this.register(meta.uuid, relativePath);- return meta.uuid;- }- } catch {- // Fall through to create new meta- }- }- }-- const uuid = crypto.randomUUID();- const assetType = getAssetType(relativePath);- const meta: AssetMeta = {- uuid,- version: '1.0',- type: assetType,- };-- if (assetType === 'texture') {- const existingContent = await this.fs_.readFile(metaPath);- if (existingContent) {- try {- const existing = JSON.parse(existingContent);- if (existing.sliceBorder) {- meta.sliceBorder = existing.sliceBorder;- }- } catch {- // ignore- }- }- if (!meta.sliceBorder) {- meta.sliceBorder = { left: 0, right: 0, top: 0, bottom: 0 };- }- }-- await this.fs_.writeFile(metaPath, JSON.stringify(meta, null, 2));- this.register(uuid, relativePath);- return uuid;- }-- async migrateScene(scene: SceneData): Promise<boolean> {- if (scene.version === '2.0') return false;- if (!this.fs_) return false;-- let changed = false;-- for (const entity of scene.entities) {- for (const comp of entity.components || []) {- if (comp.type === 'Sprite' && comp.data) {- if (typeof comp.data.texture === 'string' && !isUUID(comp.data.texture as string)) {- const uuid = await this.ensureMeta(comp.data.texture as string);- comp.data.texture = uuid;- changed = true;- }- if (typeof comp.data.material === 'string' && !isUUID(comp.data.material as string)) {- const uuid = await this.ensureMeta(comp.data.material as string);- comp.data.material = uuid;- changed = true;- }- }-- if (comp.type === 'SpineAnimation' && comp.data) {- if (typeof comp.data.skeletonPath === 'string' && !isUUID(comp.data.skeletonPath as string)) {- const uuid = await this.ensureMeta(comp.data.skeletonPath as string);- comp.data.skeletonPath = uuid;- changed = true;- }- if (typeof comp.data.atlasPath === 'string' && !isUUID(comp.data.atlasPath as string)) {- const uuid = await this.ensureMeta(comp.data.atlasPath as string);- comp.data.atlasPath = uuid;- changed = true;- }- if (typeof comp.data.material === 'string' && !isUUID(comp.data.material as string)) {- const uuid = await this.ensureMeta(comp.data.material as string);- comp.data.material = uuid;- changed = true;- }- }- }- }-- if (scene.textureMetadata) {- const newMetadata: Record<string, TextureMetadata> = {};- for (const [key, value] of Object.entries(scene.textureMetadata)) {- if (isUUID(key)) {- newMetadata[key] = value;- } else {- const uuid = await this.ensureMeta(key);- newMetadata[uuid] = value;- changed = true;- }- }- scene.textureMetadata = newMetadata;- }-- if (changed) {- scene.version = '2.0';- }-- return changed;- }-- resolveSceneAssetPaths(scene: SceneData): void {- for (const entity of scene.entities) {- for (const comp of entity.components || []) {- if (comp.type === 'Sprite' && comp.data) {- if (typeof comp.data.texture === 'string' && isUUID(comp.data.texture as string)) {- const path = this.getPath(comp.data.texture as string);- if (path) comp.data.texture = path;- }- if (typeof comp.data.material === 'string' && isUUID(comp.data.material as string)) {- const path = this.getPath(comp.data.material as string);- if (path) comp.data.material = path;- }- }-- if (comp.type === 'SpineAnimation' && comp.data) {- if (typeof comp.data.skeletonPath === 'string' && isUUID(comp.data.skeletonPath as string)) {- const path = this.getPath(comp.data.skeletonPath as string);- if (path) comp.data.skeletonPath = path;- }- if (typeof comp.data.atlasPath === 'string' && isUUID(comp.data.atlasPath as string)) {- const path = this.getPath(comp.data.atlasPath as string);- if (path) comp.data.atlasPath = path;- }- if (typeof comp.data.material === 'string' && isUUID(comp.data.material as string)) {- const path = this.getPath(comp.data.material as string);- if (path) comp.data.material = path;- }- }- }- }-- if (scene.textureMetadata) {- const resolved: Record<string, TextureMetadata> = {};- for (const [key, value] of Object.entries(scene.textureMetadata)) {- if (isUUID(key)) {- const path = this.getPath(key);- if (path) {- resolved[path] = value;- } else {- resolved[key] = value;- }- } else {- resolved[key] = value;- }- }- scene.textureMetadata = resolved;- }- }-- unregister(relativePath: string): void {- const uuid = this.pathToUuid_.get(relativePath);- if (uuid) {- this.uuidToPath_.delete(uuid);- }- this.pathToUuid_.delete(relativePath);- }-- updatePath(oldRelativePath: string, newRelativePath: string): void {- const uuid = this.pathToUuid_.get(oldRelativePath);- if (uuid) {- this.uuidToPath_.set(uuid, newRelativePath);- }- this.pathToUuid_.delete(oldRelativePath);- if (uuid) {- this.pathToUuid_.set(newRelativePath, uuid);- }- }-- private register(uuid: string, relativePath: string): void {- this.uuidToPath_.set(uuid, relativePath);- this.pathToUuid_.set(relativePath, uuid);- }-- private async scanDirectory(absolutePath: string, relativePath: string): Promise<void> {- if (!this.fs_) return;-- const entries = await this.fs_.listDirectoryDetailed(absolutePath);-- for (const entry of entries) {- const childAbsolute = joinPath(absolutePath, entry.name);- const childRelative = `${relativePath}/${entry.name}`;-- if (entry.isDirectory) {- await this.scanDirectory(childAbsolute, childRelative);- } else if (entry.name.endsWith('.meta')) {- const content = await this.fs_.readFile(childAbsolute);- if (content) {- try {- const meta = JSON.parse(content) as AssetMeta;- if (meta.uuid) {- const assetRelPath = childRelative.replace(/\.meta$/, '');- this.register(meta.uuid, assetRelPath);- }- } catch {- // Skip invalid meta files- }- }- } else {- const ext = getFileExtension(entry.name);- if (ASSET_EXTENSIONS.has(ext)) {- const metaAbsolute = `${childAbsolute}.meta`;- if (!await this.fs_.exists(metaAbsolute)) {- await this.ensureMeta(childRelative);- }- }- }- }- }-}--// =============================================================================-// Singleton-// =============================================================================--let instance: AssetLibrary | null = null;--export function getAssetLibrary(): AssetLibrary {- if (!instance) {- instance = new AssetLibrary();- }- return instance;-}--export function resetAssetLibrary(): void {- instance = null;-}+export {+ AssetDatabase as AssetLibrary,+ AssetDatabase,+ getAssetDatabase as getAssetLibrary,+ getAssetDatabase,+ resetAssetDatabase as resetAssetLibrary,+ resetAssetDatabase,+ isUUID,+ getComponentRefFields,+ registerComponentRefFields,+ type AssetEntry,+} from './AssetDatabase';diff --git a/editor/src/asset/ImporterRegistry.ts b/editor/src/asset/ImporterRegistry.tsnew file mode 100644index 000000000..5b897f81c--- /dev/null+++ b/editor/src/asset/ImporterRegistry.ts@@ -0,0 +1,89 @@+/**+ * @file ImporterRegistry.ts+ * @brief Registry for asset importers with per-type settings and UI generation+ */++import type { AssetEntry } from './AssetDatabase';+import { TextureImporter } from './importers/TextureImporter';+import { AudioImporter } from './importers/AudioImporter';++// =============================================================================+// Types+// =============================================================================++export type ImporterFieldType = 'number' | 'boolean' | 'select' | 'slider' | 'sliceBorder';++export interface ImporterField {+ name: string;+ label: string;+ type: ImporterFieldType;+ value: unknown;+ options?: { label: string; value: unknown }[];+ min?: number;+ max?: number;+ step?: number;+}++export interface AssetImporter<T = Record<string, unknown>> {+ type: string;+ extensions: string[];+ defaultSettings(): T;+ settingsUI(current: T): ImporterField[];+ apply?(asset: AssetEntry, settings: T): void;+}++// =============================================================================+// ImporterRegistry+// =============================================================================++class ImporterRegistryImpl {+ private importers_ = new Map<string, AssetImporter<any>>();+ private extToType_ = new Map<string, string>();++ register(importer: AssetImporter<any>): void {+ this.importers_.set(importer.type, importer);+ for (const ext of importer.extensions) {+ this.extToType_.set(ext, importer.type);+ }+ }++ get(type: string): AssetImporter<any> | undefined {+ return this.importers_.get(type);+ }++ getByExtension(ext: string): AssetImporter<any> | undefined {+ const type = this.extToType_.get(ext);+ return type ? this.importers_.get(type) : undefined;+ }++ getDefaultSettings(type: string): Record<string, unknown> {+ const importer = this.importers_.get(type);+ if (!importer) return {};+ return importer.defaultSettings() as Record<string, unknown>;+ }++ getSettingsUI(type: string, current: Record<string, unknown>): ImporterField[] {+ const importer = this.importers_.get(type);+ if (!importer) return [];+ return importer.settingsUI(current as any);+ }++ getAllTypes(): string[] {+ return [...this.importers_.keys()];+ }+}++// =============================================================================+// Singleton+// =============================================================================++let registry: ImporterRegistryImpl | null = null;++export function getImporterRegistry(): ImporterRegistryImpl {+ if (!registry) {+ registry = new ImporterRegistryImpl();+ registry.register(new TextureImporter());+ registry.register(new AudioImporter());+ }+ return registry;+}diff --git a/editor/src/asset/ImporterTypes.ts b/editor/src/asset/ImporterTypes.tsnew file mode 100644index 000000000..c4d5c99a4--- /dev/null+++ b/editor/src/asset/ImporterTypes.ts@@ -0,0 +1,144 @@+/**+ * @file ImporterTypes.ts+ * @brief Type definitions for asset importer settings per asset type+ */++// =============================================================================+// Per-Type Importer Settings+// =============================================================================++export interface TextureImporterSettings {+ maxSize: number;+ filterMode: 'linear' | 'nearest';+ wrapMode: 'repeat' | 'clamp' | 'mirror';+ premultiplyAlpha: boolean;+ sliceBorder: { left: number; right: number; top: number; bottom: number };+}++export interface AudioImporterSettings {+ sampleRate: number;+ channels: 1 | 2;+ quality: number;+}++export type ImporterSettings =+ | TextureImporterSettings+ | AudioImporterSettings+ | Record<string, unknown>;++// =============================================================================+// Default Settings Factories+// =============================================================================++export function createDefaultTextureImporter(): TextureImporterSettings {+ return {+ maxSize: 2048,+ filterMode: 'linear',+ wrapMode: 'repeat',+ premultiplyAlpha: false,+ sliceBorder: { left: 0, right: 0, top: 0, bottom: 0 },+ };+}++export function createDefaultAudioImporter(): AudioImporterSettings {+ return {+ sampleRate: 44100,+ channels: 2,+ quality: 0.8,+ };+}++export function getDefaultImporterForType(type: string): Record<string, unknown> {+ switch (type) {+ case 'texture':+ return createDefaultTextureImporter() as unknown as Record<string, unknown>;+ case 'audio':+ return createDefaultAudioImporter() as unknown as Record<string, unknown>;+ default:+ return {};+ }+}++// =============================================================================+// Asset Meta (v2.0)+// =============================================================================++export interface AssetMeta {+ uuid: string;+ version: string;+ type: string;+ labels: string[];+ address: string | null;+ importer: Record<string, unknown>;+ platformOverrides: Record<string, Record<string, unknown>>;+ sliceBorder?: { left: number; right: number; top: number; bottom: number };+}++export function createDefaultMeta(uuid: string, type: string): AssetMeta {+ return {+ uuid,+ version: '2.0',+ type,+ labels: [],+ address: null,+ importer: getDefaultImporterForType(type),+ platformOverrides: {},+ };+}++/**+ * Upgrade a v1.0 meta object to v2.0 format.+ * Preserves existing sliceBorder by migrating it into importer.+ */+export function upgradeMeta(raw: Record<string, unknown>): AssetMeta {+ const uuid = raw.uuid as string;+ const type = (raw.type as string) || 'unknown';+ const meta = createDefaultMeta(uuid, type);++ if (raw.labels && Array.isArray(raw.labels)) {+ meta.labels = raw.labels as string[];+ }+ if (typeof raw.address === 'string') {+ meta.address = raw.address;+ }+ if (raw.importer && typeof raw.importer === 'object') {+ meta.importer = { ...meta.importer, ...(raw.importer as Record<string, unknown>) };+ }+ if (raw.platformOverrides && typeof raw.platformOverrides === 'object') {+ meta.platformOverrides = raw.platformOverrides as Record<string, Record<string, unknown>>;+ }++ if (type === 'texture' && raw.sliceBorder && typeof raw.sliceBorder === 'object') {+ (meta.importer as unknown as TextureImporterSettings).sliceBorder =+ raw.sliceBorder as TextureImporterSettings['sliceBorder'];+ }++ return meta;+}++/**+ * Serialize meta to JSON for writing to .meta file.+ * Omits empty/default fields to keep files compact.+ */+export function serializeMeta(meta: AssetMeta): string {+ const obj: Record<string, unknown> = {+ uuid: meta.uuid,+ version: meta.version,+ type: meta.type,+ };++ if (meta.labels.length > 0) {+ obj.labels = meta.labels;+ }+ if (meta.address !== null) {+ obj.address = meta.address;+ }+ if (Object.keys(meta.importer).length > 0) {+ obj.importer = meta.importer;+ }+ if (Object.keys(meta.platformOverrides).length > 0) {+ obj.platformOverrides = meta.platformOverrides;+ }++ return JSON.stringify(obj, null, 2);+}diff --git a/editor/src/asset/importers/AudioImporter.ts b/editor/src/asset/importers/AudioImporter.tsnew file mode 100644index 000000000..169343a16--- /dev/null+++ b/editor/src/asset/importers/AudioImporter.ts@@ -0,0 +1,52 @@+/**+ * @file AudioImporter.ts+ * @brief Importer for audio assets (mp3, wav, ogg)+ */++import type { AssetImporter, ImporterField } from '../ImporterRegistry';+import type { AudioImporterSettings } from '../ImporterTypes';+import { createDefaultAudioImporter } from '../ImporterTypes';++export class AudioImporter implements AssetImporter<AudioImporterSettings> {+ readonly type = 'audio';+ readonly extensions = ['.mp3', '.wav', '.ogg'];++ defaultSettings(): AudioImporterSettings {+ return createDefaultAudioImporter();+ }++ settingsUI(current: AudioImporterSettings): ImporterField[] {+ return [+ {+ name: 'sampleRate',+ label: 'Sample Rate',+ type: 'select',+ value: current.sampleRate,+ options: [+ { label: '22050 Hz', value: 22050 },+ { label: '44100 Hz', value: 44100 },+ { label: '48000 Hz', value: 48000 },+ ],+ },+ {+ name: 'channels',+ label: 'Channels',+ type: 'select',+ value: current.channels,+ options: [+ { label: 'Mono', value: 1 },+ { label: 'Stereo', value: 2 },+ ],+ },+ {+ name: 'quality',+ label: 'Quality',+ type: 'slider',+ value: current.quality,+ min: 0.1,+ max: 1.0,+ step: 0.1,+ },+ ];+ }+}diff --git a/editor/src/asset/importers/TextureImporter.ts b/editor/src/asset/importers/TextureImporter.tsnew file mode 100644index 000000000..8467eb029--- /dev/null+++ b/editor/src/asset/importers/TextureImporter.ts@@ -0,0 +1,68 @@+/**+ * @file TextureImporter.ts+ * @brief Importer for texture assets (png, jpg, gif, webp, svg)+ */++import type { AssetImporter, ImporterField } from '../ImporterRegistry';+import type { TextureImporterSettings } from '../ImporterTypes';+import { createDefaultTextureImporter } from '../ImporterTypes';++export class TextureImporter implements AssetImporter<TextureImporterSettings> {+ readonly type = 'texture';+ readonly extensions = ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'];++ defaultSettings(): TextureImporterSettings {+ return createDefaultTextureImporter();+ }++ settingsUI(current: TextureImporterSettings): ImporterField[] {+ return [+ {+ name: 'maxSize',+ label: 'Max Size',+ type: 'select',+ value: current.maxSize,+ options: [+ { label: '256', value: 256 },+ { label: '512', value: 512 },+ { label: '1024', value: 1024 },+ { label: '2048', value: 2048 },+ { label: '4096', value: 4096 },+ ],+ },+ {+ name: 'filterMode',+ label: 'Filter Mode',+ type: 'select',+ value: current.filterMode,+ options: [+ { label: 'Linear', value: 'linear' },+ { label: 'Nearest', value: 'nearest' },+ ],+ },+ {+ name: 'wrapMode',+ label: 'Wrap Mode',+ type: 'select',+ value: current.wrapMode,+ options: [+ { label: 'Repeat', value: 'repeat' },+ { label: 'Clamp', value: 'clamp' },+ { label: 'Mirror', value: 'mirror' },+ ],+ },+ {+ name: 'premultiplyAlpha',+ label: 'Premultiply Alpha',+ type: 'boolean',+ value: current.premultiplyAlpha,+ },+ {+ name: 'sliceBorder',+ label: 'Slice Border',+ type: 'sliceBorder',+ value: current.sliceBorder,+ },+ ];+ }+}diff --git a/editor/src/asset/index.ts b/editor/src/asset/index.tsindex 65554e5ad..153ab2b26 100644--- a/editor/src/asset/index.ts+++ b/editor/src/asset/index.ts@@ -18,11 +18,52 @@ export {} from './AssetDependencyGraph';export {- AssetLibrary,- getAssetLibrary,- resetAssetLibrary,+ AssetDatabase,+ AssetDatabase as AssetLibrary,+ getAssetDatabase,+ getAssetDatabase as getAssetLibrary,+ resetAssetDatabase,+ resetAssetDatabase as resetAssetLibrary,isUUID,-} from './AssetLibrary';+ getComponentRefFields,+ registerComponentRefFields,+ type AssetEntry,+} from './AssetDatabase';++export {+ AssetGroupService,+ type AssetGroupDef,+ type AssetGroupsConfig,+ type BundleMode,+} from './AssetGroup';++export {+ AssetDependencyAnalyzer,+ collectReferencedAssets,+ registerRefScanner,+ type AssetRefScanner,+ type DependencyGraph,+} from './AssetDependencyAnalyzer';++export {+ getImporterRegistry,+ type AssetImporter,+ type ImporterField,+ type ImporterFieldType,+} from './ImporterRegistry';++export {+ type AssetMeta,+ type TextureImporterSettings,+ type AudioImporterSettings,+ type ImporterSettings,+ createDefaultMeta,+ upgradeMeta,+ serializeMeta,+ getDefaultImporterForType,+ createDefaultTextureImporter,+ createDefaultAudioImporter,+} from './ImporterTypes';import { AssetPathResolver } from './AssetPathResolver';diff --git a/editor/src/builder/ArtifactBuilder.ts b/editor/src/builder/ArtifactBuilder.tsnew file mode 100644index 000000000..ed4c73998--- /dev/null+++ b/editor/src/builder/ArtifactBuilder.ts@@ -0,0 +1,196 @@+/**+ * @file ArtifactBuilder.ts+ * @brief Shared build artifact pipeline: asset collection, atlas packing, material compilation+ */++import * as esbuild from 'esbuild-wasm/esm/browser';+import type { BuildConfig } from '../types/BuildTypes';+import type { BuildArtifact } from './PlatformEmitter';+import type { NativeFS } from '../types/NativeFS';+import { BuildProgressReporter } from './BuildProgress';+import { AssetExportConfigService, BuildAssetCollector } from './AssetCollector';+import { TextureAtlasPacker } from './TextureAtlas';+import { AssetLibrary } from '../asset/AssetLibrary';+import { compileMaterials } from './MaterialCompiler';+import { normalizePath, joinPath, isAbsolutePath, getParentDir } from '../utils/path';+import { getEsbuildWasmURL } from '../context/EditorContext';++// =============================================================================+// buildArtifact+// =============================================================================++export async function buildArtifact(+ fs: NativeFS,+ projectDir: string,+ config: BuildConfig,+ progress: BuildProgressReporter+): Promise<BuildArtifact> {+ const assetLibrary = new AssetLibrary();+ await assetLibrary.initialize(projectDir, fs);+ progress.log('info', 'Asset library initialized');++ const configService = new AssetExportConfigService(projectDir, fs);+ const exportConfig = await configService.load();++ const collector = new BuildAssetCollector(fs, projectDir, assetLibrary);+ const assetPaths = await collector.collect(config, exportConfig);++ progress.setPhase('processing_assets');+ progress.setCurrentTask('Packing texture atlas...', 0);++ const imagePaths = [...assetPaths].filter(p => {+ const ext = p.split('.').pop()?.toLowerCase() ?? '';+ return ext === 'png' || ext === 'jpg' || ext === 'jpeg';+ });++ const sceneDataList: Array<{ name: string; data: Record<string, unknown> }> = [];+ for (const scenePath of config.scenes) {+ const fullPath = isAbsolutePath(scenePath)+ ? normalizePath(scenePath)+ : joinPath(projectDir, scenePath);+ const content = await fs.readFile(fullPath);+ if (content) {+ const name = scenePath.replace(/.*\//, '').replace('.esscene', '');+ sceneDataList.push({ name, data: JSON.parse(content) });+ }+ }++ const packer = new TextureAtlasPacker(fs, projectDir, assetLibrary);+ const atlasResult = await packer.pack(imagePaths, sceneDataList, 2048, [...assetPaths]);+ const packedPaths = new Set<string>(atlasResult.frameMap.keys());++ if (atlasResult.pages.length > 0) {+ progress.log('info', `Packed ${atlasResult.frameMap.size} textures into ${atlasResult.pages.length} atlas page(s)`);+ }++ progress.setCurrentTask('Compiling materials...', 20);+ const compiledMaterials = await compileMaterials(fs, projectDir, assetLibrary, config, exportConfig);+ progress.log('info', `Compiled ${compiledMaterials.length} material(s)`);++ progress.setCurrentTask('Processing scenes...', 40);+ const scenes = new Map<string, Record<string, unknown>>();+ for (const scenePath of config.scenes) {+ const fullPath = isAbsolutePath(scenePath)+ ? normalizePath(scenePath)+ : joinPath(projectDir, scenePath);+ const content = await fs.readFile(fullPath);+ if (content) {+ const name = scenePath.replace(/.*\//, '').replace('.esscene', '');+ const sceneData = JSON.parse(content);+ packer.rewriteSceneData(sceneData, atlasResult, '');+ scenes.set(name, sceneData);+ }+ }++ return {+ scenes,+ assetPaths,+ atlasResult,+ packedPaths,+ compiledMaterials,+ assetLibrary,+ };+}++// =============================================================================+// Shared esbuild utilities+// =============================================================================++export type SdkModuleLoader = (path: string) => Promise<{ contents: string; loader: esbuild.Loader }>;++export async function initializeEsbuild(): Promise<void> {+ try {+ await esbuild.initialize({ wasmURL: getEsbuildWasmURL() });+ } catch (err) {+ if (!String(err).includes('Cannot call "initialize" more than once')) {+ throw err;+ }+ }+}++export function createBuildVirtualFsPlugin(+ fs: NativeFS,+ projectDir: string,+ loadSdkModule: SdkModuleLoader,+ preferEsmEntry = true+): esbuild.Plugin {+ return {+ name: 'virtual-fs',+ setup(build) {+ build.onResolve({ filter: /^esengine(\/wasm)?$/ }, (args) => ({+ path: args.path,+ namespace: 'esengine-sdk',+ }));++ build.onLoad({ filter: /.*/, namespace: 'esengine-sdk' }, async (args) => {+ return loadSdkModule(args.path);+ });++ build.onResolve({ filter: /.*/ }, async (args) => {+ if (args.kind === 'entry-point') {+ return { path: args.path, namespace: 'virtual' };+ }++ let resolvedPath = args.path;++ if (isAbsolutePath(args.path)) {+ resolvedPath = normalizePath(args.path);+ } else if (args.path.startsWith('.')) {+ const baseDir = args.importer ? getParentDir(args.importer) : args.resolveDir;+ resolvedPath = joinPath(baseDir, args.path);+ } else {+ const pkgPath = joinPath(projectDir, 'node_modules', args.path, 'package.json');+ const pkgContent = await fs.readFile(pkgPath);+ if (pkgContent) {+ try {+ const pkg = JSON.parse(pkgContent);+ let entry = preferEsmEntry+ ? (pkg.module || pkg.main || 'index.js')+ : (pkg.main || 'index.js');+ if (pkg.exports) {+ const root = pkg.exports['.'];+ if (typeof root === 'string') {+ entry = root;+ } else if (root?.import) {+ entry = root.import;+ } else if (root?.default) {+ entry = root.default;+ }+ }+ resolvedPath = joinPath(projectDir, 'node_modules', args.path, entry);+ } catch {+ throw new Error(`Failed to parse package.json for: ${args.path}`);+ }+ } else {+ throw new Error(`Module not found: ${args.path}. Please install it with npm.`);+ }+ }++ if (!resolvedPath.endsWith('.ts') && !resolvedPath.endsWith('.js')) {+ if (await fs.exists(resolvedPath + '.ts')) {+ resolvedPath += '.ts';+ } else if (await fs.exists(resolvedPath + '.js')) {+ resolvedPath += '.js';+ } else if (await fs.exists(joinPath(resolvedPath, 'index.ts'))) {+ resolvedPath = joinPath(resolvedPath, 'index.ts');+ } else if (await fs.exists(joinPath(resolvedPath, 'index.js'))) {+ resolvedPath = joinPath(resolvedPath, 'index.js');+ } else {+ resolvedPath += '.ts';+ }+ }++ return { path: resolvedPath, namespace: 'virtual' };+ });++ build.onLoad({ filter: /.*/, namespace: 'virtual' }, async (args) => {+ const content = await fs.readFile(args.path);+ if (content === null) {+ return { contents: '', loader: 'ts' };+ }+ const loader = args.path.endsWith('.ts') ? 'ts' : 'js';+ return { contents: content, loader };+ });+ },+ };+}diff --git a/editor/src/builder/AssetCollector.ts b/editor/src/builder/AssetCollector.tsindex e96fcc1a1..8aaf90075 100644--- a/editor/src/builder/AssetCollector.ts+++ b/editor/src/builder/AssetCollector.ts@@ -4,10 +4,13 @@*/import type { BuildConfig } from '../types/BuildTypes';-import { type AssetLibrary, isUUID } from '../asset/AssetLibrary';+import { type AssetDatabase, isUUID } from '../asset/AssetDatabase';import { normalizePath, joinPath, isAbsolutePath, getFileExtension, getDirName } from '../utils/path';import type { NativeFS } from '../types/NativeFS';import { ASSET_EXTENSIONS, looksLikeAssetPath } from '../asset/AssetTypes';+import { getComponentRefFields } from '../asset/AssetDatabase';++type AssetLibrary = AssetDatabase;// =============================================================================// Types@@ -131,29 +134,24 @@ export class AssetReferenceCollector {for (const entity of entities) {for (const comp of entity.components || []) {- if (comp.type === 'Sprite' && comp.data) {- if (typeof comp.data.texture === 'string') {- refs.add(this.resolveRef(comp.data.texture));- }- if (typeof comp.data.material === 'string') {- await this.collectMaterialRefs(this.resolveRef(comp.data.material), refs, visited);- }- }-- if (comp.type === 'SpineAnimation' && comp.data) {- const skelPath = comp.data.skeletonPath;- const atlasPath = comp.data.atlasPath;-- if (typeof skelPath === 'string') {- refs.add(this.resolveRef(skelPath));- }- if (typeof atlasPath === 'string') {- const resolvedAtlas = this.resolveRef(atlasPath);- refs.add(resolvedAtlas);- await this.collectAtlasTextures(resolvedAtlas, refs);- }- if (typeof comp.data.material === 'string') {- await this.collectMaterialRefs(this.resolveRef(comp.data.material), refs, visited);+ if (!comp.data) continue;++ const refFields = getComponentRefFields(comp.type);+ if (refFields) {+ for (const field of refFields) {+ const value = comp.data[field];+ if (typeof value !== 'string') continue;++ const resolved = this.resolveRef(value);++ if (resolved.endsWith('.esmaterial')) {+ await this.collectMaterialRefs(resolved, refs, visited);+ } else if (resolved.endsWith('.atlas')) {+ refs.add(resolved);+ await this.collectAtlasTextures(resolved, refs);+ } else {+ refs.add(resolved);+ }}}}diff --git a/editor/src/builder/BuildService.ts b/editor/src/builder/BuildService.tsindex 8bffd49d4..80a7ab0cf 100644--- a/editor/src/builder/BuildService.ts+++ b/editor/src/builder/BuildService.ts@@ -5,13 +5,16 @@import type { BuildConfig } from '../types/BuildTypes';import type { SpineVersion } from '../types/ProjectTypes';-import { PlayableBuilder } from './PlayableBuilder';-import { WeChatBuilder } from './WeChatBuilder';+import type { PlatformEmitter } from './PlatformEmitter';+import { buildArtifact } from './ArtifactBuilder';+import { PlayableEmitter } from './PlayableEmitter';+import { WeChatEmitter } from './WeChatEmitter';import { BuildCache } from './BuildCache';import { BuildProgressReporter, formatDuration } from './BuildProgress';import { BuildHistory } from './BuildHistory';import { getProjectDir } from '../utils/path';import { loadProjectConfig } from '../launcher/ProjectService';+import { getEditorContext } from '../context/EditorContext';// =============================================================================// Types@@ -90,14 +93,20 @@ export class BuildService {};try {- let result: BuildResult;+ const fs = getEditorContext().fs;+ if (!fs) {+ progress.fail('Native file system not available');+ return { success: false, error: 'Native file system not available' };+ }++ const projectDir = getProjectDir(this.projectPath_);+ const artifact = await buildArtifact(fs, projectDir, config, progress);+ let emitter: PlatformEmitter;if (config.platform === 'playable') {- const builder = new PlayableBuilder(context);- result = await builder.build();+ emitter = new PlayableEmitter();} else if (config.platform === 'wechat') {- const builder = new WeChatBuilder(context);- result = await builder.build();+ emitter = new WeChatEmitter();} else {progress.fail(`Unknown platform: ${config.platform}`);return {@@ -106,6 +115,8 @@ export class BuildService {};}+ const result = await emitter.emit(artifact, context);+const duration = Date.now() - startTime;result.duration = duration;diff --git a/editor/src/builder/PlatformEmitter.ts b/editor/src/builder/PlatformEmitter.tsnew file mode 100644index 000000000..9a83eaf3b--- /dev/null+++ b/editor/src/builder/PlatformEmitter.ts@@ -0,0 +1,26 @@+/**+ * @file PlatformEmitter.ts+ * @brief Platform-specific build output emitters+ */++import type { BuildResult, BuildContext } from './BuildService';+import type { AtlasResult } from './TextureAtlas';+import type { CompiledMaterial } from './MaterialCompiler';+import type { AssetDatabase } from '../asset/AssetDatabase';++// =============================================================================+// Types+// =============================================================================++export interface BuildArtifact {+ scenes: Map<string, Record<string, unknown>>;+ assetPaths: Set<string>;+ atlasResult: AtlasResult;+ packedPaths: Set<string>;+ compiledMaterials: CompiledMaterial[];+ assetLibrary: AssetDatabase;+}++export interface PlatformEmitter {+ emit(artifact: BuildArtifact, context: BuildContext): Promise<BuildResult>;+}diff --git a/editor/src/builder/PlayableBuilder.ts b/editor/src/builder/PlayableBuilder.tsdeleted file mode 100644index d71b924f6..000000000--- a/editor/src/builder/PlayableBuilder.ts+++ /dev/null@@ -1,692 +0,0 @@-/**- * @file PlayableBuilder.ts- * @brief Builder for playable ads (single HTML file output)- *- * Build Pipeline:- * 1. Load pre-built esengine.single.js (WASM module loader)- * 2. Compile user scripts to IIFE format (with esengine bundled)- * 3. Read startup scene JSON- * 4. Compile materials (.esmaterial + .esshader → single JSON)- * 5. Collect and inline assets as base64 data URLs (keyed by UUID)- * 6. Assemble final HTML using scene-driven template- */--import * as esbuild from 'esbuild-wasm/esm/browser';-import type { BuildResult, BuildContext } from './BuildService';-import { BuildProgressReporter } from './BuildProgress';-import { getEditorContext, getEsbuildWasmURL } from '../context/EditorContext';-import { findTsFiles, EDITOR_ONLY_DIRS } from '../scripting/ScriptLoader';-import { BuildAssetCollector, AssetExportConfigService } from './AssetCollector';-import { TextureAtlasPacker, type AtlasResult } from './TextureAtlas';-import { AssetLibrary, isUUID } from '../asset/AssetLibrary';-import { normalizePath, joinPath, getProjectDir, getFileExtension, isAbsolutePath, getParentDir } from '../utils/path';-import { compileMaterials } from './MaterialCompiler';-import type { NativeFS } from '../types/NativeFS';--// =============================================================================-// MIME Types-// =============================================================================--const MIME_TYPES: Record<string, string> = {- png: 'image/png',- jpg: 'image/jpeg',- jpeg: 'image/jpeg',- gif: 'image/gif',- webp: 'image/webp',- svg: 'image/svg+xml',- atlas: 'text/plain',- json: 'application/json',- skel: 'application/octet-stream',-};--// =============================================================================-// HTML Template (Scene-Driven)-// =============================================================================--const HTML_TEMPLATE = `<!DOCTYPE html>-<html lang="en">-<head>-<meta charset="UTF-8">-<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">-<meta name="ad.size" content="width=320,height=480">-<title>Playable</title>-<style>-*{margin:0;padding:0;box-sizing:border-box}-html,body{width:100%;height:100%;overflow:hidden;background:#000}-#canvas{display:block;width:100%;height:100%;touch-action:none}-</style>-</head>-<body>-<canvas id="canvas"></canvas>-<script>-{{WASM_SDK}}-</script>-{{SPINE_SCRIPT}}-{{PHYSICS_SCRIPT}}-<script>-{{GAME_CODE}}-</script>-<script>-var __PA__={{ASSETS_MAP}};-var __SCENE__={{SCENE_DATA}};--function loadImagePixels(dataUrl){- return new Promise(function(resolve,reject){- var img=new Image();- img.onload=function(){- var cv=document.createElement('canvas');- cv.width=img.width;cv.height=img.height;- var ctx=cv.getContext('2d');- ctx.drawImage(img,0,0);- var id=ctx.getImageData(0,0,img.width,img.height);- resolve({width:img.width,height:img.height,pixels:new Uint8Array(id.data.buffer)});- };- img.onerror=reject;- img.src=dataUrl;- });-}--function decodeText(dataUrl){return atob(dataUrl.split(',')[1])}--function decodeBinary(dataUrl){- var b=atob(dataUrl.split(',')[1]);- var a=new Uint8Array(b.length);- for(var i=0;i<b.length;i++)a[i]=b.charCodeAt(i);- return a;-}--(async function(){- var c=document.getElementById('canvas');- function resize(){var dpr=window.devicePixelRatio||1;c.width=window.innerWidth*dpr;c.height=window.innerHeight*dpr}- window.addEventListener('resize',resize);- resize();-- var Module=await ESEngineModule({canvas:c,print:function(t){console.log(t)},printErr:function(t){console.error(t)}});- var es=window.esengine;- if(!es||!es.createWebApp){console.error('esengine not found');return}-- var app=es.createWebApp(Module);- if(typeof __PA__!=='undefined')es.registerEmbeddedAssets(app,__PA__);- es.flushPendingSystems(app);-- var spineModule=null;- if(typeof ESSpineModule!=='undefined'){- try{- spineModule=await ESSpineModule({- instantiateWasm:function(imports,cb){- var b=atob(__SPINE_WASM_B64__);- var a=new Uint8Array(b.length);- for(var i=0;i<b.length;i++)a[i]=b.charCodeAt(i);- WebAssembly.instantiate(a,imports).then(function(r){cb(r.instance,r.module)});- return {};- }- });- }catch(e){console.warn('Spine module not available:',e)}- }-- var physicsModule=null;- if(typeof ESPhysicsModule!=='undefined'){- try{- physicsModule=await ESPhysicsModule({- instantiateWasm:function(imports,cb){- var b=atob(__PHYSICS_WASM_B64__);- var a=new Uint8Array(b.length);- for(var i=0;i<b.length;i++)a[i]=b.charCodeAt(i);- WebAssembly.instantiate(a,imports).then(function(r){cb(r.instance,r.module)});- return {};- }- });- }catch(e){console.warn('Physics module not available:',e)}- }-- var provider={- loadPixels:function(ref){var d=__PA__[ref];if(!d)throw new Error('Asset not found: '+ref);return loadImagePixels(d)},- readText:function(ref){var d=__PA__[ref];if(!d)throw new Error('Asset not found: '+ref);return decodeText(d)},- readBinary:function(ref){var d=__PA__[ref];if(!d)throw new Error('Asset not found: '+ref);return decodeBinary(d)},- resolvePath:function(ref){return ref}- };-- await es.loadRuntimeScene(app,Module,__SCENE__,provider,spineModule,physicsModule,{{PHYSICS_CONFIG}});-- var screenAspect=c.width/c.height;- es.updateCameraAspectRatio(app.world,screenAspect);-- app.run();-})();-</script>-</body>-</html>`;--// =============================================================================-// PlayableBuilder-// =============================================================================--export class PlayableBuilder {- constructor(context: BuildContext) {- this.context_ = context;- this.fs_ = getEditorContext().fs ?? null;- this.projectDir_ = getProjectDir(context.projectPath);- this.progress_ = context.progress || new BuildProgressReporter();- this.assetLibrary_ = new AssetLibrary();- }-- // =========================================================================- // Public Methods- // =========================================================================-- async build(): Promise<BuildResult> {- if (!this.fs_) {- return { success: false, error: 'Native file system not available' };- }-- const settings = this.context_.config.playableSettings;- if (!settings) {- return { success: false, error: 'Playable settings not configured' };- }-- const startupScene = settings.startupScene || this.context_.config.scenes[0];- if (!startupScene) {- return { success: false, error: 'No startup scene configured. Add a scene to the build or set a startup scene.' };- }-- this.progress_.setPhase('preparing');- this.progress_.log('info', 'Starting Playable build...');-- try {- await this.assetLibrary_.initialize(this.projectDir_, this.fs_);- this.progress_.log('info', 'Asset library initialized');-- // 1. Load SDK- this.progress_.setCurrentTask('Loading SDK...', 0);- const wasmSdk = await this.loadSdk();- if (!wasmSdk) {- return {- success: false,- error: "SDK not found. Please run 'scripts/build-web-single.bat' first.",- };- }- this.progress_.log('info', `SDK loaded: ${wasmSdk.length} bytes`);-- // 2. Compile user scripts- this.progress_.setPhase('compiling');- this.progress_.setCurrentTask('Compiling scripts...', 0);-- const gameCode = await this.compileUserScripts();- this.progress_.log('info', `Scripts compiled: ${gameCode.length} bytes`);-- // 3. Read startup scene- this.progress_.setCurrentTask('Loading scene...', 50);- const scenePath = this.resolveScenePath(startupScene);- const sceneContent = await this.fs_.readFile(scenePath);- if (!sceneContent) {- return { success: false, error: `Startup scene not found: ${scenePath}` };- }- this.progress_.log('info', `Scene loaded: ${scenePath}`);-- // 4. Pack texture atlas- this.progress_.setPhase('processing_assets');- this.progress_.setCurrentTask('Packing texture atlas...', 0);- const { atlasResult, packedPaths } = await this.packTextureAtlas();- if (atlasResult.pages.length > 0) {- this.progress_.log('info', `Packed ${atlasResult.frameMap.size} textures into ${atlasResult.pages.length} atlas page(s)`);- }-- // 5. Rewrite scene data with atlas UVs, then resolve all UUID refs to paths- const sceneData = JSON.parse(sceneContent);- const packer = new TextureAtlasPacker(this.fs_!, this.projectDir_, this.assetLibrary_);- packer.rewriteSceneData(sceneData, atlasResult, '');- this.resolveSceneUUIDs(sceneData);- const rewrittenScene = JSON.stringify(sceneData);-- // 6. Compile materials- this.progress_.setCurrentTask('Compiling materials...', 20);- const compiledMaterials = await this.compileMaterials_();- this.progress_.log('info', `Compiled ${compiledMaterials.size} material(s)`);-- // 7. Load spine module if needed- let spineJsSource = '';- let spineWasmBase64 = '';- const spineVersion = this.context_.spineVersion;- if (spineVersion && this.fs_?.getSpineJs) {- this.progress_.setCurrentTask('Loading spine module...', 25);- const spineJs = await this.fs_.getSpineJs(spineVersion);- const spineWasm = await this.fs_.getSpineWasm(spineVersion);- if (spineJs && spineWasm.length > 0) {- spineJsSource = spineJs;- spineWasmBase64 = this.arrayBufferToBase64(spineWasm);- this.progress_.log('info', `Spine ${spineVersion} module loaded`);- }- }-- // 7.5. Load physics module if needed- let physicsJsSource = '';- let physicsWasmBase64 = '';- if (this.context_.enablePhysics && this.fs_?.getPhysicsJs) {- this.progress_.setCurrentTask('Loading physics module...', 27);- const physicsJs = await this.fs_.getPhysicsJs();- const physicsWasm = await this.fs_.getPhysicsWasm();- if (physicsJs && physicsWasm.length > 0) {- physicsJsSource = physicsJs;- physicsWasmBase64 = this.arrayBufferToBase64(physicsWasm);- this.progress_.log('info', 'Physics module loaded');- }- }-- // 8. Collect assets (keyed by UUID, excluding packed textures, adding atlas pages)- this.progress_.setCurrentTask('Collecting assets...', 30);- const assets = await this.collectAssets(packedPaths, compiledMaterials);- for (let i = 0; i < atlasResult.pages.length; i++) {- const base64 = this.arrayBufferToBase64(atlasResult.pages[i].imageData);- assets.set(`atlas_${i}.png`, `data:image/png;base64,${base64}`);- }- this.progress_.log('info', `Collected ${assets.size} assets`);-- // 9. Assemble HTML- this.progress_.setPhase('assembling');- this.progress_.setCurrentTask('Assembling HTML...', 0);- const html = this.assembleHTML(wasmSdk, gameCode, rewrittenScene, assets, spineJsSource, spineWasmBase64, physicsJsSource, physicsWasmBase64);- this.progress_.log('info', `HTML assembled: ${html.length} bytes`);-- // 10. Write output- this.progress_.setPhase('writing');- this.progress_.setCurrentTask('Writing output...', 0);- const outputPath = this.resolveOutputPath(settings.outputPath);- const outputDir = getParentDir(outputPath);-- await this.fs_.createDirectory(outputDir);- const success = await this.fs_.writeFile(outputPath, html);-- if (success) {- this.progress_.log('info', `Build successful: ${outputPath}`);- return {- success: true,- outputPath,- outputSize: new TextEncoder().encode(html).length,- };- } else {- return { success: false, error: 'Failed to write output file' };- }- } catch (err) {- console.error('[PlayableBuilder] Build error:', err);- this.progress_.fail(String(err));- return { success: false, error: String(err) };- }- }-- // =========================================================================- // Private Methods- // =========================================================================-- private async loadSdk(): Promise<string | null> {- try {- if (this.fs_?.getEngineSingleJs) {- return await this.fs_.getEngineSingleJs();- }- const response = await fetch('/wasm/esengine.single.js');- if (!response.ok) return null;- return await response.text();- } catch {- return null;- }- }-- private resolveScenePath(scenePath: string): string {- if (isAbsolutePath(scenePath)) {- return normalizePath(scenePath);- }- return joinPath(this.projectDir_, scenePath);- }-- private resolveOutputPath(outputPath: string): string {- if (isAbsolutePath(outputPath)) {- return normalizePath(outputPath);- }- return joinPath(this.projectDir_, outputPath);- }-- private async compileUserScripts(): Promise<string> {- const scriptsPath = joinPath(this.projectDir_, 'src');- const hasSrcDir = await this.fs_!.exists(scriptsPath);-- let imports = '';- if (hasSrcDir) {- const scripts = await findTsFiles(this.fs_!, scriptsPath, EDITOR_ONLY_DIRS);- imports = scripts.map(p => `import "${p}";`).join('\n');- }-- const entryContent = `-import * as esengine from 'esengine';-(window as any).esengine = esengine;-${imports}-`;-- console.log('[PlayableBuilder] Compiling scripts...');-- const settings = this.context_.config.playableSettings!;- const defines: Record<string, string> = {- 'process.env.EDITOR': 'false',- };- for (const def of this.context_.config.defines) {- defines[`process.env.${def}`] = 'true';- }-- await this.initializeEsbuild();-- const result = await esbuild.build({- stdin: {- contents: entryContent,- loader: 'ts',- resolveDir: hasSrcDir ? scriptsPath : this.projectDir_,- },- bundle: true,- format: 'iife',- write: false,- platform: 'browser',- target: 'es2020',- treeShaking: false,- minify: settings.minifyCode,- define: defines,- plugins: [this.createVirtualFsPlugin()],- });-- const output = result.outputFiles?.[0]?.text;- if (!output) {- throw new Error('esbuild produced no output');- }- return output;- }-- private async initializeEsbuild(): Promise<void> {- try {- await esbuild.initialize({- wasmURL: getEsbuildWasmURL(),- });- } catch (err) {- if (!String(err).includes('Cannot call "initialize" more than once')) {- throw err;- }- }- }-- private createVirtualFsPlugin(): esbuild.Plugin {- const fs = this.fs_!;- const projectDir = this.projectDir_;-- return {- name: 'virtual-fs',- setup(build) {- build.onResolve({ filter: /.*/ }, async (args) => {- if (args.kind === 'entry-point') {- return { path: args.path, namespace: 'virtual' };- }-- if (args.path === 'esengine') {- return { path: 'esengine', namespace: 'esengine-sdk' };- }- if (args.path === 'esengine/wasm') {- return { path: 'esengine/wasm', namespace: 'esengine-sdk' };- }-- let resolvedPath = args.path;-- if (isAbsolutePath(args.path)) {- resolvedPath = normalizePath(args.path);- } else if (args.path.startsWith('.')) {- const baseDir = args.importer ? getParentDir(args.importer) : args.resolveDir;- resolvedPath = joinPath(baseDir, args.path);- } else {- const pkgPath = joinPath(projectDir, 'node_modules', args.path, 'package.json');- const pkgContent = await fs.readFile(pkgPath);- if (pkgContent) {- try {- const pkg = JSON.parse(pkgContent);- let entry = pkg.module || pkg.main || 'index.js';- if (pkg.exports) {- const root = pkg.exports['.'];- if (typeof root === 'string') {- entry = root;- } else if (root?.import) {- entry = root.import;- } else if (root?.default) {- entry = root.default;- }- }- resolvedPath = joinPath(projectDir, 'node_modules', args.path, entry);- } catch {- throw new Error(`Failed to parse package.json for: ${args.path}`);- }- } else {- throw new Error(`Module not found: ${args.path}. Please install it with npm.`);- }- }-- if (!resolvedPath.endsWith('.ts') && !resolvedPath.endsWith('.js')) {- if (await fs.exists(resolvedPath + '.ts')) {- resolvedPath += '.ts';- } else if (await fs.exists(resolvedPath + '.js')) {- resolvedPath += '.js';- } else if (await fs.exists(joinPath(resolvedPath, 'index.ts'))) {- resolvedPath = joinPath(resolvedPath, 'index.ts');- } else if (await fs.exists(joinPath(resolvedPath, 'index.js'))) {- resolvedPath = joinPath(resolvedPath, 'index.js');- } else {- resolvedPath += '.ts';- }- }-- return { path: resolvedPath, namespace: 'virtual' };- });-- build.onLoad({ filter: /.*/, namespace: 'esengine-sdk' }, async (args) => {- if (args.path === 'esengine') {- return { contents: await fs.getSdkEsmJs(), loader: 'js' };- }- if (args.path === 'esengine/wasm') {- return { contents: await fs.getSdkWasmJs(), loader: 'js' };- }- return { contents: '', loader: 'js' };- });-- build.onLoad({ filter: /.*/, namespace: 'virtual' }, async (args) => {- const content = await fs.readFile(args.path);- if (content === null) {- return { contents: '', loader: 'ts' };- }- const loader = args.path.endsWith('.ts') ? 'ts' : 'js';- return { contents: content, loader };- });- },- };- }--- private async compileMaterials_(): Promise<Map<string, { uuid: string; compiledJson: string }>> {- const configService = new AssetExportConfigService(this.projectDir_, this.fs_!);- const exportConfig = await configService.load();- const compiled = await compileMaterials(this.fs_!, this.projectDir_, this.assetLibrary_, this.context_.config, exportConfig);-- const result = new Map<string, { uuid: string; compiledJson: string }>();- for (const mat of compiled) {- result.set(mat.relativePath, {- uuid: mat.uuid,- compiledJson: mat.json,- });- }- return result;- }-- private async packTextureAtlas(): Promise<{ atlasResult: AtlasResult; packedPaths: Set<string> }> {- const configService = new AssetExportConfigService(this.projectDir_, this.fs_!);- const exportConfig = await configService.load();-- const collector = new BuildAssetCollector(this.fs_!, this.projectDir_, this.assetLibrary_);- const assetPaths = await collector.collect(this.context_.config, exportConfig);-- const imagePaths = [...assetPaths].filter(p => {- const ext = p.split('.').pop()?.toLowerCase() ?? '';- return ext === 'png' || ext === 'jpg' || ext === 'jpeg';- });-- const sceneDataList: Array<{ name: string; data: Record<string, unknown> }> = [];- for (const scenePath of this.context_.config.scenes) {- const fullPath = this.resolveScenePath(scenePath);- const content = await this.fs_!.readFile(fullPath);- if (content) {- const name = scenePath.replace(/.*\//, '').replace('.esscene', '');- sceneDataList.push({ name, data: JSON.parse(content) });- }- }-- const packer = new TextureAtlasPacker(this.fs_!, this.projectDir_, this.assetLibrary_);- const atlasResult = await packer.pack(imagePaths, sceneDataList, 2048, [...assetPaths]);-- const packedPaths = new Set<string>(atlasResult.frameMap.keys());- return { atlasResult, packedPaths };- }-- private async collectAssets(- packedPaths: Set<string>,- compiledMaterials: Map<string, { uuid: string; compiledJson: string }>- ): Promise<Map<string, string>> {- const assets = new Map<string, string>();-- const configService = new AssetExportConfigService(this.projectDir_, this.fs_!);- const exportConfig = await configService.load();-- const collector = new BuildAssetCollector(this.fs_!, this.projectDir_, this.assetLibrary_);- const assetPaths = await collector.collect(this.context_.config, exportConfig);-- const compiledMaterialPaths = new Set<string>(compiledMaterials.keys());-- for (const relativePath of assetPaths) {- if (packedPaths.has(relativePath)) continue;- if (relativePath.endsWith('.esshader')) continue;-- if (compiledMaterialPaths.has(relativePath)) {- const compiled = compiledMaterials.get(relativePath)!;- const base64 = btoa(compiled.compiledJson);- assets.set(relativePath, `data:application/json;base64,${base64}`);- continue;- }-- const ext = getFileExtension(relativePath);- const mimeType = MIME_TYPES[ext];- if (!mimeType) continue;-- const fullPath = joinPath(this.projectDir_, relativePath);- const binary = await this.fs_!.readBinaryFile(fullPath);- if (binary) {- const base64 = this.arrayBufferToBase64(binary);- assets.set(relativePath, `data:${mimeType};base64,${base64}`);- }- }-- return assets;- }-- private resolveSceneUUIDs(sceneData: Record<string, unknown>): void {- const entities = sceneData.entities as Array<{- components: Array<{ type: string; data: Record<string, unknown> }>;- }> | undefined;- if (!entities) return;-- for (const entity of entities) {- for (const comp of entity.components || []) {- if (comp.type === 'Sprite' && comp.data) {- if (typeof comp.data.texture === 'string' && isUUID(comp.data.texture)) {- const path = this.assetLibrary_.getPath(comp.data.texture);- if (path) comp.data.texture = path;- }- if (typeof comp.data.material === 'string' && isUUID(comp.data.material)) {- const path = this.assetLibrary_.getPath(comp.data.material);- if (path) comp.data.material = path;- }- }- if (comp.type === 'SpineAnimation' && comp.data) {- if (typeof comp.data.skeletonPath === 'string' && isUUID(comp.data.skeletonPath)) {- const path = this.assetLibrary_.getPath(comp.data.skeletonPath);- if (path) comp.data.skeletonPath = path;- }- if (typeof comp.data.atlasPath === 'string' && isUUID(comp.data.atlasPath)) {- const path = this.assetLibrary_.getPath(comp.data.atlasPath);- if (path) comp.data.atlasPath = path;- }- if (typeof comp.data.material === 'string' && isUUID(comp.data.material)) {- const path = this.assetLibrary_.getPath(comp.data.material);- if (path) comp.data.material = path;- }- }- }- }-- const textureMetadata = sceneData.textureMetadata as Record<string, unknown> | undefined;- if (textureMetadata) {- const resolved: Record<string, unknown> = {};- for (const [key, value] of Object.entries(textureMetadata)) {- if (isUUID(key)) {- const path = this.assetLibrary_.getPath(key);- resolved[path ?? key] = value;- } else {- resolved[key] = value;- }- }- sceneData.textureMetadata = resolved;- }- }-- private assembleHTML(- wasmSdk: string, gameCode: string, sceneData: string,- assets: Map<string, string>,- spineJs?: string, spineWasmBase64?: string,- physicsJs?: string, physicsWasmBase64?: string,- ): string {- const entries: string[] = [];- for (const [path, dataUrl] of assets) {- entries.push(`"${path}":"${dataUrl}"`);- }-- let spineScript = '';- if (spineJs && spineWasmBase64) {- spineScript = `<script>\nvar __SPINE_WASM_B64__="${spineWasmBase64}";\n${spineJs}\n</script>`;- }-- let physicsScript = '';- if (physicsJs && physicsWasmBase64) {- physicsScript = `<script>\nvar __PHYSICS_WASM_B64__="${physicsWasmBase64}";\n${physicsJs}\n</script>`;- }-- const physicsConfig = JSON.stringify({- gravity: this.context_.physicsGravity ?? { x: 0, y: -9.81 },- fixedTimestep: this.context_.physicsFixedTimestep ?? 1 / 60,- subStepCount: this.context_.physicsSubStepCount ?? 4,- });-- return HTML_TEMPLATE- .replace('{{WASM_SDK}}', () => wasmSdk)- .replace('{{SPINE_SCRIPT}}', () => spineScript)- .replace('{{PHYSICS_SCRIPT}}', () => physicsScript)- .replace('{{GAME_CODE}}', () => gameCode)- .replace('{{ASSETS_MAP}}', () => `{${entries.join(',')}}`)- .replace('{{SCENE_DATA}}', () => sceneData)- .replace('{{PHYSICS_CONFIG}}', () => physicsConfig);- }-- private arrayBufferToBase64(buffer: Uint8Array): string {- let binary = '';- const bytes = new Uint8Array(buffer);- for (let i = 0; i < bytes.byteLength; i++) {- binary += String.fromCharCode(bytes[i]);- }- return btoa(binary);- }-- // =========================================================================- // Member Variables- // =========================================================================-- private context_: BuildContext;- private fs_: NativeFS | null;- private projectDir_: string;- private progress_: BuildProgressReporter;- private assetLibrary_: AssetLibrary;-}diff --git a/editor/src/builder/PlayableEmitter.ts b/editor/src/builder/PlayableEmitter.tsnew file mode 100644index 000000000..8c6630f26--- /dev/null+++ b/editor/src/builder/PlayableEmitter.ts@@ -0,0 +1,484 @@+/**+ * @file PlayableEmitter.ts+ * @brief Emitter that produces a single HTML file for playable ads+ */++import * as esbuild from 'esbuild-wasm/esm/browser';+import type { PlatformEmitter, BuildArtifact } from './PlatformEmitter';+import type { BuildResult, BuildContext } from './BuildService';+import { BuildProgressReporter } from './BuildProgress';+import { getEditorContext } from '../context/EditorContext';+import { findTsFiles, EDITOR_ONLY_DIRS } from '../scripting/ScriptLoader';+import { joinPath, getFileExtension, isAbsolutePath, getParentDir, normalizePath, getProjectDir } from '../utils/path';+import { isUUID } from '../asset/AssetLibrary';+import { initializeEsbuild, createBuildVirtualFsPlugin } from './ArtifactBuilder';+import type { NativeFS } from '../types/NativeFS';++// =============================================================================+// MIME Types+// =============================================================================++const MIME_TYPES: Record<string, string> = {+ png: 'image/png',+ jpg: 'image/jpeg',+ jpeg: 'image/jpeg',+ gif: 'image/gif',+ webp: 'image/webp',+ svg: 'image/svg+xml',+ atlas: 'text/plain',+ json: 'application/json',+ skel: 'application/octet-stream',+};++// =============================================================================+// PlayableEmitter+// =============================================================================++export class PlayableEmitter implements PlatformEmitter {+ async emit(artifact: BuildArtifact, context: BuildContext): Promise<BuildResult> {+ const fs = getEditorContext().fs;+ if (!fs) {+ return { success: false, error: 'Native file system not available' };+ }++ const settings = context.config.playableSettings;+ if (!settings) {+ return { success: false, error: 'Playable settings not configured' };+ }++ const startupScene = settings.startupScene || context.config.scenes[0];+ if (!startupScene) {+ return { success: false, error: 'No startup scene configured. Add a scene to the build or set a startup scene.' };+ }++ const progress = context.progress || new BuildProgressReporter();+ const projectDir = getProjectDir(context.projectPath);++ try {+ // 1. Load SDK+ progress.setCurrentTask('Loading SDK...', 0);+ const wasmSdk = await this.loadSdk(fs);+ if (!wasmSdk) {+ return { success: false, error: "SDK not found. Please run 'scripts/build-web-single.bat' first." };+ }+ progress.log('info', `SDK loaded: ${wasmSdk.length} bytes`);++ // 2. Compile user scripts+ progress.setPhase('compiling');+ progress.setCurrentTask('Compiling scripts...', 0);+ const gameCode = await this.compileUserScripts(fs, projectDir, context);+ progress.log('info', `Scripts compiled: ${gameCode.length} bytes`);++ // 3. Process startup scene (resolve UUIDs)+ const sceneName = startupScene.replace(/.*\//, '').replace('.esscene', '');+ const sceneData = artifact.scenes.get(sceneName);+ if (!sceneData) {+ return { success: false, error: `Startup scene not found: ${startupScene}` };+ }+ const sceneDataCopy = JSON.parse(JSON.stringify(sceneData));+ this.resolveSceneUUIDs(sceneDataCopy, artifact);+ const rewrittenScene = JSON.stringify(sceneDataCopy);++ // 4. Load spine module if needed+ progress.setCurrentTask('Loading modules...', 25);+ let spineJsSource = '';+ let spineWasmBase64 = '';+ if (context.spineVersion && fs.getSpineJs) {+ const spineJs = await fs.getSpineJs(context.spineVersion);+ const spineWasm = await fs.getSpineWasm(context.spineVersion);+ if (spineJs && spineWasm.length > 0) {+ spineJsSource = spineJs;+ spineWasmBase64 = this.arrayBufferToBase64(spineWasm);+ progress.log('info', `Spine ${context.spineVersion} module loaded`);+ }+ }++ // 5. Load physics module if needed+ let physicsJsSource = '';+ let physicsWasmBase64 = '';+ if (context.enablePhysics && fs.getPhysicsJs) {+ progress.setCurrentTask('Loading physics module...', 27);+ const physicsJs = await fs.getPhysicsJs();+ const physicsWasm = await fs.getPhysicsWasm();+ if (physicsJs && physicsWasm.length > 0) {+ physicsJsSource = physicsJs;+ physicsWasmBase64 = this.arrayBufferToBase64(physicsWasm);+ progress.log('info', 'Physics module loaded');+ }+ }++ // 6. Collect inline assets+ progress.setPhase('assembling');+ progress.setCurrentTask('Collecting assets...', 0);+ const assets = await this.collectInlineAssets(fs, projectDir, artifact);+ for (let i = 0; i < artifact.atlasResult.pages.length; i++) {+ const base64 = this.arrayBufferToBase64(artifact.atlasResult.pages[i].imageData);+ assets.set(`atlas_${i}.png`, `data:image/png;base64,${base64}`);+ }+ progress.log('info', `Collected ${assets.size} assets`);++ // 7. Assemble HTML+ progress.setCurrentTask('Assembling HTML...', 50);+ const html = this.assembleHTML(+ wasmSdk, gameCode, rewrittenScene, assets,+ spineJsSource, spineWasmBase64,+ physicsJsSource, physicsWasmBase64,+ context+ );+ progress.log('info', `HTML assembled: ${html.length} bytes`);++ // 8. Write output+ progress.setPhase('writing');+ progress.setCurrentTask('Writing output...', 0);+ const outputPath = isAbsolutePath(settings.outputPath)+ ? normalizePath(settings.outputPath)+ : joinPath(projectDir, settings.outputPath);+ const outputDir = getParentDir(outputPath);++ await fs.createDirectory(outputDir);+ const success = await fs.writeFile(outputPath, html);++ if (success) {+ progress.log('info', `Build successful: ${outputPath}`);+ return {+ success: true,+ outputPath,+ outputSize: new TextEncoder().encode(html).length,+ };+ }+ return { success: false, error: 'Failed to write output file' };+ } catch (err) {+ console.error('[PlayableEmitter] Build error:', err);+ progress.fail(String(err));+ return { success: false, error: String(err) };+ }+ }++ // =========================================================================+ // Private Methods+ // =========================================================================++ private async loadSdk(fs: NativeFS): Promise<string | null> {+ try {+ if (fs.getEngineSingleJs) {+ return await fs.getEngineSingleJs();+ }+ const response = await fetch('/wasm/esengine.single.js');+ if (!response.ok) return null;+ return await response.text();+ } catch {+ return null;+ }+ }++ private async compileUserScripts(fs: NativeFS, projectDir: string, context: BuildContext): Promise<string> {+ const scriptsPath = joinPath(projectDir, 'src');+ const hasSrcDir = await fs.exists(scriptsPath);++ let imports = '';+ if (hasSrcDir) {+ const scripts = await findTsFiles(fs, scriptsPath, EDITOR_ONLY_DIRS);+ imports = scripts.map(p => `import "${p}";`).join('\n');+ }++ const entryContent = `+import * as esengine from 'esengine';+(window as any).esengine = esengine;+${imports}+`;++ const settings = context.config.playableSettings!;+ const defines: Record<string, string> = {+ 'process.env.EDITOR': 'false',+ };+ for (const def of context.config.defines) {+ defines[`process.env.${def}`] = 'true';+ }++ await initializeEsbuild();++ const plugin = createBuildVirtualFsPlugin(fs, projectDir, async (path) => {+ if (path === 'esengine') {+ return { contents: await fs.getSdkEsmJs(), loader: 'js' as esbuild.Loader };+ }+ if (path === 'esengine/wasm') {+ return { contents: await fs.getSdkWasmJs(), loader: 'js' as esbuild.Loader };+ }+ return { contents: '', loader: 'js' as esbuild.Loader };+ });++ const result = await esbuild.build({+ stdin: {+ contents: entryContent,+ loader: 'ts',+ resolveDir: hasSrcDir ? scriptsPath : projectDir,+ },+ bundle: true,+ format: 'iife',+ write: false,+ platform: 'browser',+ target: 'es2020',+ treeShaking: false,+ minify: settings.minifyCode,+ define: defines,+ plugins: [plugin],+ });++ const output = result.outputFiles?.[0]?.text;+ if (!output) {+ throw new Error('esbuild produced no output');+ }+ return output;+ }++ private resolveSceneUUIDs(sceneData: Record<string, unknown>, artifact: BuildArtifact): void {+ const entities = sceneData.entities as Array<{+ components: Array<{ type: string; data: Record<string, unknown> }>;+ }> | undefined;+ if (!entities) return;++ for (const entity of entities) {+ for (const comp of entity.components || []) {+ if (comp.type === 'Sprite' && comp.data) {+ if (typeof comp.data.texture === 'string' && isUUID(comp.data.texture)) {+ const path = artifact.assetLibrary.getPath(comp.data.texture);+ if (path) comp.data.texture = path;+ }+ if (typeof comp.data.material === 'string' && isUUID(comp.data.material)) {+ const path = artifact.assetLibrary.getPath(comp.data.material);+ if (path) comp.data.material = path;+ }+ }+ if (comp.type === 'SpineAnimation' && comp.data) {+ if (typeof comp.data.skeletonPath === 'string' && isUUID(comp.data.skeletonPath)) {+ const path = artifact.assetLibrary.getPath(comp.data.skeletonPath);+ if (path) comp.data.skeletonPath = path;+ }+ if (typeof comp.data.atlasPath === 'string' && isUUID(comp.data.atlasPath)) {+ const path = artifact.assetLibrary.getPath(comp.data.atlasPath);+ if (path) comp.data.atlasPath = path;+ }+ if (typeof comp.data.material === 'string' && isUUID(comp.data.material)) {+ const path = artifact.assetLibrary.getPath(comp.data.material);+ if (path) comp.data.material = path;+ }+ }+ }+ }++ const textureMetadata = sceneData.textureMetadata as Record<string, unknown> | undefined;+ if (textureMetadata) {+ const resolved: Record<string, unknown> = {};+ for (const [key, value] of Object.entries(textureMetadata)) {+ if (isUUID(key)) {+ const path = artifact.assetLibrary.getPath(key);+ resolved[path ?? key] = value;+ } else {+ resolved[key] = value;+ }+ }+ sceneData.textureMetadata = resolved;+ }+ }++ private async collectInlineAssets(+ fs: NativeFS,+ projectDir: string,+ artifact: BuildArtifact+ ): Promise<Map<string, string>> {+ const assets = new Map<string, string>();+ const compiledMaterialPaths = new Set(artifact.compiledMaterials.map(m => m.relativePath));++ for (const relativePath of artifact.assetPaths) {+ if (artifact.packedPaths.has(relativePath)) continue;+ if (relativePath.endsWith('.esshader')) continue;++ if (compiledMaterialPaths.has(relativePath)) {+ const mat = artifact.compiledMaterials.find(m => m.relativePath === relativePath);+ if (mat) {+ const base64 = btoa(mat.json);+ assets.set(relativePath, `data:application/json;base64,${base64}`);+ }+ continue;+ }++ const ext = getFileExtension(relativePath);+ const mimeType = MIME_TYPES[ext];+ if (!mimeType) continue;++ const fullPath = joinPath(projectDir, relativePath);+ const binary = await fs.readBinaryFile(fullPath);+ if (binary) {+ const base64 = this.arrayBufferToBase64(binary);+ assets.set(relativePath, `data:${mimeType};base64,${base64}`);+ }+ }++ return assets;+ }++ private assembleHTML(+ wasmSdk: string, gameCode: string, sceneData: string,+ assets: Map<string, string>,+ spineJs: string, spineWasmBase64: string,+ physicsJs: string, physicsWasmBase64: string,+ context: BuildContext+ ): string {+ const entries: string[] = [];+ for (const [path, dataUrl] of assets) {+ entries.push(`"${path}":"${dataUrl}"`);+ }++ let spineScript = '';+ if (spineJs && spineWasmBase64) {+ spineScript = `<script>\nvar __SPINE_WASM_B64__="${spineWasmBase64}";\n${spineJs}\n</script>`;+ }++ let physicsScript = '';+ if (physicsJs && physicsWasmBase64) {+ physicsScript = `<script>\nvar __PHYSICS_WASM_B64__="${physicsWasmBase64}";\n${physicsJs}\n</script>`;+ }++ const physicsConfig = JSON.stringify({+ gravity: context.physicsGravity ?? { x: 0, y: -9.81 },+ fixedTimestep: context.physicsFixedTimestep ?? 1 / 60,+ subStepCount: context.physicsSubStepCount ?? 4,+ });++ return HTML_TEMPLATE+ .replace('{{WASM_SDK}}', () => wasmSdk)+ .replace('{{SPINE_SCRIPT}}', () => spineScript)+ .replace('{{PHYSICS_SCRIPT}}', () => physicsScript)+ .replace('{{GAME_CODE}}', () => gameCode)+ .replace('{{ASSETS_MAP}}', () => `{${entries.join(',')}}`)+ .replace('{{SCENE_DATA}}', () => sceneData)+ .replace('{{PHYSICS_CONFIG}}', () => physicsConfig);+ }++ private arrayBufferToBase64(buffer: Uint8Array): string {+ let binary = '';+ const bytes = new Uint8Array(buffer);+ for (let i = 0; i < bytes.byteLength; i++) {+ binary += String.fromCharCode(bytes[i]);+ }+ return btoa(binary);+ }+}++// =============================================================================+// HTML Template+// =============================================================================++const HTML_TEMPLATE = `<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="UTF-8">+<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">+<meta name="ad.size" content="width=320,height=480">+<title>Playable</title>+<style>+*{margin:0;padding:0;box-sizing:border-box}+html,body{width:100%;height:100%;overflow:hidden;background:#000}+#canvas{display:block;width:100%;height:100%;touch-action:none}+</style>+</head>+<body>+<canvas id="canvas"></canvas>+<script>+{{WASM_SDK}}+</script>+{{SPINE_SCRIPT}}+{{PHYSICS_SCRIPT}}+<script>+{{GAME_CODE}}+</script>+<script>+var __PA__={{ASSETS_MAP}};+var __SCENE__={{SCENE_DATA}};++function loadImagePixels(dataUrl){+ return new Promise(function(resolve,reject){+ var img=new Image();+ img.onload=function(){+ var cv=document.createElement('canvas');+ cv.width=img.width;cv.height=img.height;+ var ctx=cv.getContext('2d');+ ctx.drawImage(img,0,0);+ var id=ctx.getImageData(0,0,img.width,img.height);+ resolve({width:img.width,height:img.height,pixels:new Uint8Array(id.data.buffer)});+ };+ img.onerror=reject;+ img.src=dataUrl;+ });+}++function decodeText(dataUrl){return atob(dataUrl.split(',')[1])}++function decodeBinary(dataUrl){+ var b=atob(dataUrl.split(',')[1]);+ var a=new Uint8Array(b.length);+ for(var i=0;i<b.length;i++)a[i]=b.charCodeAt(i);+ return a;+}++(async function(){+ var c=document.getElementById('canvas');+ function resize(){var dpr=window.devicePixelRatio||1;c.width=window.innerWidth*dpr;c.height=window.innerHeight*dpr}+ window.addEventListener('resize',resize);+ resize();++ var Module=await ESEngineModule({canvas:c,print:function(t){console.log(t)},printErr:function(t){console.error(t)}});+ var es=window.esengine;+ if(!es||!es.createWebApp){console.error('esengine not found');return}++ var app=es.createWebApp(Module);+ if(typeof __PA__!=='undefined')es.registerEmbeddedAssets(app,__PA__);+ es.flushPendingSystems(app);++ var spineModule=null;+ if(typeof ESSpineModule!=='undefined'){+ try{+ spineModule=await ESSpineModule({+ instantiateWasm:function(imports,cb){+ var b=atob(__SPINE_WASM_B64__);+ var a=new Uint8Array(b.length);+ for(var i=0;i<b.length;i++)a[i]=b.charCodeAt(i);+ WebAssembly.instantiate(a,imports).then(function(r){cb(r.instance,r.module)});+ return {};+ }+ });+ }catch(e){console.warn('Spine module not available:',e)}+ }++ var physicsModule=null;+ if(typeof ESPhysicsModule!=='undefined'){+ try{+ physicsModule=await ESPhysicsModule({+ instantiateWasm:function(imports,cb){+ var b=atob(__PHYSICS_WASM_B64__);+ var a=new Uint8Array(b.length);+ for(var i=0;i<b.length;i++)a[i]=b.charCodeAt(i);+ WebAssembly.instantiate(a,imports).then(function(r){cb(r.instance,r.module)});+ return {};+ }+ });+ }catch(e){console.warn('Physics module not available:',e)}+ }++ var provider={+ loadPixels:function(ref){var d=__PA__[ref];if(!d)throw new Error('Asset not found: '+ref);return loadImagePixels(d)},+ readText:function(ref){var d=__PA__[ref];if(!d)throw new Error('Asset not found: '+ref);return decodeText(d)},+ readBinary:function(ref){var d=__PA__[ref];if(!d)throw new Error('Asset not found: '+ref);return decodeBinary(d)},+ resolvePath:function(ref){return ref}+ };++ await es.loadRuntimeScene(app,Module,__SCENE__,provider,spineModule,physicsModule,{{PHYSICS_CONFIG}});++ var screenAspect=c.width/c.height;+ es.updateCameraAspectRatio(app.world,screenAspect);++ app.run();+})();+</script>+</body>+</html>`;diff --git a/editor/src/builder/WeChatBuilder.ts b/editor/src/builder/WeChatBuilder.tsdeleted file mode 100644index a46e06074..000000000--- a/editor/src/builder/WeChatBuilder.ts+++ /dev/null@@ -1,699 +0,0 @@-/**- * @file WeChatBuilder.ts- * @brief Builder for WeChat Mini Game platform- */--import * as esbuild from 'esbuild-wasm/esm/browser';-import type { BuildResult, BuildContext } from './BuildService';-import { BuildProgressReporter } from './BuildProgress';-import { BuildCache } from './BuildCache';-import { getEditorContext, getEsbuildWasmURL } from '../context/EditorContext';-import { findTsFiles, EDITOR_ONLY_DIRS } from '../scripting/ScriptLoader';-import { BuildAssetCollector, AssetExportConfigService } from './AssetCollector';-import { TextureAtlasPacker, type AtlasResult } from './TextureAtlas';-import { AssetLibrary } from '../asset/AssetLibrary';-import { normalizePath, joinPath, getProjectDir, isAbsolutePath, getParentDir } from '../utils/path';-import { resolveShaderPath } from '../utils/shader';-import { getAssetType } from '../asset/AssetTypes';-import { compileMaterials } from './MaterialCompiler';-import type { NativeFS } from '../types/NativeFS';--// =============================================================================-// Types-// =============================================================================--interface AssetManifestEntry {- path: string;- type: string;-}--// =============================================================================-// WeChatBuilder-// =============================================================================--export class WeChatBuilder {- private context_: BuildContext;- private fs_: NativeFS | null;- private projectDir_: string;- private progress_: BuildProgressReporter;- private cache_: BuildCache | null;- private assetLibrary_: AssetLibrary;-- constructor(context: BuildContext) {- this.context_ = context;- this.fs_ = getEditorContext().fs ?? null;- this.projectDir_ = getProjectDir(context.projectPath);- this.progress_ = context.progress || new BuildProgressReporter();- this.cache_ = context.cache || null;- this.assetLibrary_ = new AssetLibrary();- }-- async build(): Promise<BuildResult> {- if (!this.fs_) {- return { success: false, error: 'Native file system not available' };- }-- const settings = this.context_.config.wechatSettings;- if (!settings) {- return { success: false, error: 'WeChat settings not configured' };- }-- this.progress_.setPhase('preparing');- this.progress_.log('info', 'Starting WeChat MiniGame build...');-- try {- await this.assetLibrary_.initialize(this.projectDir_, this.fs_);- this.progress_.log('info', 'Asset library initialized');-- const outputDir = joinPath(this.projectDir_, settings.outputDir);- await this.fs_.createDirectory(outputDir);-- // 1. Generate project.config.json- this.progress_.setCurrentTask('Generating project.config.json...', 10);- await this.generateProjectConfig(outputDir, settings);- this.progress_.log('info', 'Generated project.config.json');-- // 2. Generate game.json- this.progress_.setCurrentTask('Generating game.json...', 20);- await this.generateGameJson(outputDir);- this.progress_.log('info', 'Generated game.json');-- // 3. Compile and generate game.js- this.progress_.setPhase('compiling');- this.progress_.setCurrentTask('Compiling scripts...', 0);- await this.generateGameJs(outputDir);- this.progress_.log('info', 'Generated game.js');-- // 4. Collect assets and pack atlas- this.progress_.setPhase('processing_assets');- this.progress_.setCurrentTask('Packing texture atlas...', 0);- const { atlasResult, packedPaths } = await this.packTextureAtlas(outputDir);- if (atlasResult.pages.length > 0) {- this.progress_.log('info', `Packed ${atlasResult.frameMap.size} textures into ${atlasResult.pages.length} atlas page(s)`);- }-- // 5. Compile materials- this.progress_.setCurrentTask('Compiling materials...', 20);- const compiledMaterials = await this.compileMaterials_();- this.progress_.log('info', `Compiled ${compiledMaterials.size} material(s)`);-- // 6. Copy scenes (with atlas rewriting, UUID preserved)- this.progress_.setCurrentTask('Copying scenes...', 30);- await this.copyScenes(outputDir, atlasResult);- this.progress_.log('info', 'Copied scenes');-- // 7. Copy assets (excluding packed textures, .esmaterial, .esshader)- this.progress_.setCurrentTask('Copying assets...', 50);- await this.copyAssets(outputDir, packedPaths, compiledMaterials);- this.progress_.log('info', 'Copied assets');-- // 8. Generate asset-manifest.json- this.progress_.setCurrentTask('Generating asset manifest...', 70);- await this.generateAssetManifest(outputDir, packedPaths, compiledMaterials, atlasResult);- this.progress_.log('info', 'Generated asset-manifest.json');-- // 9. Write output- this.progress_.setPhase('writing');- this.progress_.setCurrentTask('Finalizing...', 0);-- this.progress_.log('info', `Build successful: ${outputDir}`);- return { success: true, outputPath: outputDir };- } catch (err) {- console.error('[WeChatBuilder] Build error:', err);- this.progress_.fail(String(err));- return { success: false, error: String(err) };- }- }-- private async generateProjectConfig(- outputDir: string,- settings: NonNullable<typeof this.context_.config.wechatSettings>- ): Promise<void> {- const config = {- description: 'ESEngine Game',- packOptions: {- ignore: [],- include: [],- },- setting: {- urlCheck: false,- es6: true,- enhance: true,- compileHotReLoad: false,- postcss: false,- preloadBackgroundData: false,- minified: !this.context_.config.defines.includes('DEBUG'),- newFeature: true,- coverView: true,- nodeModules: false,- autoAudits: false,- showShadowRootInWxmlPanel: true,- scopeDataCheck: false,- uglifyFileName: false,- checkInvalidKey: true,- checkSiteMap: true,- uploadWithSourceMap: true,- compileWorklet: false,- babelSetting: {- ignore: [],- disablePlugins: [],- outputPath: '',- },- },- compileType: 'minigame',- libVersion: '3.0.0',- appid: settings.appId || 'touristappid',- projectname: 'ESEngineGame',- condition: {},- editorSetting: {- tabIndent: 'auto',- tabSize: 4,- },- };-- await this.fs_!.writeFile(- joinPath(outputDir, 'project.config.json'),- JSON.stringify(config, null, 2)- );- }-- private async generateGameJson(outputDir: string): Promise<void> {- const settings = this.context_.config.wechatSettings;-- const gameJson: Record<string, unknown> = {- deviceOrientation: settings?.orientation || 'portrait',- networkTimeout: {- request: 10000,- connectSocket: 10000,- uploadFile: 10000,- downloadFile: 10000,- },- };-- if (settings?.subpackages && settings.subpackages.length > 0) {- gameJson.subpackages = settings.subpackages;- }-- if (settings?.workers) {- gameJson.workers = settings.workers;- }-- if (settings?.openDataContext) {- gameJson.openDataContext = settings.openDataContext;- }-- await this.fs_!.writeFile(- joinPath(outputDir, 'game.json'),- JSON.stringify(gameJson, null, 2)- );- }-- private async generateGameJs(outputDir: string): Promise<void> {- const scriptsPath = joinPath(this.projectDir_, 'src');-- let userCode = '';- if (await this.fs_!.exists(scriptsPath)) {- const scripts = await findTsFiles(this.fs_!, scriptsPath, EDITOR_ONLY_DIRS);-- if (scripts.length > 0) {- userCode = await this.compileScripts(scripts);- }- }-- const firstScene = this.context_.config.scenes[0];- const firstSceneName = firstScene ? firstScene.replace(/.*\//, '').replace('.esscene', '') : '';-- const gameJs = `-var ESEngineModule = require('./esengine.js');-var SDK = require('./sdk.js');-globalThis.__esengine_sdk = SDK;--var manifest = JSON.parse(wx.getFileSystemManager().readFileSync('asset-manifest.json', 'utf-8'));--function resolvePath(ref) {- var entry = manifest[ref];- return entry ? entry.path : ref;-}--var spineModule = null;-${this.context_.spineVersion ? `-async function initSpineModule() {- try {- var SpineFactory = require('./spine.js');- spineModule = await SpineFactory({- instantiateWasm: function(imports, successCallback) {- WXWebAssembly.instantiate('spine.wasm', imports).then(function(result) {- successCallback(result.instance, result.module);- });- return {};- }- });- } catch(e) { console.warn('Spine module not available:', e); }-}` : ''}--var physicsModule = null;-${this.context_.enablePhysics ? `-async function initPhysicsModule() {- try {- var PhysicsFactory = require('./physics.js');- physicsModule = await PhysicsFactory({- instantiateWasm: function(imports, successCallback) {- WXWebAssembly.instantiate('physics.wasm', imports).then(function(result) {- successCallback(result.instance, result.module);- });- return {};- }- });- } catch(e) { console.warn('Physics module not available:', e); }-}` : ''}--(async function() {- var canvas = wx.createCanvas();- var info = wx.getSystemInfoSync();- canvas.width = info.windowWidth * info.pixelRatio;- canvas.height = info.windowHeight * info.pixelRatio;-- var module = await ESEngineModule({- canvas: canvas,- instantiateWasm: function(imports, successCallback) {- WXWebAssembly.instantiate('esengine.wasm', imports).then(function(result) {- successCallback(result.instance, result.module);- });- return {};- }- });-- var gl = canvas.getContext('webgl2') || canvas.getContext('webgl');- if (!gl) {- console.error('[ESEngine] Failed to create WebGL context');- return;- }- var glHandle = module.GL.registerContext(gl, {- majorVersion: gl.getParameter(gl.VERSION).indexOf('WebGL 2') === 0 ? 2 : 1,- minorVersion: 0,- enableExtensionsByDefault: true- });-- var app = SDK.createWebApp(module, {- glContextHandle: glHandle,- getViewportSize: function() {- return { width: canvas.width, height: canvas.height };- }- });-- ${userCode}-- SDK.flushPendingSystems(app);-- ${this.context_.spineVersion ? 'await initSpineModule();' : ''}- ${this.context_.enablePhysics ? 'await initPhysicsModule();' : ''}-- ${firstSceneName ? `- try {- var wxfs = wx.getFileSystemManager();- var provider = {- loadPixels: function(ref) { return SDK.wxLoadImagePixels(resolvePath(ref)); },- loadPixelsRaw: function(ref) { return SDK.wxLoadImagePixels(resolvePath(ref)); },- readText: function(ref) { return wxfs.readFileSync(resolvePath(ref), 'utf-8'); },- readBinary: function(ref) { return new Uint8Array(wxfs.readFileSync(resolvePath(ref))); },- resolvePath: resolvePath- };-- var sceneJson = wxfs.readFileSync('scenes/${firstSceneName}.json', 'utf-8');- var sceneData = JSON.parse(sceneJson);-- await SDK.loadRuntimeScene(app, module, sceneData, provider, spineModule, physicsModule, ${JSON.stringify({- gravity: this.context_.physicsGravity ?? { x: 0, y: -9.81 },- fixedTimestep: this.context_.physicsFixedTimestep ?? 1 / 60,- subStepCount: this.context_.physicsSubStepCount ?? 4,- })});-- var screenAspect = canvas.width / canvas.height;- SDK.updateCameraAspectRatio(app.world, screenAspect);- } catch (err) {- console.error('[ESEngine] Failed to load scene:', err);- }- ` : ''}- app.run();-})();-`;-- await this.fs_!.writeFile(joinPath(outputDir, 'game.js'), gameJs);-- await this.copyWeChatSdk(outputDir);- }-- private async copyWeChatSdk(outputDir: string): Promise<void> {- const engineJs = await this.fs_!.getEngineWxgameJs();- const engineWasm = await this.fs_!.getEngineWxgameWasm();-- if (!engineJs || engineJs.length === 0) {- throw new Error(- 'WeChat engine not found. Please run: scripts/build-wxgame.sh'- );- }-- await this.fs_!.writeFile(joinPath(outputDir, 'esengine.js'), engineJs);- await this.fs_!.writeBinaryFile(joinPath(outputDir, 'esengine.wasm'), engineWasm);- console.log(`[WeChatBuilder] Copied WeChat engine files`);-- const sdkJs = await this.fs_!.getSdkWechatJs();- if (sdkJs) {- await this.fs_!.writeFile(joinPath(outputDir, 'sdk.js'), sdkJs);- console.log(`[WeChatBuilder] Copied SDK`);- }-- const spineVersion = this.context_.spineVersion;- if (spineVersion) {- const spineJs = await this.fs_!.getSpineJs(spineVersion);- const spineWasm = await this.fs_!.getSpineWasm(spineVersion);- if (spineJs && spineWasm.length > 0) {- await this.fs_!.writeFile(joinPath(outputDir, 'spine.js'), spineJs);- await this.fs_!.writeBinaryFile(joinPath(outputDir, 'spine.wasm'), spineWasm);- console.log(`[WeChatBuilder] Copied Spine ${spineVersion} module`);- }- }-- if (this.context_.enablePhysics) {- const physicsJs = await this.fs_!.getPhysicsJs();- const physicsWasm = await this.fs_!.getPhysicsWasm();- if (physicsJs && physicsWasm.length > 0) {- await this.fs_!.writeFile(joinPath(outputDir, 'physics.js'), physicsJs);- await this.fs_!.writeBinaryFile(joinPath(outputDir, 'physics.wasm'), physicsWasm);- console.log(`[WeChatBuilder] Copied Physics module`);- }- }- }-- private async compileScripts(scripts: string[]): Promise<string> {- const entryContent = scripts.map(p => `import "${p}";`).join('\n');-- const defines: Record<string, string> = {- 'process.env.EDITOR': 'false',- };- for (const def of this.context_.config.defines) {- defines[`process.env.${def}`] = 'true';- }-- try {- await esbuild.initialize({- wasmURL: getEsbuildWasmURL(),- });- } catch (err) {- if (!String(err).includes('Cannot call "initialize" more than once')) {- throw err;- }- }-- const result = await esbuild.build({- stdin: {- contents: entryContent,- loader: 'ts',- resolveDir: joinPath(this.projectDir_, 'src'),- },- bundle: true,- format: 'iife',- write: false,- platform: 'browser',- target: 'es2020',- minify: !this.context_.config.defines.includes('DEBUG'),- define: defines,- plugins: [this.createVirtualFsPlugin()],- });-- return result.outputFiles?.[0]?.text ?? '';- }-- private createVirtualFsPlugin(): esbuild.Plugin {- const fs = this.fs_!;- const projectDir = this.projectDir_;--- const resolvePackageEntry = async (pkgName: string): Promise<string | null> => {- const pkgJsonPath = joinPath(projectDir, 'node_modules', pkgName, 'package.json');- const pkgContent = await fs.readFile(pkgJsonPath);- if (!pkgContent) return null;-- try {- const pkg = JSON.parse(pkgContent);- let entry = pkg.main || 'index.js';- if (pkg.exports) {- const root = pkg.exports['.'];- if (typeof root === 'string') {- entry = root;- } else if (root?.import) {- entry = root.import;- } else if (root?.default) {- entry = root.default;- }- }- return joinPath(projectDir, 'node_modules', pkgName, entry);- } catch {- return joinPath(projectDir, 'node_modules', pkgName, 'index.js');- }- };-- return {- name: 'virtual-fs',- setup(build) {- build.onResolve({ filter: /^esengine(\/wasm)?$/ }, (args) => ({- path: args.path,- namespace: 'sdk-shim',- }));-- build.onLoad({ filter: /.*/, namespace: 'sdk-shim' }, () => ({- contents: 'module.exports = globalThis.__esengine_sdk;',- loader: 'js',- }));-- build.onResolve({ filter: /.*/ }, async (args) => {- if (args.kind === 'entry-point') {- return { path: args.path, namespace: 'virtual' };- }-- let resolvedPath = args.path;-- if (isAbsolutePath(args.path)) {- resolvedPath = normalizePath(args.path);- } else if (args.path.startsWith('.')) {- const baseDir = args.importer ? getParentDir(args.importer) : args.resolveDir;- resolvedPath = joinPath(baseDir, args.path);- } else {- const pkgEntry = await resolvePackageEntry(args.path);- if (pkgEntry) {- resolvedPath = pkgEntry;- } else {- throw new Error(`Module not found: ${args.path}. Please install it with npm.`);- }- }-- if (!resolvedPath.endsWith('.ts') && !resolvedPath.endsWith('.js')) {- if (await fs.exists(resolvedPath + '.ts')) {- resolvedPath += '.ts';- } else if (await fs.exists(resolvedPath + '.js')) {- resolvedPath += '.js';- } else if (await fs.exists(joinPath(resolvedPath, 'index.ts'))) {- resolvedPath = joinPath(resolvedPath, 'index.ts');- } else if (await fs.exists(joinPath(resolvedPath, 'index.js'))) {- resolvedPath = joinPath(resolvedPath, 'index.js');- }- }-- return { path: resolvedPath, namespace: 'virtual' };- });-- build.onLoad({ filter: /.*/, namespace: 'virtual' }, async (args) => {- const content = await fs.readFile(args.path);- if (content === null) {- return { contents: '', loader: 'ts' };- }- const loader = args.path.endsWith('.ts') ? 'ts' : 'js';- return { contents: content, loader };- });- },- };- }-- private async compileMaterials_(): Promise<Map<string, { uuid: string; outputPath: string; json: string }>> {- const configService = new AssetExportConfigService(this.projectDir_, this.fs_!);- const exportConfig = await configService.load();- const compiled = await compileMaterials(this.fs_!, this.projectDir_, this.assetLibrary_, this.context_.config, exportConfig);-- const result = new Map<string, { uuid: string; outputPath: string; json: string }>();- for (const mat of compiled) {- result.set(mat.relativePath, {- uuid: mat.uuid,- outputPath: mat.relativePath.replace(/\.esmaterial$/, '.json'),- json: JSON.stringify(JSON.parse(mat.json), null, 2),- });- }- return result;- }--- private async packTextureAtlas(- outputDir: string- ): Promise<{ atlasResult: AtlasResult; packedPaths: Set<string> }> {- const configService = new AssetExportConfigService(this.projectDir_, this.fs_!);- const exportConfig = await configService.load();-- const collector = new BuildAssetCollector(this.fs_!, this.projectDir_, this.assetLibrary_);- const assetPaths = await collector.collect(this.context_.config, exportConfig);-- const imagePaths = [...assetPaths].filter(p => {- const ext = p.split('.').pop()?.toLowerCase() ?? '';- return ext === 'png' || ext === 'jpg' || ext === 'jpeg';- });-- const sceneDataList: Array<{ name: string; data: Record<string, unknown> }> = [];- for (const scenePath of this.context_.config.scenes) {- const fullPath = isAbsolutePath(scenePath)- ? normalizePath(scenePath)- : joinPath(this.projectDir_, scenePath);- const content = await this.fs_!.readFile(fullPath);- if (content) {- const name = scenePath.replace(/.*\//, '').replace('.esscene', '');- sceneDataList.push({ name, data: JSON.parse(content) });- }- }-- const packer = new TextureAtlasPacker(this.fs_!, this.projectDir_, this.assetLibrary_);- const atlasResult = await packer.pack(imagePaths, sceneDataList, 2048, [...assetPaths]);-- for (let i = 0; i < atlasResult.pages.length; i++) {- const atlasPath = joinPath(outputDir, `atlas_${i}.png`);- await this.fs_!.writeBinaryFile(atlasPath, atlasResult.pages[i].imageData);- }-- const packedPaths = new Set<string>(atlasResult.frameMap.keys());- return { atlasResult, packedPaths };- }-- private async copyScenes(outputDir: string, atlasResult: AtlasResult): Promise<void> {- const scenesDir = joinPath(outputDir, 'scenes');- await this.fs_!.createDirectory(scenesDir);-- const packer = new TextureAtlasPacker(this.fs_!, this.projectDir_, this.assetLibrary_);-- for (const scenePath of this.context_.config.scenes) {- const fullPath = isAbsolutePath(scenePath)- ? normalizePath(scenePath)- : joinPath(this.projectDir_, scenePath);-- const content = await this.fs_!.readFile(fullPath);- if (content) {- const name = scenePath.replace(/.*\//, '').replace('.esscene', '');- const sceneData = JSON.parse(content);- packer.rewriteSceneData(sceneData, atlasResult, '');- await this.fs_!.writeFile(joinPath(scenesDir, `${name}.json`), JSON.stringify(sceneData, null, 2));- }- }- }-- private async copyAssets(- outputDir: string,- packedPaths: Set<string>,- compiledMaterials: Map<string, { uuid: string; outputPath: string; json: string }>- ): Promise<void> {- const configService = new AssetExportConfigService(this.projectDir_, this.fs_!);- const exportConfig = await configService.load();-- const collector = new BuildAssetCollector(this.fs_!, this.projectDir_, this.assetLibrary_);- const assetPaths = await collector.collect(this.context_.config, exportConfig);-- const compiledMaterialPaths = new Set<string>();- const compiledShaderPaths = new Set<string>();- for (const [matPath, compiled] of compiledMaterials) {- compiledMaterialPaths.add(matPath);- const fullPath = joinPath(this.projectDir_, matPath);- const content = await this.fs_!.readFile(fullPath);- if (content) {- try {- const matData = JSON.parse(content);- if (matData.shader) {- compiledShaderPaths.add(resolveShaderPath(matPath, matData.shader));- }- } catch {- // ignore- }- }- }-- for (const relativePath of assetPaths) {- if (packedPaths.has(relativePath)) continue;- if (compiledMaterialPaths.has(relativePath)) continue;- if (compiledShaderPaths.has(relativePath)) continue;- if (relativePath.endsWith('.esshader')) continue;-- const srcPath = joinPath(this.projectDir_, relativePath);- const destPath = joinPath(outputDir, relativePath);-- const destDir = destPath.substring(0, destPath.lastIndexOf('/'));- await this.fs_!.createDirectory(destDir);-- const data = await this.fs_!.readBinaryFile(srcPath);- if (data) {- await this.fs_!.writeBinaryFile(destPath, data);- }- }-- for (const [, compiled] of compiledMaterials) {- const destPath = joinPath(outputDir, compiled.outputPath);- const destDir = destPath.substring(0, destPath.lastIndexOf('/'));- await this.fs_!.createDirectory(destDir);- await this.fs_!.writeFile(destPath, compiled.json);- }- }-- private async generateAssetManifest(- outputDir: string,- packedPaths: Set<string>,- compiledMaterials: Map<string, { uuid: string; outputPath: string; json: string }>,- atlasResult: AtlasResult- ): Promise<void> {- const manifest: Record<string, AssetManifestEntry> = {};-- const configService = new AssetExportConfigService(this.projectDir_, this.fs_!);- const exportConfig = await configService.load();- const collector = new BuildAssetCollector(this.fs_!, this.projectDir_, this.assetLibrary_);- const assetPaths = await collector.collect(this.context_.config, exportConfig);-- for (const relativePath of assetPaths) {- if (relativePath.endsWith('.esshader')) continue;-- const uuid = this.assetLibrary_.getUuid(relativePath);- if (!uuid) continue;-- if (packedPaths.has(relativePath)) {- const entry = atlasResult.frameMap.get(relativePath);- if (entry) {- manifest[uuid] = {- path: `atlas_${entry.page}.png`,- type: 'texture',- };- }- continue;- }-- const compiled = compiledMaterials.get(relativePath);- if (compiled) {- manifest[uuid] = {- path: compiled.outputPath,- type: 'material',- };- continue;- }-- manifest[uuid] = {- path: relativePath,- type: getAssetType(relativePath),- };- }-- await this.fs_!.writeFile(- joinPath(outputDir, 'asset-manifest.json'),- JSON.stringify(manifest, null, 2)- );- }--}diff --git a/editor/src/builder/WeChatEmitter.ts b/editor/src/builder/WeChatEmitter.tsnew file mode 100644index 000000000..c67b9934b--- /dev/null+++ b/editor/src/builder/WeChatEmitter.ts@@ -0,0 +1,520 @@+/**+ * @file WeChatEmitter.ts+ * @brief Emitter that produces WeChat Mini Game output directory+ */++import * as esbuild from 'esbuild-wasm/esm/browser';+import type { PlatformEmitter, BuildArtifact } from './PlatformEmitter';+import type { BuildResult, BuildContext } from './BuildService';+import { BuildProgressReporter } from './BuildProgress';+import { getEditorContext } from '../context/EditorContext';+import { findTsFiles, EDITOR_ONLY_DIRS } from '../scripting/ScriptLoader';+import { joinPath, getProjectDir } from '../utils/path';+import { getAssetType } from '../asset/AssetTypes';+import { resolveShaderPath } from '../utils/shader';+import { initializeEsbuild, createBuildVirtualFsPlugin } from './ArtifactBuilder';+import type { NativeFS } from '../types/NativeFS';++// =============================================================================+// Types+// =============================================================================++interface AssetManifestEntry {+ path: string;+ type: string;+}++// =============================================================================+// WeChatEmitter+// =============================================================================++export class WeChatEmitter implements PlatformEmitter {+ async emit(artifact: BuildArtifact, context: BuildContext): Promise<BuildResult> {+ const fs = getEditorContext().fs;+ if (!fs) {+ return { success: false, error: 'Native file system not available' };+ }++ const settings = context.config.wechatSettings;+ if (!settings) {+ return { success: false, error: 'WeChat settings not configured' };+ }++ const progress = context.progress || new BuildProgressReporter();+ const projectDir = getProjectDir(context.projectPath);+ const outputDir = joinPath(projectDir, settings.outputDir);++ try {+ await fs.createDirectory(outputDir);++ // 1. Generate project.config.json+ progress.setCurrentTask('Generating project.config.json...', 10);+ await this.generateProjectConfig(fs, outputDir, settings, context);+ progress.log('info', 'Generated project.config.json');++ // 2. Generate game.json+ progress.setCurrentTask('Generating game.json...', 20);+ await this.generateGameJson(fs, outputDir, settings);+ progress.log('info', 'Generated game.json');++ // 3. Compile and generate game.js+ progress.setPhase('compiling');+ progress.setCurrentTask('Compiling scripts...', 0);+ await this.generateGameJs(fs, projectDir, outputDir, context);+ progress.log('info', 'Generated game.js');++ // 4. Write atlas pages+ progress.setPhase('writing');+ progress.setCurrentTask('Writing atlas pages...', 0);+ for (let i = 0; i < artifact.atlasResult.pages.length; i++) {+ await fs.writeBinaryFile(+ joinPath(outputDir, `atlas_${i}.png`),+ artifact.atlasResult.pages[i].imageData+ );+ }+ if (artifact.atlasResult.pages.length > 0) {+ progress.log('info', `Packed ${artifact.atlasResult.frameMap.size} textures into ${artifact.atlasResult.pages.length} atlas page(s)`);+ }++ // 5. Write scenes+ progress.setCurrentTask('Copying scenes...', 10);+ const scenesDir = joinPath(outputDir, 'scenes');+ await fs.createDirectory(scenesDir);+ for (const [name, sceneData] of artifact.scenes) {+ await fs.writeFile(+ joinPath(scenesDir, `${name}.json`),+ JSON.stringify(sceneData, null, 2)+ );+ }+ progress.log('info', 'Copied scenes');++ // 6. Copy assets+ progress.setCurrentTask('Copying assets...', 30);+ await this.copyAssets(fs, projectDir, outputDir, artifact);+ progress.log('info', 'Copied assets');++ // 7. Write compiled materials+ progress.setCurrentTask('Writing compiled materials...', 50);+ for (const mat of artifact.compiledMaterials) {+ const matOutputPath = mat.relativePath.replace(/\.esmaterial$/, '.json');+ const destPath = joinPath(outputDir, matOutputPath);+ const destDir = destPath.substring(0, destPath.lastIndexOf('/'));+ await fs.createDirectory(destDir);+ await fs.writeFile(destPath, JSON.stringify(JSON.parse(mat.json), null, 2));+ }+ progress.log('info', `Compiled ${artifact.compiledMaterials.length} material(s)`);++ // 8. Generate asset-manifest.json+ progress.setCurrentTask('Generating asset manifest...', 70);+ await this.generateAssetManifest(fs, outputDir, artifact);+ progress.log('info', 'Generated asset-manifest.json');++ progress.setCurrentTask('Finalizing...', 90);+ progress.log('info', `Build successful: ${outputDir}`);+ return { success: true, outputPath: outputDir };+ } catch (err) {+ console.error('[WeChatEmitter] Build error:', err);+ progress.fail(String(err));+ return { success: false, error: String(err) };+ }+ }++ // =========================================================================+ // Private Methods+ // =========================================================================++ private async generateProjectConfig(+ fs: NativeFS,+ outputDir: string,+ settings: NonNullable<BuildContext['config']['wechatSettings']>,+ context: BuildContext+ ): Promise<void> {+ const config = {+ description: 'ESEngine Game',+ packOptions: {+ ignore: [],+ include: [],+ },+ setting: {+ urlCheck: false,+ es6: true,+ enhance: true,+ compileHotReLoad: false,+ postcss: false,+ preloadBackgroundData: false,+ minified: !context.config.defines.includes('DEBUG'),+ newFeature: true,+ coverView: true,+ nodeModules: false,+ autoAudits: false,+ showShadowRootInWxmlPanel: true,+ scopeDataCheck: false,+ uglifyFileName: false,+ checkInvalidKey: true,+ checkSiteMap: true,+ uploadWithSourceMap: true,+ compileWorklet: false,+ babelSetting: {+ ignore: [],+ disablePlugins: [],+ outputPath: '',+ },+ },+ compileType: 'minigame',+ libVersion: '3.0.0',+ appid: settings.appId || 'touristappid',+ projectname: 'ESEngineGame',+ condition: {},+ editorSetting: {+ tabIndent: 'auto',+ tabSize: 4,+ },+ };++ await fs.writeFile(+ joinPath(outputDir, 'project.config.json'),+ JSON.stringify(config, null, 2)+ );+ }++ private async generateGameJson(+ fs: NativeFS,+ outputDir: string,+ settings: NonNullable<BuildContext['config']['wechatSettings']>+ ): Promise<void> {+ const gameJson: Record<string, unknown> = {+ deviceOrientation: settings.orientation || 'portrait',+ networkTimeout: {+ request: 10000,+ connectSocket: 10000,+ uploadFile: 10000,+ downloadFile: 10000,+ },+ };++ if (settings.subpackages && settings.subpackages.length > 0) {+ gameJson.subpackages = settings.subpackages;+ }++ if (settings.workers) {+ gameJson.workers = settings.workers;+ }++ if (settings.openDataContext) {+ gameJson.openDataContext = settings.openDataContext;+ }++ await fs.writeFile(+ joinPath(outputDir, 'game.json'),+ JSON.stringify(gameJson, null, 2)+ );+ }++ private async generateGameJs(+ fs: NativeFS,+ projectDir: string,+ outputDir: string,+ context: BuildContext+ ): Promise<void> {+ const scriptsPath = joinPath(projectDir, 'src');++ let userCode = '';+ if (await fs.exists(scriptsPath)) {+ const scripts = await findTsFiles(fs, scriptsPath, EDITOR_ONLY_DIRS);+ if (scripts.length > 0) {+ userCode = await this.compileScripts(fs, projectDir, scripts, context);+ }+ }++ const firstScene = context.config.scenes[0];+ const firstSceneName = firstScene ? firstScene.replace(/.*\//, '').replace('.esscene', '') : '';++ const gameJs = `+var ESEngineModule = require('./esengine.js');+var SDK = require('./sdk.js');+globalThis.__esengine_sdk = SDK;++var manifest = JSON.parse(wx.getFileSystemManager().readFileSync('asset-manifest.json', 'utf-8'));++function resolvePath(ref) {+ var entry = manifest[ref];+ return entry ? entry.path : ref;+}++var spineModule = null;+${context.spineVersion ? `+async function initSpineModule() {+ try {+ var SpineFactory = require('./spine.js');+ spineModule = await SpineFactory({+ instantiateWasm: function(imports, successCallback) {+ WXWebAssembly.instantiate('spine.wasm', imports).then(function(result) {+ successCallback(result.instance, result.module);+ });+ return {};+ }+ });+ } catch(e) { console.warn('Spine module not available:', e); }+}` : ''}++var physicsModule = null;+${context.enablePhysics ? `+async function initPhysicsModule() {+ try {+ var PhysicsFactory = require('./physics.js');+ physicsModule = await PhysicsFactory({+ instantiateWasm: function(imports, successCallback) {+ WXWebAssembly.instantiate('physics.wasm', imports).then(function(result) {+ successCallback(result.instance, result.module);+ });+ return {};+ }+ });+ } catch(e) { console.warn('Physics module not available:', e); }+}` : ''}++(async function() {+ var canvas = wx.createCanvas();+ var info = wx.getSystemInfoSync();+ canvas.width = info.windowWidth * info.pixelRatio;+ canvas.height = info.windowHeight * info.pixelRatio;++ var module = await ESEngineModule({+ canvas: canvas,+ instantiateWasm: function(imports, successCallback) {+ WXWebAssembly.instantiate('esengine.wasm', imports).then(function(result) {+ successCallback(result.instance, result.module);+ });+ return {};+ }+ });++ var gl = canvas.getContext('webgl2') || canvas.getContext('webgl');+ if (!gl) {+ console.error('[ESEngine] Failed to create WebGL context');+ return;+ }+ var glHandle = module.GL.registerContext(gl, {+ majorVersion: gl.getParameter(gl.VERSION).indexOf('WebGL 2') === 0 ? 2 : 1,+ minorVersion: 0,+ enableExtensionsByDefault: true+ });++ var app = SDK.createWebApp(module, {+ glContextHandle: glHandle,+ getViewportSize: function() {+ return { width: canvas.width, height: canvas.height };+ }+ });++ ${userCode}++ SDK.flushPendingSystems(app);++ ${context.spineVersion ? 'await initSpineModule();' : ''}+ ${context.enablePhysics ? 'await initPhysicsModule();' : ''}++ ${firstSceneName ? `+ try {+ var wxfs = wx.getFileSystemManager();+ var provider = {+ loadPixels: function(ref) { return SDK.wxLoadImagePixels(resolvePath(ref)); },+ loadPixelsRaw: function(ref) { return SDK.wxLoadImagePixels(resolvePath(ref)); },+ readText: function(ref) { return wxfs.readFileSync(resolvePath(ref), 'utf-8'); },+ readBinary: function(ref) { return new Uint8Array(wxfs.readFileSync(resolvePath(ref))); },+ resolvePath: resolvePath+ };++ var sceneJson = wxfs.readFileSync('scenes/${firstSceneName}.json', 'utf-8');+ var sceneData = JSON.parse(sceneJson);++ await SDK.loadRuntimeScene(app, module, sceneData, provider, spineModule, physicsModule, ${JSON.stringify({+ gravity: context.physicsGravity ?? { x: 0, y: -9.81 },+ fixedTimestep: context.physicsFixedTimestep ?? 1 / 60,+ subStepCount: context.physicsSubStepCount ?? 4,+ })});++ var screenAspect = canvas.width / canvas.height;+ SDK.updateCameraAspectRatio(app.world, screenAspect);+ } catch (err) {+ console.error('[ESEngine] Failed to load scene:', err);+ }+ ` : ''}+ app.run();+})();+`;++ await fs.writeFile(joinPath(outputDir, 'game.js'), gameJs);+ await this.copyWeChatSdk(fs, outputDir, context);+ }++ private async compileScripts(+ fs: NativeFS,+ projectDir: string,+ scripts: string[],+ context: BuildContext+ ): Promise<string> {+ const entryContent = scripts.map(p => `import "${p}";`).join('\n');++ const defines: Record<string, string> = {+ 'process.env.EDITOR': 'false',+ };+ for (const def of context.config.defines) {+ defines[`process.env.${def}`] = 'true';+ }++ await initializeEsbuild();++ const plugin = createBuildVirtualFsPlugin(fs, projectDir, async () => ({+ contents: 'module.exports = globalThis.__esengine_sdk;',+ loader: 'js' as esbuild.Loader,+ }), false);++ const result = await esbuild.build({+ stdin: {+ contents: entryContent,+ loader: 'ts',+ resolveDir: joinPath(projectDir, 'src'),+ },+ bundle: true,+ format: 'iife',+ write: false,+ platform: 'browser',+ target: 'es2020',+ minify: !context.config.defines.includes('DEBUG'),+ define: defines,+ plugins: [plugin],+ });++ return result.outputFiles?.[0]?.text ?? '';+ }++ private async copyWeChatSdk(+ fs: NativeFS,+ outputDir: string,+ context: BuildContext+ ): Promise<void> {+ const engineJs = await fs.getEngineWxgameJs();+ const engineWasm = await fs.getEngineWxgameWasm();++ if (!engineJs || engineJs.length === 0) {+ throw new Error(+ 'WeChat engine not found. Please run: scripts/build-wxgame.sh'+ );+ }++ await fs.writeFile(joinPath(outputDir, 'esengine.js'), engineJs);+ await fs.writeBinaryFile(joinPath(outputDir, 'esengine.wasm'), engineWasm);++ const sdkJs = await fs.getSdkWechatJs();+ if (sdkJs) {+ await fs.writeFile(joinPath(outputDir, 'sdk.js'), sdkJs);+ }++ const spineVersion = context.spineVersion;+ if (spineVersion) {+ const spineJs = await fs.getSpineJs(spineVersion);+ const spineWasm = await fs.getSpineWasm(spineVersion);+ if (spineJs && spineWasm.length > 0) {+ await fs.writeFile(joinPath(outputDir, 'spine.js'), spineJs);+ await fs.writeBinaryFile(joinPath(outputDir, 'spine.wasm'), spineWasm);+ }+ }++ if (context.enablePhysics) {+ const physicsJs = await fs.getPhysicsJs();+ const physicsWasm = await fs.getPhysicsWasm();+ if (physicsJs && physicsWasm.length > 0) {+ await fs.writeFile(joinPath(outputDir, 'physics.js'), physicsJs);+ await fs.writeBinaryFile(joinPath(outputDir, 'physics.wasm'), physicsWasm);+ }+ }+ }++ private async copyAssets(+ fs: NativeFS,+ projectDir: string,+ outputDir: string,+ artifact: BuildArtifact+ ): Promise<void> {+ const compiledMaterialPaths = new Set(artifact.compiledMaterials.map(m => m.relativePath));+ const compiledShaderPaths = new Set<string>();++ for (const mat of artifact.compiledMaterials) {+ const fullPath = joinPath(projectDir, mat.relativePath);+ const content = await fs.readFile(fullPath);+ if (content) {+ try {+ const matData = JSON.parse(content);+ if (matData.shader) {+ compiledShaderPaths.add(resolveShaderPath(mat.relativePath, matData.shader));+ }+ } catch {+ // ignore+ }+ }+ }++ for (const relativePath of artifact.assetPaths) {+ if (artifact.packedPaths.has(relativePath)) continue;+ if (compiledMaterialPaths.has(relativePath)) continue;+ if (compiledShaderPaths.has(relativePath)) continue;+ if (relativePath.endsWith('.esshader')) continue;++ const srcPath = joinPath(projectDir, relativePath);+ const destPath = joinPath(outputDir, relativePath);+ const destDir = destPath.substring(0, destPath.lastIndexOf('/'));+ await fs.createDirectory(destDir);++ const data = await fs.readBinaryFile(srcPath);+ if (data) {+ await fs.writeBinaryFile(destPath, data);+ }+ }+ }++ private async generateAssetManifest(+ fs: NativeFS,+ outputDir: string,+ artifact: BuildArtifact+ ): Promise<void> {+ const manifest: Record<string, AssetManifestEntry> = {};++ for (const relativePath of artifact.assetPaths) {+ if (relativePath.endsWith('.esshader')) continue;++ const uuid = artifact.assetLibrary.getUuid(relativePath);+ if (!uuid) continue;++ if (artifact.packedPaths.has(relativePath)) {+ const entry = artifact.atlasResult.frameMap.get(relativePath);+ if (entry) {+ manifest[uuid] = {+ path: `atlas_${entry.page}.png`,+ type: 'texture',+ };+ }+ continue;+ }++ const compiledMat = artifact.compiledMaterials.find(m => m.relativePath === relativePath);+ if (compiledMat) {+ manifest[uuid] = {+ path: relativePath.replace(/\.esmaterial$/, '.json'),+ type: 'material',+ };+ continue;+ }++ manifest[uuid] = {+ path: relativePath,+ type: getAssetType(relativePath),+ };+ }++ await fs.writeFile(+ joinPath(outputDir, 'asset-manifest.json'),+ JSON.stringify(manifest, null, 2)+ );+ }+}diff --git a/editor/src/builder/index.ts b/editor/src/builder/index.tsindex fc8cfd0d1..e48d78616 100644--- a/editor/src/builder/index.ts+++ b/editor/src/builder/index.ts@@ -5,8 +5,7 @@export { BuildSettingsDialog, showBuildSettingsDialog } from './BuildSettingsDialog';export { BuildService, type BuildResult, type BuildContext, type BuildOptions } from './BuildService';-export { PlayableBuilder } from './PlayableBuilder';-export { WeChatBuilder } from './WeChatBuilder';+export { buildArtifact, initializeEsbuild, createBuildVirtualFsPlugin, type SdkModuleLoader } from './ArtifactBuilder';export { BuildCache, type BuildCacheData, type FileHash, type FileChangeResult } from './BuildCache';export { BuildProgressReporter, formatDuration, formatSize, type BuildProgress, type BuildLogEntry, type BuildPhase, type LogLevel } from './BuildProgress';@@ -18,5 +17,9 @@ export { BuildHistory, formatBuildTime, formatBuildDuration, getBuildStatusIcon,export { BUILD_TEMPLATES, getTemplates, getTemplatesByPlatform, getTemplate, createConfigFromTemplate, applyTemplateToConfig, getTemplateIconSvg, type BuildTemplate } from './BuildTemplates';export { BatchBuilder, ParallelBatchBuilder, type BatchBuildResult, type ConfigBuildResult, type BatchBuildProgress } from './BatchBuilder';export { AssetExportConfigService, AssetReferenceCollector, BuildAssetCollector, type FolderExportMode, type AssetExportConfig } from './AssetCollector';+export { AssetDependencyAnalyzer, collectReferencedAssets, registerRefScanner, type AssetRefScanner, type DependencyGraph } from '../asset/AssetDependencyAnalyzer';+export { type PlatformEmitter, type BuildArtifact } from './PlatformEmitter';+export { PlayableEmitter } from './PlayableEmitter';+export { WeChatEmitter } from './WeChatEmitter';export { TextureAtlasPacker, type AtlasFrame, type AtlasPage, type AtlasResult } from './TextureAtlas';-export { AssetLibrary, getAssetLibrary, resetAssetLibrary, isUUID } from '../asset/AssetLibrary';+export { AssetDatabase, AssetDatabase as AssetLibrary, getAssetDatabase, getAssetDatabase as getAssetLibrary, resetAssetDatabase, resetAssetDatabase as resetAssetLibrary, isUUID } from '../asset/AssetDatabase';diff --git a/editor/src/math/Transform.ts b/editor/src/math/Transform.tsindex 643cabd29..3afcd691f 100644--- a/editor/src/math/Transform.ts+++ b/editor/src/math/Transform.ts@@ -3,6 +3,8 @@* @brief Math utilities for transform calculations*/+import { computeUIRectLayout, type LayoutRect } from 'esengine';+// =============================================================================// Types// =============================================================================@@ -194,14 +196,20 @@ export function getLocalTransformFromEntity(entity: EntityDataLike): Transform {}export interface UIRectLike {+ anchorMin: { x: number; y: number };+ anchorMax: { x: number; y: number };+ offsetMin: { x: number; y: number };+ offsetMax: { x: number; y: number };size: { x: number; y: number };- anchor: { x: number; y: number };pivot: { x: number; y: number };}const DEFAULT_UIRECT: UIRectLike = {+ anchorMin: { x: 0.5, y: 0.5 },+ anchorMax: { x: 0.5, y: 0.5 },+ offsetMin: { x: 0, y: 0 },+ offsetMax: { x: 0, y: 0 },size: { x: 100, y: 100 },- anchor: { x: 0.5, y: 0.5 },pivot: { x: 0.5, y: 0.5 },};@@ -209,10 +217,21 @@ export function getUIRectFromEntity(entity: EntityDataLike): UIRectLike | null {const comp = entity.components.find(c => c.type === 'UIRect');if (!comp) return null;+ const data = comp.data as Record<string, any>;+ let anchorMin = data.anchorMin as { x: number; y: number } | undefined;+ let anchorMax = data.anchorMax as { x: number; y: number } | undefined;+ if (!anchorMin && data.anchor) {+ anchorMin = data.anchor as { x: number; y: number };+ anchorMax = { ...anchorMin };+ }+return {- size: (comp.data.size as { x: number; y: number }) ?? DEFAULT_UIRECT.size,- anchor: (comp.data.anchor as { x: number; y: number }) ?? DEFAULT_UIRECT.anchor,- pivot: (comp.data.pivot as { x: number; y: number }) ?? DEFAULT_UIRECT.pivot,+ anchorMin: anchorMin ?? DEFAULT_UIRECT.anchorMin,+ anchorMax: anchorMax ?? DEFAULT_UIRECT.anchorMax,+ offsetMin: (data.offsetMin as { x: number; y: number }) ?? DEFAULT_UIRECT.offsetMin,+ offsetMax: (data.offsetMax as { x: number; y: number }) ?? DEFAULT_UIRECT.offsetMax,+ size: (data.size as { x: number; y: number }) ?? DEFAULT_UIRECT.size,+ pivot: (data.pivot as { x: number; y: number }) ?? DEFAULT_UIRECT.pivot,};}@@ -236,6 +255,116 @@ export function getEntitySize(entity: EntityDataLike): { x: number; y: number }return { x: 100, y: 100 };}+// =============================================================================+// ScreenSpace Layout Helpers+// =============================================================================++export function isInScreenSpaceHierarchy(+ entity: EntityDataLike,+ getParentEntity: (id: number) => EntityDataLike | undefined,+): boolean {+ if (entity.components.some(c => c.type === 'ScreenSpace')) return true;+ let parentId = entity.parent;+ while (parentId !== null) {+ const parent = getParentEntity(parentId);+ if (!parent) break;+ if (parent.components.some(c => c.type === 'ScreenSpace')) return true;+ parentId = parent.parent;+ }+ return false;+}++export function findCanvasWorldRect(allEntities: EntityDataLike[]): LayoutRect | null {+ let designResolution: { x: number; y: number } | null = null;+ let cameraPos = { x: 0, y: 0 };++ for (const e of allEntities) {+ const canvas = e.components.find(c => c.type === 'Canvas');+ if (canvas?.data?.designResolution) {+ designResolution = canvas.data.designResolution as { x: number; y: number };+ }+ const camera = e.components.find(c => c.type === 'Camera');+ if (camera) {+ const lt = e.components.find(c => c.type === 'LocalTransform');+ if (lt?.data?.position) {+ const pos = lt.data.position as { x: number; y: number };+ cameraPos = { x: pos.x, y: pos.y };+ }+ }+ }++ if (!designResolution) return null;++ const halfW = designResolution.x / 2;+ const halfH = designResolution.y / 2;+ return {+ left: cameraPos.x - halfW,+ bottom: cameraPos.y - halfH,+ right: cameraPos.x + halfW,+ top: cameraPos.y + halfH,+ };+}++function computeScreenSpaceTransform(+ entity: EntityDataLike,+ getParentEntity: (id: number) => EntityDataLike | undefined,+ canvasRect: LayoutRect,+): Transform {+ const localTransform = getLocalTransformFromEntity(entity);++ const path: EntityDataLike[] = [];+ let cur: EntityDataLike | undefined = entity;+ while (cur) {+ path.unshift(cur);+ if (cur.components.some(c => c.type === 'ScreenSpace')) break;+ if (cur.parent === null) break;+ cur = getParentEntity(cur.parent);+ }++ let parentRect = canvasRect;+ let parentCenterX = (canvasRect.left + canvasRect.right) * 0.5;+ let parentCenterY = (canvasRect.bottom + canvasRect.top) * 0.5;++ let resultX = 0;+ let resultY = 0;++ for (let i = 0; i < path.length; i++) {+ const node = path[i];+ const uiRect = getUIRectFromEntity(node);+ if (!uiRect) {+ const lt = getLocalTransformFromEntity(node);+ resultX = lt.position.x;+ resultY = lt.position.y;+ continue;+ }++ const layout = computeUIRectLayout(+ uiRect.anchorMin, uiRect.anchorMax,+ uiRect.offsetMin, uiRect.offsetMax,+ uiRect.size, parentRect,+ );++ const isRoot = i === 0;+ if (isRoot) {+ resultX = layout.centerX;+ resultY = layout.centerY;+ } else {+ resultX = layout.centerX - parentCenterX;+ resultY = layout.centerY - parentCenterY;+ }++ parentRect = layout.rect;+ parentCenterX = layout.centerX;+ parentCenterY = layout.centerY;+ }++ return {+ position: { x: resultX, y: resultY, z: localTransform.position.z },+ rotation: localTransform.rotation,+ scale: localTransform.scale,+ };+}+// =============================================================================// UIRect-Adjusted Transform// =============================================================================@@ -267,8 +396,16 @@ export function getParentSizeForEntity(export function computeAdjustedLocalTransform(entity: EntityDataLike,- getParentEntity: (id: number) => EntityDataLike | undefined+ getParentEntity: (id: number) => EntityDataLike | undefined,+ allEntities?: EntityDataLike[],): Transform {+ if (allEntities && isInScreenSpaceHierarchy(entity, getParentEntity)) {+ const canvasRect = findCanvasWorldRect(allEntities);+ if (canvasRect) {+ return computeScreenSpaceTransform(entity, getParentEntity, canvasRect);+ }+ }+const localTransform = getLocalTransformFromEntity(entity);const uiRect = getUIRectFromEntity(entity);const size = getEntitySize(entity);@@ -277,9 +414,11 @@ export function computeAdjustedLocalTransform(if (uiRect) {const parentSize = getParentSizeForEntity(entity, getParentEntity);+ const anchorX = (uiRect.anchorMin.x + uiRect.anchorMax.x) * 0.5;+ const anchorY = (uiRect.anchorMin.y + uiRect.anchorMax.y) * 0.5;- adjustedPosition.x += (uiRect.anchor.x - 0.5) * parentSize.x;- adjustedPosition.y += (uiRect.anchor.y - 0.5) * parentSize.y;+ adjustedPosition.x += (anchorX - 0.5) * parentSize.x;+ adjustedPosition.y += (anchorY - 0.5) * parentSize.y;adjustedPosition.x += (0.5 - uiRect.pivot.x) * size.x;adjustedPosition.y += (0.5 - uiRect.pivot.y) * size.y;diff --git a/editor/src/panels/SceneViewPanel.ts b/editor/src/panels/SceneViewPanel.tsindex 7635abc9a..e3bcb95af 100644--- a/editor/src/panels/SceneViewPanel.ts+++ b/editor/src/panels/SceneViewPanel.ts@@ -14,7 +14,7 @@ import { getDefaultComponentData } from '../schemas/ComponentSchemas';import { getGlobalPathResolver } from '../asset';import { icons } from '../utils/icons';import { EditorSceneRenderer } from '../renderer/EditorSceneRenderer';-import { quatToEuler, eulerToQuat } from '../math/Transform';+import { quatToEuler, eulerToQuat, findCanvasWorldRect } from '../math/Transform';import { getEntityBounds } from '../bounds';import { GizmoManager, getAllGizmos } from '../gizmos';import type { GizmoContext } from '../gizmos';@@ -862,6 +862,7 @@ export class SceneViewPanel {this.drawGrid(ctx, w, h);this.drawCameraFrustums(ctx);+ this.drawScreenSpaceBounds(ctx);if (getSettingsValue<boolean>('scene.showColliders')) {this.colliderOverlay_.drawAll({@@ -1067,6 +1068,46 @@ export class SceneViewPanel {}}+ private drawScreenSpaceBounds(ctx: CanvasRenderingContext2D): void {+ const hasScreenSpace = this.store_.scene.entities.some(+ e => e.components.some(c => c.type === 'ScreenSpace')+ );+ if (!hasScreenSpace) return;++ const canvasRect = findCanvasWorldRect(this.store_.scene.entities);+ if (!canvasRect) return;++ const x = canvasRect.left;+ const y = -(canvasRect.top);+ const w = canvasRect.right - canvasRect.left;+ const h = canvasRect.top - canvasRect.bottom;++ ctx.save();++ ctx.strokeStyle = '#ffb400';+ ctx.lineWidth = 2 / this.zoom_;+ ctx.setLineDash([6 / this.zoom_, 4 / this.zoom_]);+ ctx.strokeRect(x, y, w, h);++ ctx.fillStyle = 'rgba(255, 180, 0, 0.04)';+ ctx.fillRect(x, y, w, h);++ ctx.setLineDash([]);+ const fontSize = 11 / this.zoom_;+ ctx.font = `bold ${fontSize}px system-ui, sans-serif`;+ ctx.textAlign = 'left';+ ctx.textBaseline = 'bottom';+ const label = 'ScreenSpace';+ const pad = 2 / this.zoom_;+ const metrics = ctx.measureText(label);+ ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';+ ctx.fillRect(x, y - fontSize - pad * 2, metrics.width + pad * 2, fontSize + pad * 2);+ ctx.fillStyle = '#ffb400';+ ctx.fillText(label, x + pad, y - pad);++ ctx.restore();+ }+private drawCameraIcon(ctx: CanvasRenderingContext2D, color: string): void {const s = 1 / this.zoom_;const bodyW = 16 * s;@@ -1183,6 +1224,7 @@ export class SceneViewPanel {}this.drawCameraFrustums(ctx);+ this.drawScreenSpaceBounds(ctx);if (getSettingsValue<boolean>('scene.showColliders')) {this.colliderOverlay_.drawAll({diff --git a/editor/src/scene/EditorSceneManager.ts b/editor/src/scene/EditorSceneManager.tsindex a0c7b435b..9950bcf43 100644--- a/editor/src/scene/EditorSceneManager.ts+++ b/editor/src/scene/EditorSceneManager.ts@@ -423,6 +423,15 @@ export class EditorSceneManager {// Component Sync (Editor-specific logic)// =========================================================================+ syncScreenSpaceDescendants(entityId: number): void {+ const entityData = this.entityDataMap_.get(entityId);+ if (!entityData) return;+ for (const childId of entityData.children) {+ this.syncEntityTransform(childId);+ this.syncScreenSpaceDescendants(childId);+ }+ }+private syncTransform(entity: Entity, data: any, entityId: number): void {if (this.world_.has(entity, LocalTransform)) {this.world_.remove(entity, LocalTransform);@@ -431,8 +440,9 @@ export class EditorSceneManager {const entityData = this.entityDataMap_.get(entityId);if (!entityData) return;+ const allEntities = Array.from(this.entityDataMap_.values());const adjustedLocal = computeAdjustedLocalTransform(- entityData, (id) => this.entityDataMap_.get(id)+ entityData, (id) => this.entityDataMap_.get(id), allEntities,);this.world_.insert(entity, LocalTransform, {diff --git a/editor/src/sync/RuntimeSyncService.ts b/editor/src/sync/RuntimeSyncService.tsindex a6e86f268..fb823a0c7 100644--- a/editor/src/sync/RuntimeSyncService.ts+++ b/editor/src/sync/RuntimeSyncService.ts@@ -69,6 +69,11 @@ export class RuntimeSyncService {this.sceneManager_.syncEntityTransform(event.entity);}+ if (event.componentType === 'UIRect' || event.componentType === 'ScreenSpace') {+ this.sceneManager_.syncEntityTransform(event.entity);+ this.sceneManager_.syncScreenSpaceDescendants(event.entity);+ }+this.scheduleEntityUpdate(event.entity);if (event.componentType === 'Canvas') {diff --git a/sdk/src/app.ts b/sdk/src/app.tsindex ce89ca70b..6181b173c 100644--- a/sdk/src/app.ts+++ b/sdk/src/app.ts@@ -9,6 +9,9 @@ import { ResourceStorage, Time, TimeData, type ResourceDef } from './resource';import type { ESEngineModule, CppRegistry } from './wasm';import { textPlugin } from './ui/TextPlugin';import { uiMaskPlugin } from './ui/UIMaskPlugin';+import { uiInteractionPlugin } from './ui/UIInteractionPlugin';+import { uiLayoutPlugin } from './ui/UILayoutPlugin';+import { UICameraInfo } from './ui/UICameraInfo';import { inputPlugin } from './input';import { assetPlugin } from './asset';import { initDrawAPI, shutdownDrawAPI } from './draw';@@ -274,6 +277,14 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): Aheight: window.innerHeight * (window.devicePixelRatio || 1)}));+ app.insertResource(UICameraInfo, {+ viewProjection: new Float32Array(16),+ vpX: 0, vpY: 0, vpW: 0, vpH: 0,+ screenW: 0, screenH: 0,+ worldLeft: 0, worldBottom: 0, worldRight: 0, worldTop: 0,+ valid: false,+ });+const renderSystem: SystemDef = {_id: Symbol('RenderSystem'),_name: 'RenderSystem',@@ -296,6 +307,27 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): A}const cameras = collectCameras(module, cppRegistry, width, height);++ const uiCam = app.getResource(UICameraInfo);+ if (cameras.length > 0) {+ const cam = cameras[0];+ const vr = cam.viewportRect;+ uiCam.viewProjection.set(cam.viewProjection);+ uiCam.vpX = Math.round(vr.x * width);+ uiCam.vpY = Math.round((1 - vr.y - vr.h) * height);+ uiCam.vpW = Math.round(vr.w * width);+ uiCam.vpH = Math.round(vr.h * height);+ uiCam.screenW = width;+ uiCam.screenH = height;+ uiCam.worldLeft = cam.cameraX - cam.halfW;+ uiCam.worldRight = cam.cameraX + cam.halfW;+ uiCam.worldBottom = cam.cameraY - cam.halfH;+ uiCam.worldTop = cam.cameraY + cam.halfH;+ uiCam.valid = true;+ } else {+ uiCam.valid = false;+ }+if (cameras.length === 0) {pipeline.render({registry: { _cpp: cppRegistry },@@ -328,6 +360,8 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): Aapp.addPlugin(inputPlugin);app.addPlugin(textPlugin);app.addPlugin(uiMaskPlugin);+ app.addPlugin(uiLayoutPlugin);+ app.addPlugin(uiInteractionPlugin);return app;}@@ -399,6 +433,10 @@ interface CameraInfo {viewportRect: { x: number; y: number; w: number; h: number };clearFlags: number;priority: number;+ halfW: number;+ halfH: number;+ cameraX: number;+ cameraY: number;}function collectCameras(module: ESEngineModule, registry: CppRegistry, width: number, height: number): CameraInfo[] {@@ -436,21 +474,23 @@ function collectCameras(module: ESEngineModule, registry: CppRegistry, width: nu};const aspect = (vr.w * width) / (vr.h * height);let projection: Float32Array;+ let camHalfW = 0;+ let camHalfH = 0;if (camera.projectionType === 1) {- let halfH = camera.orthoSize;+ camHalfH = camera.orthoSize;if (canvas) {const baseOrthoSize = canvas.designResolution.y / 2;const designAspect = canvas.designResolution.x / canvas.designResolution.y;- halfH = computeEffectiveOrthoSize(+ camHalfH = computeEffectiveOrthoSize(baseOrthoSize, designAspect, aspect,canvas.scaleMode, canvas.matchWidthOrHeight,);}- const halfW = halfH * aspect;- projection = ortho(-halfW, halfW, -halfH, halfH, -camera.farPlane, camera.farPlane);+ camHalfW = camHalfH * aspect;+ projection = ortho(-camHalfW, camHalfW, -camHalfH, camHalfH, -camera.farPlane, camera.farPlane);} else {projection = perspective(camera.fov * Math.PI / 180,@@ -467,6 +507,10 @@ function collectCameras(module: ESEngineModule, registry: CppRegistry, width: nuviewportRect: vr,clearFlags: camera.clearFlags,priority: camera.priority,+ halfW: camHalfW,+ halfH: camHalfH,+ cameraX: transform.position.x,+ cameraY: transform.position.y,});}diff --git a/sdk/src/asset/AssetServer.ts b/sdk/src/asset/AssetServer.tsindex 567cf03c3..19b58f8ce 100644--- a/sdk/src/asset/AssetServer.ts+++ b/sdk/src/asset/AssetServer.ts@@ -64,6 +64,25 @@ export interface AssetBundle {binary: Map<string, ArrayBuffer>;}+export interface AddressableManifestAsset {+ path: string;+ address?: string;+ type: string;+ size: number;+ labels: string[];+}++export interface AddressableManifestGroup {+ bundleMode: string;+ labels: string[];+ assets: Record<string, AddressableManifestAsset>;+}++export interface AddressableManifest {+ version: '2.0';+ groups: Record<string, AddressableManifestGroup>;+}+// =============================================================================// AssetServer// =============================================================================@@ -84,6 +103,10 @@ export class AssetServer {private ctx_: CanvasRenderingContext2D;private fontCache_ = new AsyncCache<FontHandle>();private embedded_ = new Map<string, string>();+ private addressableManifest_: AddressableManifest | null = null;+ private addressIndex_ = new Map<string, AddressableManifestAsset>();+ private labelIndex_ = new Map<string, AddressableManifestAsset[]>();+ private groupAssets_ = new Map<string, AddressableManifestAsset[]>();constructor(module: ESEngineModule) {this.module_ = module;@@ -433,6 +456,116 @@ export class AssetServer {return bundle;}+ // =========================================================================+ // Addressable Assets+ // =========================================================================++ setAddressableManifest(manifest: AddressableManifest): void {+ this.addressableManifest_ = manifest;+ this.addressIndex_.clear();+ this.labelIndex_.clear();+ this.groupAssets_.clear();++ for (const [groupName, group] of Object.entries(manifest.groups)) {+ const groupList: AddressableManifestAsset[] = [];+ for (const asset of Object.values(group.assets)) {+ groupList.push(asset);+ if (asset.address) {+ this.addressIndex_.set(asset.address, asset);+ }+ for (const label of asset.labels) {+ let list = this.labelIndex_.get(label);+ if (!list) {+ list = [];+ this.labelIndex_.set(label, list);+ }+ list.push(asset);+ }+ }+ this.groupAssets_.set(groupName, groupList);+ }+ }++ async loadByAddress(address: string): Promise<TextureInfo | LoadedMaterial | unknown> {+ const asset = this.addressIndex_.get(address);+ if (!asset) {+ throw new Error(`No asset found with address: ${address}`);+ }+ return this.loadAddressableAsset(asset);+ }++ async loadByLabel(label: string): Promise<AssetBundle> {+ const assets = this.labelIndex_.get(label) ?? [];+ return this.loadAddressableAssets(assets);+ }++ async loadGroup(groupName: string): Promise<AssetBundle> {+ const assets = this.groupAssets_.get(groupName) ?? [];+ return this.loadAddressableAssets(assets);+ }++ private async loadAddressableAsset(asset: AddressableManifestAsset): Promise<TextureInfo | LoadedMaterial | unknown> {+ switch (asset.type) {+ case 'texture':+ return this.loadTexture(asset.path);+ case 'material':+ return this.loadMaterial(asset.path);+ case 'json':+ return this.loadJson(asset.path);+ case 'text':+ return this.loadText(asset.path);+ case 'binary':+ return this.loadBinary(asset.path);+ default:+ return this.loadBinary(asset.path);+ }+ }++ private async loadAddressableAssets(assets: AddressableManifestAsset[]): Promise<AssetBundle> {+ const bundle: AssetBundle = {+ textures: new Map(),+ materials: new Map(),+ spine: new Map(),+ json: new Map(),+ text: new Map(),+ binary: new Map(),+ };++ const promises: Promise<void>[] = [];+ for (const asset of assets) {+ switch (asset.type) {+ case 'texture':+ promises.push(+ this.loadTexture(asset.path).then(info => { bundle.textures.set(asset.path, info); })+ );+ break;+ case 'material':+ promises.push(+ this.loadMaterial(asset.path).then(mat => { bundle.materials.set(asset.path, mat); })+ );+ break;+ case 'json':+ promises.push(+ this.loadJson(asset.path).then(data => { bundle.json.set(asset.path, data); })+ );+ break;+ case 'text':+ promises.push(+ this.loadText(asset.path).then(data => { bundle.text.set(asset.path, data); })+ );+ break;+ default:+ promises.push(+ this.loadBinary(asset.path).then(data => { bundle.binary.set(asset.path, data); })+ );+ break;+ }+ }++ await Promise.all(promises);+ return bundle;+ }+// =========================================================================// Private - Texture// =========================================================================diff --git a/sdk/src/asset/index.ts b/sdk/src/asset/index.tsindex 1b4ed93bb..34ad8d17d 100644--- a/sdk/src/asset/index.ts+++ b/sdk/src/asset/index.ts@@ -12,6 +12,9 @@ export {type FileLoadOptions,type AssetManifest,type AssetBundle,+ type AddressableManifest,+ type AddressableManifestGroup,+ type AddressableManifestAsset,} from './AssetServer';export { AsyncCache } from './AsyncCache';export { Assets, AssetPlugin, assetPlugin, type AssetsData } from './AssetPlugin';diff --git a/sdk/src/core.ts b/sdk/src/core.tsindex cf6696db3..17c2bf35e 100644--- a/sdk/src/core.ts+++ b/sdk/src/core.ts@@ -182,10 +182,38 @@ export {TextRenderer,TextPlugin,textPlugin,+ worldRectToScreen,+ intersectRects,+ invertMatrix4,+ screenToWorld,+ pointInWorldRect,+ Interactable,+ UIInteraction,+ Button,+ ButtonState,+ UIEvents,+ UIEventQueue,+ UICameraInfo,+ ScreenSpace,+ computeUIRectLayout,+ UILayoutPlugin,+ uiLayoutPlugin,+ UIInteractionPlugin,+ uiInteractionPlugin,type TextData,type UIRectData,type UIMaskData,type TextRenderResult,+ type ScreenRect,+ type InteractableData,+ type UIInteractionData,+ type ButtonTransition,+ type ButtonData,+ type UIEvent,+ type UIEventType,+ type UICameraData,+ type LayoutRect,+ type LayoutResult,} from './ui';// =============================================================================@@ -207,6 +235,9 @@ export {type FileLoadOptions,type AssetManifest,type AssetBundle,+ type AddressableManifest,+ type AddressableManifestGroup,+ type AddressableManifestAsset,type AssetsData,type LoadedMaterial,type ShaderLoader,diff --git a/sdk/src/scene.ts b/sdk/src/scene.tsindex e25671274..799dff5d1 100644--- a/sdk/src/scene.ts+++ b/sdk/src/scene.ts@@ -250,9 +250,16 @@ export function loadComponent(world: World, entity: Entity, compData: SceneCompocase 'SpineAnimation':world.insert(entity, SpineAnimation, data as SpineAnimationData);break;- case 'UIRect':- world.insert(entity, UIRect, data as UIRectData);+ case 'UIRect': {+ const rectData = data as Record<string, any>;+ if (rectData.anchor && !rectData.anchorMin) {+ rectData.anchorMin = { ...rectData.anchor };+ rectData.anchorMax = { ...rectData.anchor };+ delete rectData.anchor;+ }+ world.insert(entity, UIRect, rectData as UIRectData);break;+ }case 'UIMask':world.insert(entity, UIMask, data as UIMaskData);break;diff --git a/sdk/src/ui/Button.ts b/sdk/src/ui/Button.tsnew file mode 100644index 000000000..fc34bbfb8--- /dev/null+++ b/sdk/src/ui/Button.ts@@ -0,0 +1,26 @@+import { defineComponent } from '../component';+import type { Color } from '../types';++export enum ButtonState {+ Normal = 0,+ Hovered = 1,+ Pressed = 2,+ Disabled = 3,+}++export interface ButtonTransition {+ normalColor: Color;+ hoveredColor: Color;+ pressedColor: Color;+ disabledColor: Color;+}++export interface ButtonData {+ state: ButtonState;+ transition: ButtonTransition | null;+}++export const Button = defineComponent<ButtonData>('Button', {+ state: ButtonState.Normal,+ transition: null,+});diff --git a/sdk/src/ui/Interactable.ts b/sdk/src/ui/Interactable.tsnew file mode 100644index 000000000..cda049091--- /dev/null+++ b/sdk/src/ui/Interactable.ts@@ -0,0 +1,9 @@+import { defineComponent } from '../component';++export interface InteractableData {+ enabled: boolean;+}++export const Interactable = defineComponent<InteractableData>('Interactable', {+ enabled: true,+});diff --git a/sdk/src/ui/ScreenSpace.ts b/sdk/src/ui/ScreenSpace.tsnew file mode 100644index 000000000..2c5c9d240--- /dev/null+++ b/sdk/src/ui/ScreenSpace.ts@@ -0,0 +1,3 @@+import { defineTag } from '../component';++export const ScreenSpace = defineTag('ScreenSpace');diff --git a/sdk/src/ui/TextPlugin.ts b/sdk/src/ui/TextPlugin.tsindex 58a4083e5..93c8861ba 100644--- a/sdk/src/ui/TextPlugin.ts+++ b/sdk/src/ui/TextPlugin.ts@@ -39,10 +39,14 @@ export class TextPlugin implements Plugin {if (!world.has(entity, Sprite)) {world.insert(entity, Sprite, {texture: INVALID_TEXTURE,- size: { x: 0, y: 0 },color: { r: 1, g: 1, b: 1, a: 1 },- anchor: { x: 0.5, y: 0.5 },- flip: { x: false, y: false }+ size: { x: 0, y: 0 },+ uvOffset: { x: 0, y: 0 },+ uvScale: { x: 1, y: 1 },+ layer: 0,+ flipX: false,+ flipY: false,+ material: 0,});}diff --git a/sdk/src/ui/UICameraInfo.ts b/sdk/src/ui/UICameraInfo.tsnew file mode 100644index 000000000..7a5c3de8e--- /dev/null+++ b/sdk/src/ui/UICameraInfo.ts@@ -0,0 +1,24 @@+import { defineResource } from '../resource';++export interface UICameraData {+ viewProjection: Float32Array;+ vpX: number;+ vpY: number;+ vpW: number;+ vpH: number;+ screenW: number;+ screenH: number;+ worldLeft: number;+ worldBottom: number;+ worldRight: number;+ worldTop: number;+ valid: boolean;+}++export const UICameraInfo = defineResource<UICameraData>({+ viewProjection: new Float32Array(16),+ vpX: 0, vpY: 0, vpW: 0, vpH: 0,+ screenW: 0, screenH: 0,+ worldLeft: 0, worldBottom: 0, worldRight: 0, worldTop: 0,+ valid: false,+}, 'UICameraInfo');diff --git a/sdk/src/ui/UIEvents.ts b/sdk/src/ui/UIEvents.tsnew file mode 100644index 000000000..8cb4a2c1a--- /dev/null+++ b/sdk/src/ui/UIEvents.ts@@ -0,0 +1,33 @@+import { defineResource } from '../resource';+import type { Entity } from '../types';++export type UIEventType = 'click' | 'press' | 'release' | 'hover_enter' | 'hover_exit';++export interface UIEvent {+ entity: Entity;+ type: UIEventType;+}++export class UIEventQueue {+ private events_: UIEvent[] = [];++ emit(entity: Entity, type: UIEventType): void {+ this.events_.push({ entity, type });+ }++ drain(): UIEvent[] {+ const events = this.events_;+ this.events_ = [];+ return events;+ }++ query(type: UIEventType): UIEvent[] {+ return this.events_.filter(e => e.type === type);+ }++ hasEvent(entity: Entity, type: UIEventType): boolean {+ return this.events_.some(e => e.entity === entity && e.type === type);+ }+}++export const UIEvents = defineResource<UIEventQueue>(new UIEventQueue(), 'UIEvents');diff --git a/sdk/src/ui/UIInteraction.ts b/sdk/src/ui/UIInteraction.tsnew file mode 100644index 000000000..ce5a2eea3--- /dev/null+++ b/sdk/src/ui/UIInteraction.ts@@ -0,0 +1,15 @@+import { defineComponent } from '../component';++export interface UIInteractionData {+ hovered: boolean;+ pressed: boolean;+ justPressed: boolean;+ justReleased: boolean;+}++export const UIInteraction = defineComponent<UIInteractionData>('UIInteraction', {+ hovered: false,+ pressed: false,+ justPressed: false,+ justReleased: false,+});diff --git a/sdk/src/ui/UIInteractionPlugin.ts b/sdk/src/ui/UIInteractionPlugin.tsnew file mode 100644index 000000000..fa0d667db--- /dev/null+++ b/sdk/src/ui/UIInteractionPlugin.ts@@ -0,0 +1,183 @@+import type { App, Plugin } from '../app';+import { WorldTransform, Sprite } from '../component';+import type { WorldTransformData, SpriteData } from '../component';+import { defineSystem, Schedule } from '../system';+import { Res } from '../resource';+import { Input } from '../input';+import type { InputState } from '../input';+import type { Entity } from '../types';+import type { World } from '../world';+import { Interactable } from './Interactable';+import type { InteractableData } from './Interactable';+import { UIInteraction } from './UIInteraction';+import type { UIInteractionData } from './UIInteraction';+import { UIRect } from './UIRect';+import type { UIRectData } from './UIRect';+import { Button, ButtonState } from './Button';+import type { ButtonData } from './Button';+import { UIEvents, UIEventQueue } from './UIEvents';+import { UICameraInfo } from './UICameraInfo';+import type { UICameraData } from './UICameraInfo';+import { invertMatrix4, screenToWorld, pointInWorldRect } from './uiMath';++const _invVP = new Float32Array(16);++export class UIInteractionPlugin implements Plugin {+ build(app: App): void {+ const world = app.world;+ const events = new UIEventQueue();+ app.insertResource(UIEvents, events);++ let hoveredEntity: Entity | null = null;+ let pressedEntity: Entity | null = null;++ // -----------------------------------------------------------------+ // PreUpdate: Hit Testing & Interaction State+ // -----------------------------------------------------------------+ app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(+ [Res(Input), Res(UICameraInfo)],+ (input: InputState, camera: UICameraData) => {+ events.drain();++ const interactionEntities = world.getEntitiesWithComponents([UIInteraction]);+ for (const entity of interactionEntities) {+ const interaction = world.get(entity, UIInteraction) as UIInteractionData;+ interaction.justPressed = false;+ interaction.justReleased = false;+ }++ if (!camera.valid) return;++ const dpr = typeof window !== 'undefined' ? (window.devicePixelRatio || 1) : 1;+ const mouseGLX = input.mouseX * dpr;+ const mouseGLY = camera.screenH - input.mouseY * dpr;++ invertMatrix4(camera.viewProjection, _invVP);+ const worldMouse = screenToWorld(+ mouseGLX, mouseGLY, _invVP,+ camera.vpX, camera.vpY, camera.vpW, camera.vpH,+ );++ const interactableEntities = world.getEntitiesWithComponents(+ [Interactable, UIRect, WorldTransform]+ );++ let hitEntity: Entity | null = null;+ let hitLayer = -Infinity;++ for (const entity of interactableEntities) {+ if (!world.has(entity, UIInteraction)) {+ world.insert(entity, UIInteraction);+ }++ const interactable = world.get(entity, Interactable) as InteractableData;+ if (!interactable.enabled) continue;++ const wt = world.get(entity, WorldTransform) as WorldTransformData;+ const rect = world.get(entity, UIRect) as UIRectData;+ const worldW = rect.size.x * wt.scale.x;+ const worldH = rect.size.y * wt.scale.y;++ if (pointInWorldRect(+ worldMouse.x, worldMouse.y,+ wt.position.x, wt.position.y,+ worldW, worldH,+ rect.pivot.x, rect.pivot.y,+ )) {+ let layer = 0;+ if (world.has(entity, Sprite)) {+ layer = (world.get(entity, Sprite) as SpriteData).layer;+ }+ if (layer >= hitLayer) {+ hitLayer = layer;+ hitEntity = entity;+ }+ }+ }++ if (hoveredEntity !== hitEntity) {+ if (hoveredEntity !== null && world.valid(hoveredEntity) && world.has(hoveredEntity, UIInteraction)) {+ const prev = world.get(hoveredEntity, UIInteraction) as UIInteractionData;+ prev.hovered = false;+ events.emit(hoveredEntity, 'hover_exit');+ }+ if (hitEntity !== null) {+ const curr = world.get(hitEntity, UIInteraction) as UIInteractionData;+ curr.hovered = true;+ events.emit(hitEntity, 'hover_enter');+ }+ hoveredEntity = hitEntity;+ }++ if (input.isMouseButtonPressed(0) && hitEntity !== null) {+ const interaction = world.get(hitEntity, UIInteraction) as UIInteractionData;+ interaction.pressed = true;+ interaction.justPressed = true;+ pressedEntity = hitEntity;+ events.emit(hitEntity, 'press');+ }++ if (input.isMouseButtonReleased(0) && pressedEntity !== null) {+ if (world.valid(pressedEntity) && world.has(pressedEntity, UIInteraction)) {+ const interaction = world.get(pressedEntity, UIInteraction) as UIInteractionData;+ interaction.pressed = false;+ interaction.justReleased = true;+ events.emit(pressedEntity, 'release');+ if (pressedEntity === hoveredEntity) {+ events.emit(pressedEntity, 'click');+ }+ }+ pressedEntity = null;+ }+ },+ { name: 'UIInteractionSystem' }+ ));++ // -----------------------------------------------------------------+ // Update: Button State+ // -----------------------------------------------------------------+ app.addSystemToSchedule(Schedule.Update, defineSystem(+ [],+ () => {+ const buttonEntities = world.getEntitiesWithComponents([Button]);+ for (const entity of buttonEntities) {+ if (!world.has(entity, Interactable)) {+ world.insert(entity, Interactable, { enabled: true });+ }+ if (!world.has(entity, UIInteraction)) continue;++ const interaction = world.get(entity, UIInteraction) as UIInteractionData;+ const button = world.get(entity, Button) as ButtonData;+ const interactable = world.get(entity, Interactable) as InteractableData;++ const prevState = button.state;++ if (!interactable.enabled) {+ button.state = ButtonState.Disabled;+ } else if (interaction.pressed) {+ button.state = ButtonState.Pressed;+ } else if (interaction.hovered) {+ button.state = ButtonState.Hovered;+ } else {+ button.state = ButtonState.Normal;+ }++ if (prevState !== button.state && button.transition && world.has(entity, Sprite)) {+ const sprite = world.get(entity, Sprite) as SpriteData;+ const t = button.transition;+ switch (button.state) {+ case ButtonState.Normal: sprite.color = { ...t.normalColor }; break;+ case ButtonState.Hovered: sprite.color = { ...t.hoveredColor }; break;+ case ButtonState.Pressed: sprite.color = { ...t.pressedColor }; break;+ case ButtonState.Disabled: sprite.color = { ...t.disabledColor }; break;+ }+ world.insert(entity, Sprite, sprite);+ }+ }+ },+ { name: 'ButtonSystem' }+ ));+ }+}++export const uiInteractionPlugin = new UIInteractionPlugin();diff --git a/sdk/src/ui/UILayoutPlugin.ts b/sdk/src/ui/UILayoutPlugin.tsnew file mode 100644index 000000000..47f9b470d--- /dev/null+++ b/sdk/src/ui/UILayoutPlugin.ts@@ -0,0 +1,88 @@+import type { App, Plugin } from '../app';+import { LocalTransform, Children } from '../component';+import type { LocalTransformData, ChildrenData } from '../component';+import { defineSystem, Schedule } from '../system';+import { Res } from '../resource';+import { UIRect } from './UIRect';+import type { UIRectData } from './UIRect';+import { ScreenSpace } from './ScreenSpace';+import { UICameraInfo } from './UICameraInfo';+import type { UICameraData } from './UICameraInfo';+import type { Entity } from '../types';+import type { World } from '../world';+import { computeUIRectLayout, type LayoutRect } from './uiLayout';++function layoutEntity(+ world: World,+ entity: Entity,+ parentRect: LayoutRect,+ parentCenterX: number,+ parentCenterY: number,+ isRoot: boolean,+): void {+ if (!world.has(entity, UIRect)) return;++ const rect = world.get(entity, UIRect) as UIRectData;++ const result = computeUIRectLayout(+ rect.anchorMin, rect.anchorMax,+ rect.offsetMin, rect.offsetMax,+ rect.size, parentRect,+ );++ if (rect.anchorMin.x !== rect.anchorMax.x || rect.anchorMin.y !== rect.anchorMax.y) {+ rect.size.x = result.width;+ rect.size.y = result.height;+ }++ const transform = world.get(entity, LocalTransform) as LocalTransformData;+ if (isRoot) {+ transform.position.x = result.centerX;+ transform.position.y = result.centerY;+ } else {+ transform.position.x = result.centerX - parentCenterX;+ transform.position.y = result.centerY - parentCenterY;+ }+ world.insert(entity, LocalTransform, transform);++ if (!world.has(entity, Children)) return;++ const children = world.get(entity, Children) as ChildrenData;+ if (!children || !children.entities) return;++ for (const child of children.entities) {+ if (world.valid(child)) {+ layoutEntity(world, child, result.rect, result.centerX, result.centerY, false);+ }+ }+}++export class UILayoutPlugin implements Plugin {+ build(app: App): void {+ const world = app.world;++ app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(+ [Res(UICameraInfo)],+ (camera: UICameraData) => {+ if (!camera.valid) return;++ const cameraRect: LayoutRect = {+ left: camera.worldLeft,+ bottom: camera.worldBottom,+ right: camera.worldRight,+ top: camera.worldTop,+ };+ const cameraCenterX = (cameraRect.left + cameraRect.right) * 0.5;+ const cameraCenterY = (cameraRect.bottom + cameraRect.top) * 0.5;++ const roots = world.getEntitiesWithComponents([ScreenSpace, UIRect, LocalTransform]);+ for (const root of roots) {+ layoutEntity(world, root, cameraRect, cameraCenterX, cameraCenterY, true);+ }+ },+ { name: 'UILayoutSystem' }+ ));+ }+}++export const uiLayoutPlugin = new UILayoutPlugin();diff --git a/sdk/src/ui/UIMaskPlugin.ts b/sdk/src/ui/UIMaskPlugin.tsindex b5332251e..d7094b7d3 100644--- a/sdk/src/ui/UIMaskPlugin.ts+++ b/sdk/src/ui/UIMaskPlugin.ts@@ -7,61 +7,7 @@ import { WorldTransform, Parent } from '../component';import type { WorldTransformData, ParentData } from '../component';import { UIMask, type UIMaskData } from './UIMask';import { UIRect, type UIRectData } from './UIRect';--interface ScreenRect {- x: number;- y: number;- w: number;- h: number;-}--function intersectRects(a: ScreenRect, b: ScreenRect): ScreenRect {- const x = Math.max(a.x, b.x);- const y = Math.max(a.y, b.y);- const r = Math.min(a.x + a.w, b.x + b.w);- const t = Math.min(a.y + a.h, b.y + b.h);- return { x, y, w: Math.max(0, r - x), h: Math.max(0, t - y) };-}--function worldRectToScreen(- worldX: number, worldY: number,- worldW: number, worldH: number,- pivotX: number, pivotY: number,- vp: Float32Array,- vpX: number, vpY: number, vpW: number, vpH: number-): ScreenRect {- const left = worldX - worldW * pivotX;- const right = worldX + worldW * (1 - pivotX);- const bottom = worldY - worldH * pivotY;- const top = worldY + worldH * (1 - pivotY);-- function toScreen(wx: number, wy: number): [number, number] {- const clipX = vp[0] * wx + vp[4] * wy + vp[12];- const clipY = vp[1] * wx + vp[5] * wy + vp[13];- const clipW = vp[3] * wx + vp[7] * wy + vp[15];- const ndcX = clipX / clipW;- const ndcY = clipY / clipW;- return [- vpX + (ndcX * 0.5 + 0.5) * vpW,- vpY + (ndcY * 0.5 + 0.5) * vpH,- ];- }-- const [px0, py0] = toScreen(left, bottom);- const [px1, py1] = toScreen(right, top);-- const minX = Math.min(px0, px1);- const maxX = Math.max(px0, px1);- const minY = Math.min(py0, py1);- const maxY = Math.max(py0, py1);-- return {- x: Math.round(minX),- y: Math.round(minY),- w: Math.round(maxX - minX),- h: Math.round(maxY - minY),- };-}+import { worldRectToScreen, intersectRects, type ScreenRect } from './uiMath';function computeMaskScreenRect(world: World, entity: Entity,@@ -77,7 +23,7 @@ function computeMaskScreenRect(return worldRectToScreen(wt.position.x, wt.position.y,worldW, worldH,- 0.5, 0.5,+ uiRect.pivot.x, uiRect.pivot.y,vp, vpX, vpY, vpW, vpH);}diff --git a/sdk/src/ui/UIRect.ts b/sdk/src/ui/UIRect.tsindex 2031130da..ca81fec75 100644--- a/sdk/src/ui/UIRect.ts+++ b/sdk/src/ui/UIRect.ts@@ -1,27 +1,20 @@-/**- * @file UIRect.ts- * @brief UIRect component for UI layout with anchor and pivot- */-import { defineComponent } from '../component';import type { Vec2 } from '../types';-// =============================================================================-// UIRect Component Data-// =============================================================================-export interface UIRectData {+ anchorMin: Vec2;+ anchorMax: Vec2;+ offsetMin: Vec2;+ offsetMax: Vec2;size: Vec2;- anchor: Vec2;pivot: Vec2;}-// =============================================================================-// UIRect Component Definition-// =============================================================================-export const UIRect = defineComponent<UIRectData>('UIRect', {+ anchorMin: { x: 0.5, y: 0.5 },+ anchorMax: { x: 0.5, y: 0.5 },+ offsetMin: { x: 0, y: 0 },+ offsetMax: { x: 0, y: 0 },size: { x: 100, y: 100 },- anchor: { x: 0.5, y: 0.5 },pivot: { x: 0.5, y: 0.5 },});diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.tsindex da55c516d..9749c2e0a 100644--- a/sdk/src/ui/index.ts+++ b/sdk/src/ui/index.ts@@ -42,3 +42,71 @@ export {uiMaskPlugin,createMaskProcessor,} from './UIMaskPlugin';++// UI Math Utilities+export {+ worldRectToScreen,+ intersectRects,+ invertMatrix4,+ screenToWorld,+ pointInWorldRect,+ type ScreenRect,+} from './uiMath';++// Interactable Component+export {+ Interactable,+ type InteractableData,+} from './Interactable';++// UIInteraction Component+export {+ UIInteraction,+ type UIInteractionData,+} from './UIInteraction';++// Button Component+export {+ Button,+ ButtonState,+ type ButtonTransition,+ type ButtonData,+} from './Button';++// UI Events+export {+ UIEvents,+ UIEventQueue,+ type UIEvent,+ type UIEventType,+} from './UIEvents';++// UI Camera Info Resource+export {+ UICameraInfo,+ type UICameraData,+} from './UICameraInfo';++// ScreenSpace Tag+export {+ ScreenSpace,+} from './ScreenSpace';++// UI Layout Calculation+export {+ computeUIRectLayout,+ type LayoutRect,+ type LayoutResult,+} from './uiLayout';++// UI Layout Plugin+export {+ UILayoutPlugin,+ uiLayoutPlugin,+} from './UILayoutPlugin';++// UI Interaction Plugin+export {+ UIInteractionPlugin,+ uiInteractionPlugin,+} from './UIInteractionPlugin';diff --git a/sdk/src/ui/uiLayout.ts b/sdk/src/ui/uiLayout.tsnew file mode 100644index 000000000..f1ffb5584--- /dev/null+++ b/sdk/src/ui/uiLayout.ts@@ -0,0 +1,65 @@+export interface LayoutRect {+ left: number;+ bottom: number;+ right: number;+ top: number;+}++export interface LayoutResult {+ centerX: number;+ centerY: number;+ width: number;+ height: number;+ rect: LayoutRect;+}++export function computeUIRectLayout(+ anchorMin: { x: number; y: number },+ anchorMax: { x: number; y: number },+ offsetMin: { x: number; y: number },+ offsetMax: { x: number; y: number },+ size: { x: number; y: number },+ parentRect: LayoutRect,+): LayoutResult {+ const parentW = parentRect.right - parentRect.left;+ const parentH = parentRect.top - parentRect.bottom;++ const aLeft = parentRect.left + anchorMin.x * parentW;+ const aRight = parentRect.left + anchorMax.x * parentW;+ const aBottom = parentRect.bottom + anchorMin.y * parentH;+ const aTop = parentRect.bottom + anchorMax.y * parentH;++ let myLeft: number;+ let myBottom: number;+ let myRight: number;+ let myTop: number;++ if (aLeft === aRight && aBottom === aTop) {+ const cx = aLeft + offsetMin.x;+ const cy = aBottom + offsetMin.y;+ const hw = size.x * 0.5;+ const hh = size.y * 0.5;+ myLeft = cx - hw;+ myBottom = cy - hh;+ myRight = cx + hw;+ myTop = cy + hh;+ } else {+ myLeft = aLeft + offsetMin.x;+ myBottom = aBottom + offsetMin.y;+ myRight = aRight + offsetMax.x;+ myTop = aTop + offsetMax.y;+ }++ const width = myRight - myLeft;+ const height = myTop - myBottom;+ const centerX = (myLeft + myRight) * 0.5;+ const centerY = (myBottom + myTop) * 0.5;++ return {+ centerX,+ centerY,+ width,+ height,+ rect: { left: myLeft, bottom: myBottom, right: myRight, top: myTop },+ };+}diff --git a/sdk/src/ui/uiMath.ts b/sdk/src/ui/uiMath.tsnew file mode 100644index 000000000..67928b482--- /dev/null+++ b/sdk/src/ui/uiMath.ts@@ -0,0 +1,127 @@+export interface ScreenRect {+ x: number;+ y: number;+ w: number;+ h: number;+}++export function intersectRects(a: ScreenRect, b: ScreenRect): ScreenRect {+ const x = Math.max(a.x, b.x);+ const y = Math.max(a.y, b.y);+ const r = Math.min(a.x + a.w, b.x + b.w);+ const t = Math.min(a.y + a.h, b.y + b.h);+ return { x, y, w: Math.max(0, r - x), h: Math.max(0, t - y) };+}++export function worldRectToScreen(+ worldX: number, worldY: number,+ worldW: number, worldH: number,+ pivotX: number, pivotY: number,+ vp: Float32Array,+ vpX: number, vpY: number, vpW: number, vpH: number+): ScreenRect {+ const left = worldX - worldW * pivotX;+ const right = worldX + worldW * (1 - pivotX);+ const bottom = worldY - worldH * pivotY;+ const top = worldY + worldH * (1 - pivotY);++ function toScreen(wx: number, wy: number): [number, number] {+ const clipX = vp[0] * wx + vp[4] * wy + vp[12];+ const clipY = vp[1] * wx + vp[5] * wy + vp[13];+ const clipW = vp[3] * wx + vp[7] * wy + vp[15];+ const ndcX = clipX / clipW;+ const ndcY = clipY / clipW;+ return [+ vpX + (ndcX * 0.5 + 0.5) * vpW,+ vpY + (ndcY * 0.5 + 0.5) * vpH,+ ];+ }++ const [px0, py0] = toScreen(left, bottom);+ const [px1, py1] = toScreen(right, top);++ const minX = Math.min(px0, px1);+ const maxX = Math.max(px0, px1);+ const minY = Math.min(py0, py1);+ const maxY = Math.max(py0, py1);++ return {+ x: Math.round(minX),+ y: Math.round(minY),+ w: Math.round(maxX - minX),+ h: Math.round(maxY - minY),+ };+}++export function invertMatrix4(m: Float32Array, result?: Float32Array): Float32Array {+ const out = result ?? new Float32Array(16);++ const a00 = m[0], a01 = m[1], a02 = m[2], a03 = m[3];+ const a10 = m[4], a11 = m[5], a12 = m[6], a13 = m[7];+ const a20 = m[8], a21 = m[9], a22 = m[10], a23 = m[11];+ const a30 = m[12], a31 = m[13], a32 = m[14], a33 = m[15];++ const b00 = a00 * a11 - a01 * a10;+ const b01 = a00 * a12 - a02 * a10;+ const b02 = a00 * a13 - a03 * a10;+ const b03 = a01 * a12 - a02 * a11;+ const b04 = a01 * a13 - a03 * a11;+ const b05 = a02 * a13 - a03 * a12;+ const b06 = a20 * a31 - a21 * a30;+ const b07 = a20 * a32 - a22 * a30;+ const b08 = a20 * a33 - a23 * a30;+ const b09 = a21 * a32 - a22 * a31;+ const b10 = a21 * a33 - a23 * a31;+ const b11 = a22 * a33 - a23 * a32;++ let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;+ if (Math.abs(det) < 1e-8) return out;+ det = 1.0 / det;++ out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;+ out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;+ out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;+ out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;+ out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;+ out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;+ out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;+ out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;+ out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;+ out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;+ out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;+ out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;+ out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;+ out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;+ out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;+ out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;++ return out;+}++export function screenToWorld(+ screenX: number, screenY: number,+ inverseVP: Float32Array,+ vpX: number, vpY: number, vpW: number, vpH: number+): { x: number; y: number } {+ const ndcX = ((screenX - vpX) / vpW) * 2 - 1;+ const ndcY = ((screenY - vpY) / vpH) * 2 - 1;++ const wx = inverseVP[0] * ndcX + inverseVP[4] * ndcY + inverseVP[12];+ const wy = inverseVP[1] * ndcX + inverseVP[5] * ndcY + inverseVP[13];+ const ww = inverseVP[3] * ndcX + inverseVP[7] * ndcY + inverseVP[15];++ return { x: wx / ww, y: wy / ww };+}++export function pointInWorldRect(+ px: number, py: number,+ worldX: number, worldY: number,+ worldW: number, worldH: number,+ pivotX: number, pivotY: number+): boolean {+ const left = worldX - worldW * pivotX;+ const right = worldX + worldW * (1 - pivotX);+ const bottom = worldY - worldH * pivotY;+ const top = worldY + worldH * (1 - pivotY);+ return px >= left && px <= right && py >= bottom && py <= top;+}